agentfootprint 7.18.0 → 7.19.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 (79) hide show
  1. package/dist/adapters/hosting/agentcore.js +23 -9
  2. package/dist/adapters/hosting/agentcore.js.map +1 -1
  3. package/dist/core/Agent.js +6 -0
  4. package/dist/core/Agent.js.map +1 -1
  5. package/dist/core/agent/stages/toolCalls.js +13 -0
  6. package/dist/core/agent/stages/toolCalls.js.map +1 -1
  7. package/dist/core/durabilityBarrier.js +68 -0
  8. package/dist/core/durabilityBarrier.js.map +1 -0
  9. package/dist/esm/adapters/hosting/agentcore.d.ts +4 -4
  10. package/dist/esm/adapters/hosting/agentcore.js +24 -10
  11. package/dist/esm/adapters/hosting/agentcore.js.map +1 -1
  12. package/dist/esm/core/Agent.js +6 -0
  13. package/dist/esm/core/Agent.js.map +1 -1
  14. package/dist/esm/core/agent/stages/toolCalls.d.ts +21 -0
  15. package/dist/esm/core/agent/stages/toolCalls.js +13 -0
  16. package/dist/esm/core/agent/stages/toolCalls.js.map +1 -1
  17. package/dist/esm/core/durabilityBarrier.d.ts +61 -0
  18. package/dist/esm/core/durabilityBarrier.js +63 -0
  19. package/dist/esm/core/durabilityBarrier.js.map +1 -0
  20. package/dist/esm/hosting/durability.d.ts +92 -0
  21. package/dist/esm/hosting/durability.js +174 -0
  22. package/dist/esm/hosting/durability.js.map +1 -0
  23. package/dist/esm/hosting/envelope.d.ts +75 -14
  24. package/dist/esm/hosting/envelope.js +141 -16
  25. package/dist/esm/hosting/envelope.js.map +1 -1
  26. package/dist/esm/hosting/errors.d.ts +60 -11
  27. package/dist/esm/hosting/errors.js +92 -18
  28. package/dist/esm/hosting/errors.js.map +1 -1
  29. package/dist/esm/hosting/httpHost.d.ts +17 -1
  30. package/dist/esm/hosting/httpHost.js +42 -6
  31. package/dist/esm/hosting/httpHost.js.map +1 -1
  32. package/dist/esm/hosting/index.d.ts +7 -4
  33. package/dist/esm/hosting/index.js +6 -3
  34. package/dist/esm/hosting/index.js.map +1 -1
  35. package/dist/esm/hosting/nodeHost.d.ts +4 -2
  36. package/dist/esm/hosting/nodeHost.js +14 -3
  37. package/dist/esm/hosting/nodeHost.js.map +1 -1
  38. package/dist/esm/hosting/standingAgent.d.ts +22 -7
  39. package/dist/esm/hosting/standingAgent.js +144 -32
  40. package/dist/esm/hosting/standingAgent.js.map +1 -1
  41. package/dist/esm/hosting/types.d.ts +193 -19
  42. package/dist/hosting/durability.js +178 -0
  43. package/dist/hosting/durability.js.map +1 -0
  44. package/dist/hosting/envelope.js +146 -18
  45. package/dist/hosting/envelope.js.map +1 -1
  46. package/dist/hosting/errors.js +95 -19
  47. package/dist/hosting/errors.js.map +1 -1
  48. package/dist/hosting/httpHost.js +42 -6
  49. package/dist/hosting/httpHost.js.map +1 -1
  50. package/dist/hosting/index.js +10 -2
  51. package/dist/hosting/index.js.map +1 -1
  52. package/dist/hosting/nodeHost.js +14 -3
  53. package/dist/hosting/nodeHost.js.map +1 -1
  54. package/dist/hosting/standingAgent.js +142 -30
  55. package/dist/hosting/standingAgent.js.map +1 -1
  56. package/dist/types/adapters/hosting/agentcore.d.ts +4 -4
  57. package/dist/types/adapters/hosting/agentcore.d.ts.map +1 -1
  58. package/dist/types/core/Agent.d.ts.map +1 -1
  59. package/dist/types/core/agent/stages/toolCalls.d.ts +21 -0
  60. package/dist/types/core/agent/stages/toolCalls.d.ts.map +1 -1
  61. package/dist/types/core/durabilityBarrier.d.ts +62 -0
  62. package/dist/types/core/durabilityBarrier.d.ts.map +1 -0
  63. package/dist/types/hosting/durability.d.ts +93 -0
  64. package/dist/types/hosting/durability.d.ts.map +1 -0
  65. package/dist/types/hosting/envelope.d.ts +75 -14
  66. package/dist/types/hosting/envelope.d.ts.map +1 -1
  67. package/dist/types/hosting/errors.d.ts +60 -11
  68. package/dist/types/hosting/errors.d.ts.map +1 -1
  69. package/dist/types/hosting/httpHost.d.ts +17 -1
  70. package/dist/types/hosting/httpHost.d.ts.map +1 -1
  71. package/dist/types/hosting/index.d.ts +7 -4
  72. package/dist/types/hosting/index.d.ts.map +1 -1
  73. package/dist/types/hosting/nodeHost.d.ts +4 -2
  74. package/dist/types/hosting/nodeHost.d.ts.map +1 -1
  75. package/dist/types/hosting/standingAgent.d.ts +22 -7
  76. package/dist/types/hosting/standingAgent.d.ts.map +1 -1
  77. package/dist/types/hosting/types.d.ts +193 -19
  78. package/dist/types/hosting/types.d.ts.map +1 -1
  79. package/package.json +1 -1
