agentfootprint 7.13.0 → 7.14.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.
Files changed (57) hide show
  1. package/dist/core/Agent.js +79 -2
  2. package/dist/core/Agent.js.map +1 -1
  3. package/dist/esm/core/Agent.d.ts +47 -0
  4. package/dist/esm/core/Agent.js +79 -2
  5. package/dist/esm/core/Agent.js.map +1 -1
  6. package/dist/esm/hosting/envelope.d.ts +33 -0
  7. package/dist/esm/hosting/envelope.js +49 -0
  8. package/dist/esm/hosting/envelope.js.map +1 -0
  9. package/dist/esm/hosting/errors.d.ts +78 -0
  10. package/dist/esm/hosting/errors.js +119 -0
  11. package/dist/esm/hosting/errors.js.map +1 -0
  12. package/dist/esm/hosting/index.d.ts +53 -0
  13. package/dist/esm/hosting/index.js +52 -0
  14. package/dist/esm/hosting/index.js.map +1 -0
  15. package/dist/esm/hosting/memorySessions.d.ts +22 -0
  16. package/dist/esm/hosting/memorySessions.js +31 -0
  17. package/dist/esm/hosting/memorySessions.js.map +1 -0
  18. package/dist/esm/hosting/nodeHost.d.ts +64 -0
  19. package/dist/esm/hosting/nodeHost.js +245 -0
  20. package/dist/esm/hosting/nodeHost.js.map +1 -0
  21. package/dist/esm/hosting/standingAgent.d.ts +62 -0
  22. package/dist/esm/hosting/standingAgent.js +192 -0
  23. package/dist/esm/hosting/standingAgent.js.map +1 -0
  24. package/dist/esm/hosting/types.d.ts +206 -0
  25. package/dist/esm/hosting/types.js +21 -0
  26. package/dist/esm/hosting/types.js.map +1 -0
  27. package/dist/hosting/envelope.js +54 -0
  28. package/dist/hosting/envelope.js.map +1 -0
  29. package/dist/hosting/errors.js +126 -0
  30. package/dist/hosting/errors.js.map +1 -0
  31. package/dist/hosting/index.js +64 -0
  32. package/dist/hosting/index.js.map +1 -0
  33. package/dist/hosting/memorySessions.js +35 -0
  34. package/dist/hosting/memorySessions.js.map +1 -0
  35. package/dist/hosting/nodeHost.js +272 -0
  36. package/dist/hosting/nodeHost.js.map +1 -0
  37. package/dist/hosting/standingAgent.js +196 -0
  38. package/dist/hosting/standingAgent.js.map +1 -0
  39. package/dist/hosting/types.js +22 -0
  40. package/dist/hosting/types.js.map +1 -0
  41. package/dist/types/core/Agent.d.ts +47 -0
  42. package/dist/types/core/Agent.d.ts.map +1 -1
  43. package/dist/types/hosting/envelope.d.ts +34 -0
  44. package/dist/types/hosting/envelope.d.ts.map +1 -0
  45. package/dist/types/hosting/errors.d.ts +79 -0
  46. package/dist/types/hosting/errors.d.ts.map +1 -0
  47. package/dist/types/hosting/index.d.ts +54 -0
  48. package/dist/types/hosting/index.d.ts.map +1 -0
  49. package/dist/types/hosting/memorySessions.d.ts +23 -0
  50. package/dist/types/hosting/memorySessions.d.ts.map +1 -0
  51. package/dist/types/hosting/nodeHost.d.ts +65 -0
  52. package/dist/types/hosting/nodeHost.d.ts.map +1 -0
  53. package/dist/types/hosting/standingAgent.d.ts +63 -0
  54. package/dist/types/hosting/standingAgent.d.ts.map +1 -0
  55. package/dist/types/hosting/types.d.ts +207 -0
  56. package/dist/types/hosting/types.d.ts.map +1 -0
  57. package/package.json +14 -1