@@ -0,0 +1,178 @@
1
+ "use strict";
2
+ /**
3
+ * hosting/durability — how often a run's progress becomes crash-survivable.
4
+ *
5
+ * A standing agent that only writes at the end of a turn is one restart away
6
+ * from losing everything the turn had done: the tool calls it made, the results
7
+ * it read, the iterations it spent. This is the dial that decides how much of
8
+ * that survives, and what it costs.
9
+ *
10
+ * ── Where a mid-run write can honestly come from ─────────────────────────────
11
+ * From the COMMIT boundary, and nowhere else. footprintjs commits a stage's
12
+ * writes after the stage function returns, and committed state is
13
+ * immutable-after-swap — so `ScopeRecorder.onCommit` is the one moment where
14
+ * "what the run has agreed on so far" is a real, complete, consistent thing.
15
+ * Reading the agent's live state at any other moment would be reading a stage's
16
+ * work in progress.
17
+ *
18
+ * There is no mid-run engine checkpoint to store: footprintjs builds a
19
+ * `FlowchartCheckpoint` only at a pause (`getCheckpoint()` is documented as "the
20
+ * most recent PAUSED execution"). So what a mid-run write can carry is a
21
+ * CONVERSATION — the same `AgentRunCheckpoint` every finished turn stores — and
22
+ * that is exactly enough, because that is what the next turn resumes from.
23
+ *
24
+ * ── Why it writes on SOME commits and not all of them ────────────────────────
25
+ * A two-iteration turn commits about forty times. Exactly two of those commits
26
+ * change the conversation: `Initialize` (the user's message lands) and
27
+ * `ToolCalls` (an iteration's assistant turn and its tool results land). Every
28
+ * other commit would store bytes identical to the last write. So the trigger is
29
+ * "this commit wrote `history`", which is not an optimisation but the honest
30
+ * reading of the question: the conversation moved iff `history` moved.
31
+ *
32
+ * ── What a commit boundary actually guarantees, and what it does not ─────────
33
+ * It guarantees the whole stage. The agent dispatches ALL of one iteration's
34
+ * tool calls inside one stage body, so a crash part-way through that body stores
35
+ * nothing from it and a replay re-runs that iteration's tools. That is the
36
+ * shipped idempotency requirement, unchanged — mutating tools must be
37
+ * idempotent, keyed on stable call content rather than `ctx.toolCallId`. What
38
+ * `'sync'` adds is a BOUND on it: iteration N's tools do not start until
39
+ * iteration N-1's write has landed, so the replay is the current iteration and
40
+ * never an earlier one.
41
+ *
42
+ * Pattern: an observer (`CombinedRecorder`) for the snapshot, a serialiser for
43
+ * the writes, and — for `'sync'` only — a barrier the tool dispatch waits on.
44
+ * Role: internal to `standingAgent`. Deliberately not exported: it is how the
45
+ * composer keeps its promise, not a second way to write to a store.
46
+ */
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.durableWriter = void 0;
49
+ const durabilityBarrier_js_1 = require("../core/durabilityBarrier.js");
50
+ /**
51
+ * Build the writer.
52
+ *
53
+ * Under `'sync'` it also answers the tool-dispatch barrier, which is what turns
54
+ * "we write often" into a bound on how much can re-run.
55
+ */
56
+ function durableWriter(options) {
57
+ const { mode, session, runId, write } = options;
58
+ /** The write currently on the wire, or `undefined` when nothing is. */
59
+ let inFlight;
60
+ /**
61
+ * The newest snapshot that has not been started yet. At most ONE, and a newer
62
+ * one replaces it: the conversation only grows, so a superseded snapshot is a
63
+ * prefix of the one replacing it and writing it first would buy nothing.
64
+ */
65
+ let queued;
66
+ /**
67
+ * Why the NEWEST write did not land, or `undefined` when it did. Cleared by a
68
+ * write that succeeds — a store that failed once and then took the newer
69
+ * state has made that state durable, and reporting the older failure would be
70
+ * describing a problem that no longer exists.
71
+ */
72
+ let failure;
73
+ /** Per-run accumulation, rebuilt from the commits themselves. */
74
+ let history = [];
75
+ let userMessage = '';
76
+ let iteration = 0;
77
+ function pump() {
78
+ if (inFlight !== undefined || queued === undefined)
79
+ return;
80
+ const next = queued;
81
+ queued = undefined;
82
+ inFlight = write(next.sessionId, next.conversation)
83
+ .then(() => {
84
+ failure = undefined;
85
+ }, (err) => {
86
+ failure = new Error(`[hosting] the session store did not accept this run's progress, so nothing ` +
87
+ `after this point may proceed as if it had` +
88
+ (mode === 'sync' ? ` — the next tool call was not allowed to run` : '') +
89
+ `. Underlying error: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
90
+ })
91
+ .then(() => {
92
+ inFlight = undefined;
93
+ pump();
94
+ });
95
+ }
96
+ function enqueue(sessionId) {
97
+ queued = {
98
+ sessionId,
99
+ conversation: {
100
+ version: 1,
101
+ runId: runId() ?? 'unknown',
102
+ // The commit event hands over the stage's retained write view. Clone on
103
+ // the way to a store so nothing a persistence layer does can reach back
104
+ // into the run's own snapshot.
105
+ history: structuredClone(history),
106
+ lastCompletedIteration: iteration,
107
+ originalInput: { message: userMessage },
108
+ checkpointedAt: Date.now(),
109
+ },
110
+ };
111
+ pump();
112
+ }
113
+ const recorder = {
114
+ id: 'af-hosting-durability',
115
+ // INLINE, always. A write delivered one beat behind is a write that can be
116
+ // lost by the very crash it exists to survive — and under `'sync'` the
117
+ // barrier would be waiting on a snapshot the queue had not handed over yet.
118
+ // The causal-evidence bridge and the compaction meter are inline for the
119
+ // same class of reason.
120
+ delivery: 'inline',
121
+ onCommit(event) {
122
+ let conversationMoved = false;
123
+ for (const mutation of event.mutations) {
124
+ if (mutation.key === 'history' && Array.isArray(mutation.value)) {
125
+ history = mutation.value;
126
+ conversationMoved = true;
127
+ }
128
+ else if (mutation.key === 'userMessage' && typeof mutation.value === 'string') {
129
+ userMessage = mutation.value;
130
+ }
131
+ else if (mutation.key === 'iteration' && typeof mutation.value === 'number') {
132
+ iteration = mutation.value;
133
+ }
134
+ }
135
+ if (!conversationMoved)
136
+ return;
137
+ const sessionId = session();
138
+ if (sessionId === undefined)
139
+ return;
140
+ enqueue(sessionId);
141
+ },
142
+ // A fresh run starts from a fresh conversation. Without this a resumed run
143
+ // whose first commit has not landed yet could stamp the previous run's
144
+ // history onto this run's id.
145
+ clear() {
146
+ history = [];
147
+ userMessage = '';
148
+ iteration = 0;
149
+ },
150
+ };
151
+ const settle = async () => {
152
+ // Loop rather than await once: a write that completes may release a queued
153
+ // successor, and "settled" has to mean nothing is left.
154
+ while (inFlight !== undefined || queued !== undefined) {
155
+ pump();
156
+ await inFlight;
157
+ }
158
+ if (failure)
159
+ throw failure;
160
+ };
161
+ return {
162
+ recorder,
163
+ install(agent) {
164
+ // `'async'` deliberately takes NO barrier: its whole promise is that the
165
+ // run does not wait, and a barrier would be that promise broken quietly.
166
+ if (mode !== 'sync')
167
+ return () => undefined;
168
+ return (0, durabilityBarrier_js_1.installDurabilityBarrier)(agent, () => {
169
+ if (inFlight === undefined && queued === undefined && failure === undefined)
170
+ return undefined;
171
+ return settle();
172
+ });
173
+ },
174
+ settle,
175
+ };
176
+ }
177
+ exports.durableWriter = durableWriter;
178
+ //# sourceMappingURL=durability.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"durability.js","sourceRoot":"","sources":["../../src/hosting/durability.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;;;AAIH,uEAAwE;AA4CxE;;;;;GAKG;AACH,SAAgB,aAAa,CAAC,OAA6B;IACzD,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,OAAO,CAAC;IAEhD,uEAAuE;IACvE,IAAI,QAAmC,CAAC;IACxC;;;;OAIG;IACH,IAAI,MAA2E,CAAC;IAChF;;;;;OAKG;IACH,IAAI,OAA0B,CAAC;IAE/B,iEAAiE;IACjE,IAAI,OAAO,GAA0B,EAAE,CAAC;IACxC,IAAI,WAAW,GAAG,EAAE,CAAC;IACrB,IAAI,SAAS,GAAG,CAAC,CAAC;IAElB,SAAS,IAAI;QACX,IAAI,QAAQ,KAAK,SAAS,IAAI,MAAM,KAAK,SAAS;YAAE,OAAO;QAC3D,MAAM,IAAI,G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AE,MAAM,OAAO,CAAC;IAC7B,CAAC,CAAC;IAEF,OAAO;QACL,QAAQ;QACR,OAAO,CAAC,KAAa;YACnB,yEAAyE;YACzE,yEAAyE;YACzE,IAAI,IAAI,KAAK,MAAM;gBAAE,OAAO,GAAG,EAAE,CAAC,SAAS,CAAC;YAC5C,OAAO,IAAA,+CAAwB,EAAC,KAAK,EAAE,GAAG,EAAE;gBAC1C,IAAI,QAAQ,KAAK,SAAS,IAAI,MAAM,KAAK,SAAS,IAAI,OAAO,KAAK,SAAS;oBACzE,OAAO,SAAS,CAAC;gBACnB,OAAO,MAAM,EAAE,CAAC;YAClB,CAAC,CAAC,CAAC;QACL,CAAC;QACD,MAAM;KACP,CAAC;AACJ,CAAC;AAhID,sCAgIC"}
@@ -1,21 +1,31 @@
1
1
  "use strict";
2
2
  /**
3
- * hosting/envelope — pack a conversation for storage, and refuse to unpack one
4
- * you cannot read.
3
+ * hosting/envelope — pack a session for storage, and refuse to unpack one you
4
+ * cannot read.
5
5
  *
6
- * Two functions and one rule: **an unknown format is refused by name, never
7
- * guessed at.** A store outlives the code that wrote to it. Somebody will
8
- * deploy a newer runtime, it will write a newer format, and an older instance
9
- * still running will read it. The only honest thing that older instance can do
10
- * is say which format it found, which ones it knows, and stop — because
11
- * "restore what I can and hope" means an agent answering from a conversation
12
- * that is missing whatever the older reader did not understand.
6
+ * One rule, and everything here is a consequence of it: **an envelope this
7
+ * runtime cannot read is refused BY NAME, never guessed at.** A store outlives
8
+ * the code that wrote to it. Somebody will deploy a newer runtime, it will write
9
+ * a newer format, and an older instance still running will read it. The only
10
+ * honest thing that older instance can do is say which format it found, which
11
+ * ones it knows, and stop — because "restore what I can and hope" means an agent
12
+ * answering from a session that is missing whatever the older reader did not
13
+ * understand.
14
+ *
15
+ * ── Two formats, two readers, and why they refuse each other ─────────────────
16
+ * `readEnvelope` unpacks a CONVERSATION; `readPausedRun` unpacks a PAUSED RUN.
17
+ * Each refuses the other's format by name and points at its sibling. That looks
18
+ * fussy until you notice the alternative: one reader that quietly returned the
19
+ * conversation inside a paused run would hand back a session that LOOKS finished
20
+ * while a person is still waiting on a question nobody mentioned. That is a
21
+ * half-restore wearing a happy path, which is the exact failure the format field
22
+ * exists to prevent.
13
23
  */
14
24
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.readEnvelope = exports.toEnvelope = void 0;
25
+ exports.checkEnvelope = exports.readPausedRun = exports.readEnvelope = exports.toPausedEnvelope = exports.toEnvelope = void 0;
16
26
  const runCheckpoint_js_1 = require("../core/runCheckpoint.js");
17
27
  /** Every format this runtime can read. Add, never redefine. */
18
- const KNOWN_FORMATS = ['conversation-v1'];
28
+ const KNOWN_FORMATS = ['conversation-v1', 'flowchart-v1'];
19
29
  /**
20
30
  * Pack a conversation checkpoint for storage.
21
31
  *
@@ -27,6 +37,30 @@ function toEnvelope(checkpoint) {
27
37
  return { format: 'conversation-v1', data: checkpoint, savedAt: Date.now() };
28
38
  }
29
39
  exports.toEnvelope = toEnvelope;
40
+ /**
41
+ * Pack a paused run for storage — the engine checkpoint, the conversation as of
42
+ * the pause, and the question it is waiting on.
43
+ *
44
+ * Store it anywhere that speaks JSON. Note what JSON does and does not preserve
45
+ * here: `agent.resume()` reads `checkpoint.sharedState`, which round-trips
46
+ * unchanged; the engine's diagnostic halves lose their explicitly-`undefined`
47
+ * properties, because that is what `JSON.stringify` does to them. See
48
+ * {@link PausedRun}.
49
+ *
50
+ * @example
51
+ * const outcome = await agent.run({ message });
52
+ * if (isPaused(outcome)) {
53
+ * await sessions.persist(sessionId, toPausedEnvelope({
54
+ * checkpoint: outcome.checkpoint,
55
+ * conversation: agent.checkpoint()!,
56
+ * pending: { pauseData: outcome.pauseData },
57
+ * }));
58
+ * }
59
+ */
60
+ function toPausedEnvelope(paused) {
61
+ return { format: 'flowchart-v1', data: paused, savedAt: Date.now() };
62
+ }
63
+ exports.toPausedEnvelope = toPausedEnvelope;
30
64
  /**
31
65
  * Unpack a stored envelope back into a conversation checkpoint.
32
66
  *
@@ -34,21 +68,115 @@ exports.toEnvelope = toEnvelope;
34
68
  * else wrote, in a format this runtime may not know, and typing the parameter
35
69
  * as the happy shape would be assuming the very thing that needs checking.
36
70
  *
37
- * @throws TypeError naming the format when it is one this runtime cannot read,
38
- * and naming the missing field when the conversation inside is malformed.
71
+ * @throws TypeError naming the format when it is one this runtime cannot read;
72
+ * naming the missing field when the conversation inside is malformed; and
73
+ * pointing at {@link readPausedRun} when the envelope holds a paused run,
74
+ * which is a session with a question outstanding rather than a conversation.
39
75
  */
40
76
  function readEnvelope(envelope) {
41
- if (!envelope || typeof envelope !== 'object') {
42
- throw new TypeError(`[hosting] stored session is not an envelope (got ${envelope === null ? 'null' : typeof envelope}). ` + `Expected { format, data, savedAt } as written by toEnvelope().`);
77
+ if (readFormat(envelope) === 'flowchart-v1') {
78
+ throw new TypeError(`[hosting] this envelope holds a PAUSED RUN ('flowchart-v1'), not a conversation. ` +
79
+ `Read it with readPausedRun(envelope) — it is waiting on a person's decision, and ` +
80
+ `handing back only the conversation inside it would restore a session that looks ` +
81
+ `finished while somebody is still waiting to be asked.`);
82
+ }
83
+ return (0, runCheckpoint_js_1.validateCheckpoint)(envelope.data);
84
+ }
85
+ exports.readEnvelope = readEnvelope;
86
+ /**
87
+ * Unpack a stored envelope back into a paused run.
88
+ *
89
+ * @throws TypeError naming the format when it is one this runtime cannot read;
90
+ * pointing at {@link readEnvelope} when the envelope holds a plain
91
+ * conversation; and naming the missing field when the paused run inside is
92
+ * malformed.
93
+ */
94
+ function readPausedRun(envelope) {
95
+ if (readFormat(envelope) === 'conversation-v1') {
96
+ throw new TypeError(`[hosting] this envelope holds a conversation ('conversation-v1'), not a paused run. ` +
97
+ `Read it with readEnvelope(envelope). Nothing is waiting on a decision here.`);
98
+ }
99
+ return validatePausedRun(envelope.data);
100
+ }
101
+ exports.readPausedRun = readPausedRun;
102
+ /**
103
+ * Check that an envelope is one this runtime can read, and hand it back
104
+ * unchanged — without committing to which half you wanted.
105
+ *
106
+ * This is what a STORE wants. A store's job is to notice that the bytes it is
107
+ * about to hand over are unreadable, so the refusal names the store that
108
+ * produced them rather than whoever read them next; it has no business caring
109
+ * whether the session inside is mid-conversation or mid-question.
110
+ *
111
+ * @throws TypeError naming the format when this runtime cannot read it, or the
112
+ * missing field when the payload is malformed.
113
+ *
114
+ * @example
115
+ * async hydrate(sessionId) {
116
+ * const stored = await myStore.get(sessionId);
117
+ * return stored === undefined ? undefined : checkEnvelope(stored);
118
+ * }
119
+ */
120
+ function checkEnvelope(envelope) {
121
+ if (readFormat(envelope) === 'flowchart-v1') {
122
+ validatePausedRun(envelope.data);
123
+ }
124
+ else {
125
+ (0, runCheckpoint_js_1.validateCheckpoint)(envelope.data);
126
+ }
127
+ return envelope;
128
+ }
129
+ exports.checkEnvelope = checkEnvelope;
130
+ /**
131
+ * The one place a `format` is checked, so every refusal in this file says the
132
+ * same thing in the same words.
133
+ */
134
+ function readFormat(envelope) {
135
+ if (!envelope || typeof envelope !== 'object' || Array.isArray(envelope)) {
136
+ throw new TypeError(`[hosting] stored session is not an envelope (got ${envelope === null ? 'null' : Array.isArray(envelope) ? 'an array' : typeof envelope}). Expected { format, data, savedAt } as written by toEnvelope() / toPausedEnvelope().`);
43
137
  }
44
138
  const found = envelope.format;
45
139
  if (typeof found !== 'string' || !KNOWN_FORMATS.includes(found)) {
46
140
  throw new TypeError(`[hosting] unknown checkpoint format '${String(found)}'. ` +
47
141
  `This runtime reads: ${KNOWN_FORMATS.join(', ')}. ` +
48
- `Refusing rather than restoring a conversation it cannot read — a newer envelope ` +
142
+ `Refusing rather than restoring a session it cannot read — a newer envelope ` +
49
143
  `needs a runtime that knows the format that wrote it.`);
50
144
  }
51
- return (0, runCheckpoint_js_1.validateCheckpoint)(envelope.data);
145
+ return found;
146
+ }
147
+ /**
148
+ * Validate a paused run at deserialization time, naming the missing piece.
149
+ *
150
+ * Only the fields resume actually consumes are required. `executionTree` and
151
+ * `subflowResults` are the engine's diagnostic halves — a checkpoint that lost
152
+ * them in transit still resumes, so demanding them would refuse a session that
153
+ * would have worked.
154
+ */
155
+ function validatePausedRun(value) {
156
+ if (!value || typeof value !== 'object') {
157
+ throw new TypeError('[hosting] paused run is not an object.');
158
+ }
159
+ const run = value;
160
+ const cp = run.checkpoint;
161
+ if (!cp || typeof cp !== 'object') {
162
+ throw new TypeError(`[hosting] paused run is missing required field: checkpoint. ` +
163
+ `It is the engine checkpoint agent.resume() continues from; without it the run ` +
164
+ `cannot be continued at all.`);
165
+ }
166
+ if (typeof cp.pausedStageId !== 'string' ||
167
+ !cp.sharedState ||
168
+ typeof cp.sharedState !== 'object') {
169
+ throw new TypeError(`[hosting] paused run's checkpoint is missing required fields (pausedStageId, ` +
170
+ `sharedState) — the two agent.resume() rebuilds the cursor and the run's state from.`);
171
+ }
172
+ if (!Array.isArray(cp.subflowPath)) {
173
+ throw new TypeError(`[hosting] paused run's checkpoint is missing required field: subflowPath.`);
174
+ }
175
+ if (!run.pending || typeof run.pending !== 'object') {
176
+ throw new TypeError(`[hosting] paused run is missing required field: pending — the question it is ` +
177
+ `waiting on. A stored pause nobody can describe is a session that hangs.`);
178
+ }
179
+ (0, runCheckpoint_js_1.validateCheckpoint)(run.conversation);
180
+ return run;
52
181
  }
53
- exports.readEnvelope = readEnvelope;
54
182
  //# sourceMappingURL=envelope.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"envelope.js","sourceRoot":"","sources":["../../src/hosting/envelope.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;GAWG;;;AAEH,+DAAuF;AAGvF,+DAA+D;AAC/D,MAAM,aAAa,GAAsB,CAAC,iBAAiB,CAAC,CAAC;AAE7D;;;;;;GAMG;AACH,SAAgB,UAAU,CAAC,UAA8B;IACvD,OAAO,EAAE,MAAM,EAAE,iBAAiB,EAAE,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC;AAC9E,CAAC;AAFD,gCAEC;AAED;;;;;;;;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CAAC;IACJ,CAAC;IACD,IAAI,CAAC,GAAG,CAAC,OAAO,IAAI,OAAO,GAAG,CAAC,OAAO,KAAK,QAAQ,EAAE,CAAC;QACpD,MAAM,IAAI,SAAS,CACjB,+EAA+E;YAC7E,yEAAyE,CAC5E,CAAC;IACJ,CAAC;IACD,IAAA,qCAAkB,EAAC,GAAG,CAAC,YAAY,CAAC,CAAC;IACrC,OAAO,GAAgB,CAAC;AAC1B,CAAC"}
@@ -4,18 +4,22 @@
4
4
  * same words.
5
5
  *
6
6
  * A refusal that varies by adapter is a refusal nobody can write a test or a
7
- * runbook against. These three carry a stable `code`, name WHO refused, and say
7
+ * runbook against. These five carry a stable `code`, name WHO refused, and say
8
8
  * what the caller should do instead. Adapters map the codes onto whatever their
9
9
  * transport uses to say "no" — that mapping is the adapter's business and lives
10
10
  * in the adapter, never here.
11
11
  *
12
- * `requireCapability` is the fourth refusal and the only one that is a
12
+ * Note what is NOT here: a run that paused. That is unfinished work rather than
13
+ * a refusal, and it leaves through `reply.awaiting(...)` — its own terminal —
14
+ * not through an error dressed up as one.
15
+ *
16
+ * `requireCapability` is the last refusal and the only one that is a
13
17
  * programming mistake rather than a runtime condition, so it throws a plain
14
18
  * `Error`: nothing branches on "I forgot to feature-detect", it just needs to
15
19
  * say so loudly and name the adapter it is talking about.
16
20
  */
17
21
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.requireCapability = exports.PauseNotCarriedError = exports.ConcurrentRunError = exports.HostClosedError = void 0;
22
+ exports.requireCapability = exports.NoPendingAskError = exports.AwaitingDecisionError = exports.PauseNotCarriedError = exports.ConcurrentRunError = exports.HostClosedError = void 0;
19
23
  /**
20
24
  * Thrown when a request arrives at a host that is shutting down or shut down.
21
25
  *
@@ -65,40 +69,112 @@ class ConcurrentRunError extends Error {
65
69
  }
66
70
  exports.ConcurrentRunError = ConcurrentRunError;
67
71
  /**
68
- * Raised when a run paused to ask a person something and the reply cannot carry
69
- * a pause.
72
+ * Raised when a run paused to ask a person something and there is **nowhere to
73
+ * keep it**.
70
74
  *
71
75
  * **The run did not fail.** A pause is unfinished work: the agent stopped to ask
72
- * and is waiting for an answer. What cannot happen here is storing it — the
73
- * `'conversation-v1'` envelope holds a conversation, and a paused run is a
74
- * conversation plus an engine checkpoint. So nothing is written, and the
75
- * session keeps exactly the conversation it had before this request.
76
+ * and is waiting for an answer. Since 7.19 a paused run is stored as
77
+ * `'flowchart-v1'` and continued by a later request carrying a decision — so the
78
+ * one case left where a pause genuinely cannot be carried is a request with no
79
+ * session id. There is no session to store it under, and therefore no later
80
+ * request that could ever answer it.
81
+ *
82
+ * The other half of the old meaning — "the reply cannot carry a pause" — is
83
+ * gone: {@link HostReply.awaiting} carries it now. An adapter that has not
84
+ * implemented that terminal still gets its pause STORED (the store is not the
85
+ * transport's business) and this refusal on the wire, naming the session it can
86
+ * be answered on.
76
87
  */
77
88
  class PauseNotCarriedError extends Error {
78
89
  code = 'ERR_PAUSE_NOT_CARRIED';
79
90
  /** The tool that asked, when the run recorded which one it was. */
80
91
  toolName;
81
- /** The session whose stored conversation was left untouched. */
92
+ /** The session the paused run was stored under, when there was one. */
82
93
  sessionId;
83
- constructor(toolName, sessionId) {
94
+ /** Whether the paused run was stored. `false` means it is gone. */
95
+ stored;
96
+ constructor(toolName, sessionId, stored = false) {
84
97
  super(`[hosting] the run paused to ask a person about ` +
85
98
  (toolName ? `'${toolName}'` : 'a tool') +
86
- ` and this reply cannot carry a pause. ` +
87
- `The run did not fail — it is unfinished, waiting on an answer. ` +
88
- `Nothing was written: ` +
89
- (sessionId ? `session '${sessionId}'` : 'the session') +
90
- ` still holds the conversation it held before this request. ` +
91
- `The 'conversation-v1' envelope stores a conversation; a paused run is a ` +
92
- `conversation plus an engine checkpoint, and storing half of it would be worse ` +
93
- `than storing none. Carry the pause yourself with agent.run() / agent.resume().`);
99
+ `. The run did not fail — it is unfinished, waiting on an answer. ` +
100
+ (stored
101
+ ? `It IS stored: send another request for session '${String(sessionId)}' carrying ` +
102
+ `a 'decision' to continue it. This reply could not describe the question ` +
103
+ `because the host it arrived on does not implement reply.awaiting(); read the ` +
104
+ `pending ask from the session store, or serve on a host that has it.`
105
+ : `Nothing was written: ` +
106
+ (sessionId === undefined
107
+ ? `this request carried no session id, so there is nowhere to store a paused ` +
108
+ `run and no later request that could ever answer it. Send a sessionId, or `
109
+ : `session '${sessionId}' still holds what it held before this request. `) +
110
+ `carry the pause yourself with agent.run() / agent.resume().`));
94
111
  this.name = 'PauseNotCarriedError';
95
112
  if (toolName !== undefined)
96
113
  this.toolName = toolName;
97
114
  if (sessionId !== undefined)
98
115
  this.sessionId = sessionId;
116
+ this.stored = stored;
99
117
  }
100
118
  }
101
119
  exports.PauseNotCarriedError = PauseNotCarriedError;
120
+ /**
121
+ * Thrown when a new message arrives for a session whose run is waiting on a
122
+ * person's decision.
123
+ *
124
+ * The message is NOT run and the pause is NOT discarded — those are the two ways
125
+ * this could have gone wrong. Answering the message would step over an
126
+ * outstanding consent gate; dropping the paused run to make room for the message
127
+ * would throw away work a person was asked about. So the request is refused, the
128
+ * pending question is named, and the session sits exactly where it was.
129
+ *
130
+ * Answer it by sending the same session a request carrying
131
+ * {@link HostRequest.decision}.
132
+ */
133
+ class AwaitingDecisionError extends Error {
134
+ code = 'ERR_AWAITING_DECISION';
135
+ /** The session that is waiting. */
136
+ sessionId;
137
+ /** What it is waiting on — the same payload `reply.awaiting()` delivered. */
138
+ pending;
139
+ constructor(sessionId, pending) {
140
+ const asked = pending.question ?? pending.ask?.question ?? pending.checkIn?.evidence.willDo ?? 'a decision';
141
+ super(`[hosting] session '${sessionId}' is waiting on a person: ` +
142
+ (pending.tool ? `'${pending.tool}' asked "${asked}"` : `"${asked}"`) +
143
+ `. This message was NOT run and the paused run was NOT discarded — answering a ` +
144
+ `new message would step over the question, and dropping the question to answer ` +
145
+ `the message would throw away work somebody was asked to approve. ` +
146
+ `Send this session a request carrying 'decision' (checkInApproved(...) / ` +
147
+ `checkInDeclined(...) for a check-in or a middleware ask) to continue the run.`);
148
+ this.name = 'AwaitingDecisionError';
149
+ this.sessionId = sessionId;
150
+ this.pending = pending;
151
+ }
152
+ }
153
+ exports.AwaitingDecisionError = AwaitingDecisionError;
154
+ /**
155
+ * Thrown when a request carries a decision for a session that is not waiting on
156
+ * one.
157
+ *
158
+ * Usually a duplicate delivery: the run was already continued, or already
159
+ * answered, and the same decision arrived twice. Running it as an ordinary
160
+ * message would put a raw approval into the conversation as if the user had
161
+ * typed it, so it is refused by name instead.
162
+ */
163
+ class NoPendingAskError extends Error {
164
+ code = 'ERR_NO_PENDING_ASK';
165
+ /** The session the decision was addressed to. */
166
+ sessionId;
167
+ constructor(sessionId) {
168
+ super(`[hosting] this request carries a 'decision' but session '${sessionId}' is not ` +
169
+ `waiting on one — nothing is paused. The run it answered has most likely already ` +
170
+ `been continued (a duplicate delivery). Refusing rather than treating an approval ` +
171
+ `as if a person had typed it into the conversation. Send it as 'input' if that is ` +
172
+ `genuinely what you meant.`);
173
+ this.name = 'NoPendingAskError';
174
+ this.sessionId = sessionId;
175
+ }
176
+ }
177
+ exports.NoPendingAskError = NoPendingAskError;
102
178
  /**
103
179
  * Assert that a host can do something, and throw a corrective error naming the
104
180
  * adapter when it cannot.
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/hosting/errors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAIH;;;;;GAKG;AACH,MAAa,eAAgB,SAAQ,KAAK;IAC/B,IAAI,GAAG,iBAA0B,CAAC;IAC3C,6BAA6B;IACpB,QAAQ,CAAS;IAE1B,YAAY,QAAgB;QAC1B,KAAK,CACH,kBAAkB,QAAQ,sDAAsD;YAC9E,wFAAwF;YACxF,iDAAiD,CACpD,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;QAC9B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;CACF;AAdD,0CAcC;AAED;;;;;;;;G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iB,CAAC,IAAe,EAAE,UAA0B;IAC3E,IAAI,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,UAAU,CAAC;QAAE,OAAO;IACnD,MAAM,GAAG,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;IACjF,MAAM,IAAI,KAAK,CACb,kBAAkB,IAAI,CAAC,IAAI,4BAA4B,UAAU,KAAK;QACpE,eAAe,GAAG,wBAAwB;QAC1C,+BAA+B,UAAU,uCAAuC;QAChF,oFAAoF,CACvF,CAAC;AACJ,CAAC;AATD,8CASC"}
@@ -59,17 +59,27 @@ const errors_js_1 = require("./errors.js");
59
59
  /**
60
60
  * Status codes mapped by refusal code. Anything else is a 500.
61
61
  *
62
- * None of the three is a 5xx: none of them is the agent breaking. A closed host
63
- * is shutting down (503), a concurrent turn conflicts with the run already
64
- * going (409), and a paused run conflicts with the state this reply can carry
65
- * (409) — the run is unfinished, not failed, and a 500 would say otherwise to
66
- * every dashboard that ever sees it.
62
+ * Not one of them is a 5xx: none of them is the agent breaking. A closed host is
63
+ * shutting down (503); the other four are conflicts with the state the session
64
+ * is already in (409) — a run already going, a question already outstanding, a
65
+ * decision with nothing to decide, a pause this reply cannot describe. A 500
66
+ * would tell every dashboard that ever sees it something untrue.
67
67
  */
68
68
  const STATUS_BY_CODE = {
69
69
  ERR_HOST_CLOSED: 503,
70
70
  ERR_CONCURRENT_RUN: 409,
71
71
  ERR_PAUSE_NOT_CARRIED: 409,
72
+ ERR_AWAITING_DECISION: 409,
73
+ ERR_NO_PENDING_ASK: 409,
72
74
  };
75
+ /**
76
+ * What a run that stopped to ask a person answers with: **202 Accepted.**
77
+ *
78
+ * The request was understood and acted on, and the work is not finished — which
79
+ * is what 202 means and what nothing else in the 2xx range means. Not 200: there
80
+ * is no answer. Not 4xx or 5xx: nothing was refused and nothing broke.
81
+ */
82
+ const AWAITING_STATUS = 202;
73
83
  const DEFAULT_CAPABILITIES = ['streaming'];
74
84
  /**
75
85
  * An HTTP host for one handler, speaking the dialect you hand it.
@@ -153,7 +163,7 @@ async function serveOne(req, res, handler, wire) {
153
163
  }
154
164
  const headers = lowerCased(req.headers);
155
165
  const query = new URLSearchParams((req.url ?? '').split('?')[1] ?? '');
156
- const { input, sessionId } = wire.readRequest({ body, headers, query });
166
+ const { input, sessionId, decision } = wire.readRequest({ body, headers, query });
157
167
  if (wantsStream) {
158
168
  res.writeHead(200, {
159
169
  'content-type': 'text/event-stream',
@@ -188,6 +198,31 @@ async function serveOne(req, res, handler, wire) {
188
198
  sendJson(res, 200, wire.output(output));
189
199
  }
190
200
  },
201
+ awaiting(pending) {
202
+ if (settled)
203
+ return;
204
+ // A wire that cannot describe a question must not answer 202 with an
205
+ // empty body — that would look like a completed request. Fall through to
206
+ // the named refusal, which at least says what happened and where the
207
+ // paused run is.
208
+ if (!wire.awaiting) {
209
+ const refusal = new Error(`[hosting] the run is waiting on a person and this host's wire has no ` +
210
+ `awaiting() body shape, so the question cannot be described on the wire. ` +
211
+ `The paused run is stored; read the pending ask from the session store.`);
212
+ refusal.code = 'ERR_PAUSE_NOT_CARRIED';
213
+ reply.fail(refusal);
214
+ return;
215
+ }
216
+ settled = true;
217
+ const payload = wire.awaiting(pending);
218
+ if (wantsStream) {
219
+ res.write((0, stream_js_1.encodeSSE)('awaiting', payload));
220
+ res.end();
221
+ }
222
+ else {
223
+ sendJson(res, AWAITING_STATUS, payload);
224
+ }
225
+ },
191
226
  fail(error) {
192
227
  if (settled)
193
228
  return;
@@ -207,6 +242,7 @@ async function serveOne(req, res, handler, wire) {
207
242
  await handler({
208
243
  input,
209
244
  ...(sessionId !== undefined && { sessionId }),
245
+ ...(decision !== undefined && { decision }),
210
246
  headers,
211
247
  signal: controller.signal,
212
248
  }, reply);