@@ -0,0 +1,272 @@
1
+ "use strict";
2
+ /**
3
+ * hosting/nodeHost — the plain HTTP adapter, built on `node:http` and nothing
4
+ * else.
5
+ *
6
+ * const host = nodeHost({ port: 8080 });
7
+ * const handle = await host.serve(async (request, reply) => {
8
+ * reply.complete(await answer(request.input));
9
+ * });
10
+ *
11
+ * Two routes: `POST /invoke` takes `{ input, sessionId? }` and answers
12
+ * `{ output }`; `GET /health` answers `{ status: 'ok' }`. Both paths are
13
+ * options, because the paths are the part most likely to be dictated to you by
14
+ * whatever is in front of the process — a load balancer, a container contract,
15
+ * a colleague's convention. A path is a deployment detail, so it is a knob
16
+ * here and absent from the port entirely.
17
+ *
18
+ * **Streaming is the caller's choice, not the server's.** Send
19
+ * `Accept: text/event-stream` and the reply is Server-Sent Events, one `chunk`
20
+ * event per `reply.emit(...)` then a final `complete`. Send anything else and
21
+ * the same handler produces one JSON body — it emits into a buffer that the
22
+ * completion settles. The handler cannot tell the difference and does not need
23
+ * to, which is the property `capabilities` exists to describe.
24
+ *
25
+ * Pattern: Adapter. Everything specific to HTTP — the paths, the JSON body
26
+ * shape, the status codes, the SSE framing — lives in this file. `types.ts`
27
+ * knows none of it, and a future adapter for somewhere else re-decides all of
28
+ * it without touching a port.
29
+ */
30
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
31
+ if (k2 === undefined) k2 = k;
32
+ var desc = Object.getOwnPropertyDescriptor(m, k);
33
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
34
+ desc = { enumerable: true, get: function() { return m[k]; } };
35
+ }
36
+ Object.defineProperty(o, k2, desc);
37
+ }) : (function(o, m, k, k2) {
38
+ if (k2 === undefined) k2 = k;
39
+ o[k2] = m[k];
40
+ }));
41
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
42
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
43
+ }) : function(o, v) {
44
+ o["default"] = v;
45
+ });
46
+ var __importStar = (this && this.__importStar) || function (mod) {
47
+ if (mod && mod.__esModule) return mod;
48
+ var result = {};
49
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
50
+ __setModuleDefault(result, mod);
51
+ return result;
52
+ };
53
+ Object.defineProperty(exports, "__esModule", { value: true });
54
+ exports.nodeHost = void 0;
55
+ const stream_js_1 = require("../stream.js");
56
+ const errors_js_1 = require("./errors.js");
57
+ const HOST_NAME = 'nodeHost';
58
+ const CAPABILITIES = ['streaming'];
59
+ /**
60
+ * Status codes this adapter maps by error code. Anything else is a 500.
61
+ *
62
+ * All three are deliberately NOT 5xx: none of them is the agent breaking. A
63
+ * closed host is shutting down (503), a concurrent turn conflicts with the run
64
+ * already going (409), and a paused run conflicts with the state this reply can
65
+ * carry (409) — the run is unfinished, not failed, and a 500 would say
66
+ * otherwise to every dashboard that ever sees it.
67
+ */
68
+ const STATUS_BY_CODE = {
69
+ ERR_HOST_CLOSED: 503,
70
+ ERR_CONCURRENT_RUN: 409,
71
+ ERR_PAUSE_NOT_CARRIED: 409,
72
+ };
73
+ /**
74
+ * An HTTP host for one handler.
75
+ *
76
+ * @example
77
+ * const handle = await nodeHost({ port: 0 }).serve(handler);
78
+ * await fetch(`${handle.url}/invoke`, {
79
+ * method: 'POST',
80
+ * headers: { 'content-type': 'application/json' },
81
+ * body: JSON.stringify({ input: 'hello', sessionId: 'c-1' }),
82
+ * });
83
+ * await handle.close();
84
+ */
85
+ function nodeHost(options = {}) {
86
+ const port = options.port ?? 8080;
87
+ const hostname = options.hostname ?? '0.0.0.0';
88
+ const invokePath = options.invokePath ?? '/invoke';
89
+ const healthPath = options.healthPath ?? '/health';
90
+ return {
91
+ name: HOST_NAME,
92
+ capabilities: CAPABILITIES,
93
+ async serve(handler) {
94
+ const { createServer } = await Promise.resolve().then(() => __importStar(require('node:http')));
95
+ const startedAt = Date.now();
96
+ const inFlight = new Set();
97
+ let accepting = true;
98
+ let closing;
99
+ const server = createServer((req, res) => {
100
+ const path = (req.url ?? '').split('?')[0];
101
+ if (req.method === 'GET' && path === healthPath) {
102
+ sendJson(res, 200, { status: 'ok', uptimeMs: Date.now() - startedAt });
103
+ return;
104
+ }
105
+ if (req.method !== 'POST' || path !== invokePath) {
106
+ sendJson(res, 404, { error: `no route for ${req.method ?? '?'} ${path}` });
107
+ return;
108
+ }
109
+ if (!accepting) {
110
+ const refusal = new errors_js_1.HostClosedError(HOST_NAME);
111
+ sendJson(res, STATUS_BY_CODE[refusal.code] ?? 500, {
112
+ error: refusal.message,
113
+ code: refusal.code,
114
+ });
115
+ return;
116
+ }
117
+ const served = serveOne(req, res, handler);
118
+ inFlight.add(served);
119
+ void served.finally(() => inFlight.delete(served));
120
+ });
121
+ await new Promise((resolve, reject) => {
122
+ server.once('error', reject);
123
+ server.listen(port, hostname, resolve);
124
+ });
125
+ const address = server.address();
126
+ const boundPort = typeof address === 'object' && address ? address.port : port;
127
+ const displayHost = hostname === '0.0.0.0' || hostname === '::' ? '127.0.0.1' : hostname;
128
+ return {
129
+ url: `http://${displayHost}:${boundPort}`,
130
+ port: boundPort,
131
+ close() {
132
+ // Idempotent: the first call owns the shutdown, later ones await it.
133
+ closing ??= (async () => {
134
+ accepting = false;
135
+ // Drain BEFORE touching sockets — an in-flight request is work the
136
+ // caller is still waiting on, and dropping it would be the exact
137
+ // thing close() promises not to do.
138
+ await Promise.allSettled([...inFlight]);
139
+ server.closeIdleConnections();
140
+ await new Promise((resolve) => server.close(() => resolve()));
141
+ })();
142
+ return closing;
143
+ },
144
+ };
145
+ },
146
+ };
147
+ }
148
+ exports.nodeHost = nodeHost;
149
+ /** Run one request through the handler and write whatever it decides. */
150
+ async function serveOne(req, res, handler) {
151
+ const wantsStream = (req.headers.accept ?? '').includes('text/event-stream');
152
+ const controller = new AbortController();
153
+ let body;
154
+ try {
155
+ body = await readJson(req);
156
+ }
157
+ catch (err) {
158
+ sendJson(res, 400, { error: `invalid JSON body: ${asError(err).message}` });
159
+ return;
160
+ }
161
+ const input = typeof body.input === 'string' ? body.input : '';
162
+ // sessionId is caller data whichever way it arrives; the body wins so a
163
+ // caller that sets both is not surprised by which one the server preferred.
164
+ const sessionId = typeof body.sessionId === 'string'
165
+ ? body.sessionId
166
+ : typeof req.headers['x-session-id'] === 'string'
167
+ ? req.headers['x-session-id']
168
+ : undefined;
169
+ if (wantsStream) {
170
+ res.writeHead(200, {
171
+ 'content-type': 'text/event-stream',
172
+ 'cache-control': 'no-cache',
173
+ connection: 'keep-alive',
174
+ });
175
+ }
176
+ let settled = false;
177
+ // The caller hung up before we answered — tell the handler so it can stop
178
+ // paying for work nobody is waiting for.
179
+ res.once('close', () => {
180
+ if (!settled)
181
+ controller.abort();
182
+ });
183
+ const reply = {
184
+ emit(chunk) {
185
+ // Not streaming? The chunk is a preview of text `complete` will deliver
186
+ // in full, so there is nothing to send and nothing to keep.
187
+ if (settled || !wantsStream)
188
+ return;
189
+ res.write((0, stream_js_1.encodeSSE)('chunk', { text: chunk }));
190
+ },
191
+ complete(output) {
192
+ if (settled)
193
+ return;
194
+ settled = true;
195
+ if (wantsStream) {
196
+ res.write((0, stream_js_1.encodeSSE)('complete', { output }));
197
+ res.end();
198
+ }
199
+ else {
200
+ sendJson(res, 200, { output });
201
+ }
202
+ },
203
+ fail(error) {
204
+ if (settled)
205
+ return;
206
+ settled = true;
207
+ const code = error.code;
208
+ const payload = { error: error.message, ...(code !== undefined && { code }) };
209
+ if (wantsStream) {
210
+ res.write((0, stream_js_1.encodeSSE)('error', payload));
211
+ res.end();
212
+ }
213
+ else {
214
+ sendJson(res, code !== undefined ? STATUS_BY_CODE[code] ?? 500 : 500, payload);
215
+ }
216
+ },
217
+ };
218
+ try {
219
+ await handler({
220
+ input,
221
+ ...(sessionId !== undefined && { sessionId }),
222
+ headers: lowerCased(req.headers),
223
+ signal: controller.signal,
224
+ }, reply);
225
+ }
226
+ catch (err) {
227
+ // A handler that throws is a failed request, never a hung one.
228
+ reply.fail(asError(err));
229
+ }
230
+ // A handler that returned without answering gets one authored answer rather
231
+ // than a socket the caller waits on until it times out.
232
+ if (!settled) {
233
+ reply.fail(new Error('[hosting] the handler returned without calling complete() or fail().'));
234
+ }
235
+ }
236
+ function readJson(req) {
237
+ return new Promise((resolve, reject) => {
238
+ const chunks = [];
239
+ req.on('data', (c) => chunks.push(c));
240
+ req.on('error', reject);
241
+ req.on('end', () => {
242
+ const raw = Buffer.concat(chunks).toString('utf8');
243
+ if (!raw)
244
+ return resolve({});
245
+ try {
246
+ const parsed = JSON.parse(raw);
247
+ resolve(parsed && typeof parsed === 'object' ? parsed : {});
248
+ }
249
+ catch (err) {
250
+ reject(err);
251
+ }
252
+ });
253
+ });
254
+ }
255
+ function sendJson(res, status, body) {
256
+ res.writeHead(status, { 'content-type': 'application/json' });
257
+ res.end(JSON.stringify(body));
258
+ }
259
+ function lowerCased(headers) {
260
+ const out = {};
261
+ for (const [name, value] of Object.entries(headers)) {
262
+ if (typeof value === 'string')
263
+ out[name.toLowerCase()] = value;
264
+ else if (Array.isArray(value))
265
+ out[name.toLowerCase()] = value.join(', ');
266
+ }
267
+ return out;
268
+ }
269
+ function asError(err) {
270
+ return err instanceof Error ? err : new Error(String(err));
271
+ }
272
+ //# sourceMappingURL=nodeHost.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nodeHost.js","sourceRoot":"","sources":["../../src/hosting/nodeHost.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;;;;;;;;;;;;;;;;;;;;;;;;;;AAIH,4CAAyC;AACzC,2CAA8C;AA4B9C,MAAM,SAAS,GAAG,UAAU,CAAC;AAC7B,MAAM,YAAY,GAA8B,CAAC,WAAW,CAAC,CAAC;AAE9D;;;;;;;;GAQG;AACH,MAAM,cAAc,GAAqC;IACvD,eAAe,EAAE,GAAG;IACpB,kBAAkB,EAAE,GAAG;IACvB,qBAAqB,EAAE,GAAG;CAC3B,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,SAAgB,QAAQ,CAAC,UAA2B,EAAE;IACpD,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,IAAI,CAAC;IAClC,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,SAAS,CAAC;IAC/C,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,IAAI,SAAS,CAAC;IACnD,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,IAAI,SAAS,CAAC;IAEnD,OAAO;QACL,IAAI,EAAE,SAAS;QACf,YAAY,EAAE,YAAY;QAC1B,KAAK,CAAC,KAAK,CAAC,OAAoB;YAC9B,MAAM,EAAE,YAAY,EAAE,GAAG,wDAAa,WAAW,GAAC,CAAC;YACnD,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;YAC7B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0,0 +1,196 @@
1
+ "use strict";
2
+ /**
3
+ * hosting/standingAgent — an agent that stays up and remembers.
4
+ *
5
+ * await standingAgent({
6
+ * agent,
7
+ * sessions: memorySessions(),
8
+ * host: nodeHost({ port: 8080 }),
9
+ * });
10
+ *
11
+ * One request at a time it does four things: wake and hydrate the session,
12
+ * resume that conversation or start a fresh one, persist what the run leaves
13
+ * behind, then reply. Everything else is somebody else's job — the host carries
14
+ * bytes, the store keeps them, the agent thinks.
15
+ *
16
+ * ── Resuming is a REPLAY, and that has a cost you must know about ────────────
17
+ * A stored conversation is restored through `agent.resumeOnError(...)`, and
18
+ * this is its caveat, stated here in the words the Agent states it in, because
19
+ * a composition that hides the caveat of the thing it composes is worse than no
20
+ * composition at all:
21
+ *
22
+ * > **Tool re-execution / idempotency**: tool side effects from the FAILED
23
+ * > iteration are not in the checkpoint. The model re-decides from the
24
+ * > restored history and may re-issue those tool calls — they WILL execute
25
+ * > again (there is no built-in toolCallId dedup). Mutating tools (payments,
26
+ * > emails, DB writes) must be idempotent — key on stable call content, not
27
+ * > `ctx.toolCallId` (a re-issued call gets a new id).
28
+ *
29
+ * ── Why one run at a time ───────────────────────────────────────────────────
30
+ * An Agent instance holds per-run state on itself, and this composer shares ONE
31
+ * instance across every session. Two runs overlapping on it do not crash —
32
+ * which is precisely the danger. They both finish, and the state the composer
33
+ * reads afterwards belongs to whichever started last, so one session's envelope
34
+ * can end up holding another session's conversation. Nothing in the recording
35
+ * would say so. Runs are therefore serialized, globally, and that is a
36
+ * correctness requirement rather than a tuning choice.
37
+ *
38
+ * `onConcurrentInvoke` is the separate question of what to do when a second
39
+ * turn of the SAME conversation arrives while the first is running: refuse it
40
+ * (default) or queue it. A request for a DIFFERENT session is never refused —
41
+ * there is nothing wrong with it; it simply waits its turn.
42
+ *
43
+ * Pattern: Composition root. It owns wiring and ordering; it invents no
44
+ * mechanism of its own.
45
+ */
46
+ Object.defineProperty(exports, "__esModule", { value: true });
47
+ exports.standingAgent = void 0;
48
+ const pause_js_1 = require("../core/pause.js");
49
+ const envelope_js_1 = require("./envelope.js");
50
+ const errors_js_1 = require("./errors.js");
51
+ /**
52
+ * Serve one agent, with per-session conversation memory, on any
53
+ * {@link AgentHost}.
54
+ *
55
+ * Resolves once the host is live. Closing the returned handle closes the host
56
+ * and detaches the listeners this composer added to the agent.
57
+ *
58
+ * @example
59
+ * const handle = await standingAgent({
60
+ * agent,
61
+ * sessions: memorySessions(),
62
+ * host: nodeHost({ port: 0 }),
63
+ * onConcurrentInvoke: 'enqueue',
64
+ * });
65
+ * process.on('SIGTERM', () => void handle.close());
66
+ */
67
+ async function standingAgent(options) {
68
+ const { agent, sessions, host } = options;
69
+ const policy = options.onConcurrentInvoke ?? 'reject';
70
+ // Runs are serialized, so at any moment there is at most one active reply and
71
+ // at most one active run to name in a refusal.
72
+ let activeReply;
73
+ let activeRunId;
74
+ let activeSession;
75
+ const queued = [];
76
+ let chain = Promise.resolve();
77
+ let anonymous = 0;
78
+ const offTurnStart = agent.on('agentfootprint.agent.turn_start', (event) => {
79
+ activeRunId = event.meta?.runId;
80
+ });
81
+ // Tokens reach the caller only if the host streams; `emit` on a host that
82
+ // does not is a no-op by design, so this needs no capability check.
83
+ const offToken = agent.on('agentfootprint.stream.token', (event) => {
84
+ const content = event.payload?.content;
85
+ if (typeof content === 'string' && content.length > 0)
86
+ activeReply?.emit?.(content);
87
+ });
88
+ /** Queue `work` behind everything already waiting, FIFO. */
89
+ function serialize(sessionKey, work) {
90
+ if (policy === 'reject' && (activeSession === sessionKey || queued.includes(sessionKey))) {
91
+ return Promise.reject(new errors_js_1.ConcurrentRunError(sessionKey, activeRunId));
92
+ }
93
+ queued.push(sessionKey);
94
+ const mine = chain.then(async () => {
95
+ queued.splice(queued.indexOf(sessionKey), 1);
96
+ activeSession = sessionKey;
97
+ try {
98
+ await work();
99
+ }
100
+ finally {
101
+ activeSession = undefined;
102
+ activeRunId = undefined;
103
+ }
104
+ });
105
+ // The chain must never reject, or one failed request would wedge every
106
+ // request behind it.
107
+ chain = mine.then(() => undefined, () => undefined);
108
+ return mine;
109
+ }
110
+ const handler = async (request, reply) => {
111
+ const sessionId = request.sessionId;
112
+ // A request with no session has nothing to hydrate and nowhere to persist
113
+ // that the caller could ask for again, so it gets its own key and can never
114
+ // collide with anyone.
115
+ const sessionKey = sessionId ?? `#anonymous-${++anonymous}`;
116
+ try {
117
+ await serialize(sessionKey, () => answerOne(agent, sessions, request, reply, sessionId));
118
+ }
119
+ catch (err) {
120
+ reply.fail(err instanceof Error ? err : new Error(String(err)));
121
+ }
122
+ };
123
+ async function answerOne(runner, store, request, reply, sessionId) {
124
+ activeReply = reply;
125
+ try {
126
+ let prior;
127
+ if (sessionId !== undefined) {
128
+ await store.onWake?.(sessionId, 'invoke');
129
+ const stored = await store.hydrate(sessionId);
130
+ // Throws by name on a format this runtime cannot read — better a loud
131
+ // refusal than an agent answering from half a conversation.
132
+ if (stored !== undefined)
133
+ prior = (0, envelope_js_1.readEnvelope)(stored);
134
+ }
135
+ // The signal reaches tool execution, tool discovery and skill-entry
136
+ // scoring. It does NOT currently reach the LLM call, so a caller who
137
+ // hangs up mid-generation stops the tools, not the token stream.
138
+ const runOptions = request.signal ? { env: { signal: request.signal } } : undefined;
139
+ const output = prior
140
+ ? await runner.resumeOnError(continueConversation(prior, request.input), runOptions)
141
+ : await runner.run({ message: request.input }, runOptions);
142
+ if ((0, pause_js_1.isPaused)(output)) {
143
+ reply.fail(new errors_js_1.PauseNotCarriedError(pausedToolName(runner), sessionId));
144
+ return;
145
+ }
146
+ if (sessionId !== undefined) {
147
+ const conversation = runner.checkpoint();
148
+ // Persist BEFORE answering: the caller learns the answer only once the
149
+ // conversation that produced it is durable, so a queued next turn can
150
+ // never read state older than the answer already given.
151
+ if (conversation)
152
+ await store.persist(sessionId, (0, envelope_js_1.toEnvelope)(conversation));
153
+ }
154
+ reply.complete(typeof output === 'string' ? output : String(output));
155
+ }
156
+ finally {
157
+ activeReply = undefined;
158
+ }
159
+ }
160
+ const handle = await host.serve(handler);
161
+ // Keep whatever the adapter put on its own handle (nodeHost's bound `url`,
162
+ // say) and replace only `close`, which now also detaches this composer's
163
+ // listeners. The cast is the one place TypeScript cannot see that a spread
164
+ // plus one override is still the adapter's handle type.
165
+ return {
166
+ ...handle,
167
+ async close() {
168
+ await handle.close();
169
+ offTurnStart();
170
+ offToken();
171
+ },
172
+ };
173
+ }
174
+ exports.standingAgent = standingAgent;
175
+ /**
176
+ * The stored conversation plus this turn's message.
177
+ *
178
+ * The new message has to be appended by hand: `resumeOnError` restores the
179
+ * history it is given and the LLM stage reads that history directly, so a
180
+ * message left out here is a message the model never sees.
181
+ */
182
+ function continueConversation(prior, input) {
183
+ return {
184
+ ...prior,
185
+ history: [...prior.history, { role: 'user', content: input }],
186
+ originalInput: { message: input },
187
+ checkpointedAt: Date.now(),
188
+ };
189
+ }
190
+ /** Which tool asked for a human, when the paused run recorded one. */
191
+ function pausedToolName(runner) {
192
+ const state = runner.getLastSnapshot()?.sharedState;
193
+ const name = state?.pausedToolName;
194
+ return typeof name === 'string' && name.length > 0 ? name : undefined;
195
+ }
196
+ //# sourceMappingURL=standingAgent.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"standingAgent.js","sourceRoot":"","sources":["../../src/hosting/standingAgent.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;;;AAEH,+CAA4C;AAE5C,+CAAyD;AACzD,2CAAuE;AAUvE;;;;;;;;;;;;;;;GAeG;AACI,KAAK,UAAU,aAAa,CACjC,OAAiC;IAEjC,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC;IAC1C,MAAM,MAAM,GAAG,OAAO,CAAC,kBAAkB,IAAI,QAAQ,CAAC;IAEtD,8EAA8E;IAC9E,+CAA+C;IAC/C,IAAI,WAAkC,CAAC;IACvC,IAAI,WAA+B,CAAC;IACpC,IAAI,aA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AS,CAAC;QAC1B,CAAC;IACH,CAAC;IAED,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACzC,2EAA2E;IAC3E,yEAAyE;IACzE,2EAA2E;IAC3E,wDAAwD;IACxD,OAAO;QACL,GAAG,MAAM;QACT,KAAK,CAAC,KAAK;YACT,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;YACrB,YAAY,EAAE,CAAC;YACf,QAAQ,EAAE,CAAC;QACb,CAAC;KACI,CAAC;AACV,CAAC;AAzHD,sCAyHC;AAED;;;;;;GAMG;AACH,SAAS,oBAAoB,CAAC,KAAyB,EAAE,KAAa;IACpE,OAAO;QACL,GAAG,KAAK;QACR,OAAO,EAAE,CAAC,GAAG,KAAK,CAAC,OAAO,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;QAC7D,aAAa,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE;QACjC,cAAc,EAAE,IAAI,CAAC,GAAG,EAAE;KAC3B,CAAC;AACJ,CAAC;AAED,sEAAsE;AACtE,SAAS,cAAc,CAAC,MAAa;IACnC,MAAM,KAAK,GAAG,MAAM,CAAC,eAAe,EAAE,EAAE,WAAuD,CAAC;IAChG,MAAM,IAAI,GAAG,KAAK,EAAE,cAAc,CAAC;IACnC,OAAO,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;AACxE,CAAC"}
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ /**
3
+ * hosting/types — the two ports an agent needs to stand up and stay up.
4
+ *
5
+ * `AgentHost` is "something can call me". `SessionLifecycle` is "the
6
+ * conversation outlives the request". Both are deliberately written in the
7
+ * vocabulary every transport and every store already has — an input, a reply,
8
+ * a session id, a stored blob — and in nothing else.
9
+ *
10
+ * **The rule these types are written under:** no runtime, product or protocol
11
+ * gets a field, a name or an assumption here. A port shaped around one
12
+ * provider's request envelope stops being a port and becomes that provider's
13
+ * SDK with extra steps, and every later adapter pays for it. If a decision only
14
+ * makes sense for one place you might deploy, it belongs in the adapter for
15
+ * that place, not in this file. `nodeHost` is the first adapter and it does not
16
+ * get special treatment either: its paths, its status codes and its JSON body
17
+ * shape all live in `nodeHost.ts`, and nothing in this file knows they exist.
18
+ *
19
+ * Pattern: Ports & adapters (hexagonal). Role: the port side, exclusively.
20
+ */
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/hosting/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;GAkBG"}
@@ -175,6 +175,10 @@ export declare class Agent extends RunnerBase<AgentInput, AgentOutput> {
175
175
  * function restores `scope.history` from this instead of starting
176
176
  * fresh. Cleared on first read so subsequent runs start clean. */
177
177
  private pendingResumeHistory?;
178
+ /** The last completed run's final answer — see `checkpoint()` for why it is
179
+ * kept here rather than read back from the recording. Undefined after a run
180
+ * that failed or paused. */
181
+ private lastRunAnswer?;
178
182
  /**
179
183
  * Optional `ToolProvider` set via the builder's `.toolProvider()`.
180
184
  * When present, the Tools slot subflow consults it per iteration
@@ -360,6 +364,49 @@ export declare class Agent extends RunnerBase<AgentInput, AgentOutput> {
360
364
  */
361
365
  private installCheckpointTracker;
362
366
  resume(checkpoint: FlowchartCheckpoint, input?: unknown, options?: AgentRunOptions): Promise<AgentOutput | RunnerPauseOutcome>;
367
+ /**
368
+ * The conversation this agent's LAST completed run leaves behind, packed as
369
+ * the same `AgentRunCheckpoint` that `resumeOnError(...)` accepts. Store it,
370
+ * hand it back next turn, and the agent continues where it left off — across
371
+ * a restart, a deploy, or a different machine.
372
+ *
373
+ * Returns `undefined` before any run has completed.
374
+ *
375
+ * **Read from the run's own recording, not from a second copy.** The history
376
+ * comes from `getLastSnapshot().sharedState.history` — the state the run
377
+ * actually committed — cloned on the way out so a persistence layer can never
378
+ * mutate the live heap. The final assistant turn is appended from the answer
379
+ * `run()` returned, because nothing ever writes it back into `history`: the
380
+ * loop appends assistant turns only when they carry tool calls, and the turn
381
+ * that ends the run carries none. An agent that stored this conversation
382
+ * without that append would drop its own reply every turn and answer the next
383
+ * one having forgotten what it just said.
384
+ *
385
+ * Adds no events, no scope writes and no capture: every recording is
386
+ * byte-identical to an agent that never calls this.
387
+ *
388
+ * After a run that **paused**, this is the conversation as of the pause, with
389
+ * no answer appended — a pause is unfinished work, and pause/resume has its
390
+ * own carrier (`FlowchartCheckpoint`) that holds engine state this shape
391
+ * cannot.
392
+ *
393
+ * The conversation grows every turn and nothing here trims it. Bounding what
394
+ * the model is shown is the memory subsystem's job (`.memory(...)`), not a
395
+ * silent cap applied on the way to storage.
396
+ *
397
+ * @example
398
+ * ```ts
399
+ * await agent.run({ message: 'Book me a table for two.' });
400
+ * const conversation = agent.checkpoint(); // persist anywhere
401
+ * // …a restart later, on a fresh Agent:
402
+ * await agent.resumeOnError({
403
+ * ...conversation,
404
+ * history: [...conversation.history, { role: 'user', content: 'Make it three.' }],
405
+ * originalInput: { message: 'Make it three.' },
406
+ * });
407
+ * ```
408
+ */
409
+ checkpoint(): AgentRunCheckpoint | undefined;
363
410
  private createExecutor;
364
411
  /**
365
412
  * Flush the deferred-observer backlog of the most recent run's executor,
@@ -1 +1 @@
1
- {"version":3,"file":"Agent.d.ts","sourceRoot":"","sources":["../../../src/core/Agent.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAGL,KAAK,sBAAsB,EAI3B,KAAK,mBAAmB,EACxB,KAAK,mBAAmB,EAExB,KAAK,UAAU,EACf,KAAK,eAAe,EACrB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yBAA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storage, and refuse to unpack one
3
+ * you cannot read.
4
+ *
5
+ * Two functions and one rule: **an unknown format is refused by name, never
6
+ * guessed at.** A store outlives the code that wrote to it. Somebody will
7
+ * deploy a newer runtime, it will write a newer format, and an older instance
8
+ * still running will read it. The only honest thing that older instance can do
9
+ * is say which format it found, which ones it knows, and stop — because
10
+ * "restore what I can and hope" means an agent answering from a conversation
11
+ * that is missing whatever the older reader did not understand.
12
+ */
13
+ import { type AgentRunCheckpoint } from '../core/runCheckpoint.js';
14
+ import type { CheckpointEnvelope } from './types.js';
15
+ /**
16
+ * Pack a conversation checkpoint for storage.
17
+ *
18
+ * @example
19
+ * const conversation = agent.checkpoint();
20
+ * if (conversation) await sessions.persist(sessionId, toEnvelope(conversation));
21
+ */
22
+ export declare function toEnvelope(checkpoint: AgentRunCheckpoint): CheckpointEnvelope;
23
+ /**
24
+ * Unpack a stored envelope back into a conversation checkpoint.
25
+ *
26
+ * Takes `unknown` on purpose: what comes back from a store is bytes somebody
27
+ * else wrote, in a format this runtime may not know, and typing the parameter
28
+ * as the happy shape would be assuming the very thing that needs checking.
29
+ *
30
+ * @throws TypeError naming the format when it is one this runtime cannot read,
31
+ * and naming the missing field when the conversation inside is malformed.
32
+ */
33
+ export declare function readEnvelope(envelope: unknown): AgentRunCheckpoint;
34
+ //# sourceMappingURL=envelope.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"envelope.d.ts","sourceRoot":"","sources":["../../../src/hosting/envelope.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAsB,KAAK,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AACvF,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAKrD;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,UAAU,EAAE,kBAAkB,GAAG,kBAAkB,CAE7E;AAED;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,QAAQ,EAAE,OAAO,GAAG,kBAAkB,CAkBlE"}