@vincemakes/kiso-runtime 0.1.19 → 0.1.21
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.d.ts +6 -0
- package/dist/compose.d.ts +32 -0
- package/dist/compose.js +117 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/recovery.d.ts +28 -0
- package/dist/recovery.js +68 -0
- package/dist/run.d.ts +20 -0
- package/dist/run.js +463 -0
- package/dist/session.d.ts +32 -13
- package/dist/session.js +45 -631
- package/package.json +5 -5
package/dist/run.js
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 手感批 B4 (pure move) — the Run class (a single turn: write-ahead
|
|
3
|
+
* persistence, the loop drive, the durable recovery state machine), moved
|
|
4
|
+
* verbatim from session.ts.
|
|
5
|
+
*/
|
|
6
|
+
import { denialResult, loop } from "@vincemakes/kiso-core";
|
|
7
|
+
import { ABORTED, MergedSignal, abortable, openRunId } from "./recovery.js";
|
|
8
|
+
import { composeSystemPrompt, microcompactFor } from "./compose.js";
|
|
9
|
+
import { ResumeBlockedError } from "./session.js";
|
|
10
|
+
/**
|
|
11
|
+
* A single turn. Async-iterable, so `for await (const ev of session.run(x))`
|
|
12
|
+
* is the natural shape; the handle also carries the runId and the abort.
|
|
13
|
+
*/
|
|
14
|
+
export class Run {
|
|
15
|
+
runId;
|
|
16
|
+
#store;
|
|
17
|
+
#adapter;
|
|
18
|
+
#config;
|
|
19
|
+
#session;
|
|
20
|
+
#input;
|
|
21
|
+
#resume;
|
|
22
|
+
#abort = new AbortController();
|
|
23
|
+
#externalSignal;
|
|
24
|
+
#decisionIds = [];
|
|
25
|
+
#uncertaintyIds = [];
|
|
26
|
+
#started = false;
|
|
27
|
+
constructor(store, adapter, config, session, input, externalSignal, resume) {
|
|
28
|
+
this.#store = store;
|
|
29
|
+
this.#adapter = adapter;
|
|
30
|
+
this.#config = config;
|
|
31
|
+
this.#session = session;
|
|
32
|
+
this.#input = input;
|
|
33
|
+
this.#externalSignal = externalSignal;
|
|
34
|
+
this.#resume = resume;
|
|
35
|
+
this.runId = crypto.randomUUID();
|
|
36
|
+
}
|
|
37
|
+
/** Cancel the run: propagates to the adapter (SDK) and future executions. */
|
|
38
|
+
abort() {
|
|
39
|
+
this.#abort.abort();
|
|
40
|
+
}
|
|
41
|
+
async *[Symbol.asyncIterator]() {
|
|
42
|
+
if (this.#started)
|
|
43
|
+
throw new Error("a run may only be consumed once");
|
|
44
|
+
this.#started = true;
|
|
45
|
+
// The WHOLE body is one try/finally: a consumer that abandons the
|
|
46
|
+
// run at ANY yield (even the user_input one) must release the
|
|
47
|
+
// session's single-run slot and its approval resolvers.
|
|
48
|
+
try {
|
|
49
|
+
// 第四轮: health is re-checked when the iterator ACTUALLY starts —
|
|
50
|
+
// a run constructed before the session was poisoned must fail
|
|
51
|
+
// here, before any log or disk mutation.
|
|
52
|
+
this.#session.ensureHealthy();
|
|
53
|
+
this.#session.beginRun(this);
|
|
54
|
+
const log = this.#session.log;
|
|
55
|
+
const signal = this.#externalSignal ? new MergedSignal(this.#abort.signal, this.#externalSignal) : this.#abort.signal;
|
|
56
|
+
// E2: the session's own microcompact wins; otherwise the FIRST
|
|
57
|
+
// extension providing a compaction config supplies it.
|
|
58
|
+
const microcompact = microcompactFor(this.#config);
|
|
59
|
+
// E2: the session's own systemPrompt first, then every extension
|
|
60
|
+
// append in LOAD order — deterministic (same extensions → same
|
|
61
|
+
// prompt); no appends → byte-identical to the extension-less run.
|
|
62
|
+
const systemPrompt = composeSystemPrompt(this.#config.systemPrompt, this.#config.extensions ?? []);
|
|
63
|
+
const loopConfig = () => ({
|
|
64
|
+
adapter: this.#adapter,
|
|
65
|
+
model: this.#config.model,
|
|
66
|
+
sessionId: this.#session.id, // P3: tools see their session (ToolContext.sessionId)
|
|
67
|
+
...(systemPrompt !== undefined ? { systemPrompt } : {}),
|
|
68
|
+
registry: this.#config.registry,
|
|
69
|
+
...(this.#config.hooks !== undefined ? { hooks: this.#config.hooks } : {}),
|
|
70
|
+
...(this.#config.maxTurns !== undefined ? { maxTurns: this.#config.maxTurns } : {}),
|
|
71
|
+
...(this.#config.maxTokens !== undefined ? { maxTokens: this.#config.maxTokens } : {}),
|
|
72
|
+
...(this.#config.temperature !== undefined ? { temperature: this.#config.temperature } : {}),
|
|
73
|
+
...(this.#config.compaction !== undefined ? { compaction: this.#config.compaction } : {}),
|
|
74
|
+
...(microcompact !== undefined ? { microcompact } : {}),
|
|
75
|
+
...(this.#config.maxRetries !== undefined ? { maxRetries: this.#config.maxRetries } : {}),
|
|
76
|
+
approvalPolicies: (this.#config.extensions ?? []).flatMap((e) => (e.approvals ?? []).map((policy) => ({ extension: e.name, policy }))),
|
|
77
|
+
log,
|
|
78
|
+
signal,
|
|
79
|
+
resolveApproval: (decisionId) => new Promise((resolve) => {
|
|
80
|
+
this.#decisionIds.push(decisionId);
|
|
81
|
+
this.#session.registerResolver(decisionId, resolve);
|
|
82
|
+
}),
|
|
83
|
+
// 第四轮(对抗): the abort paths consult these so a verdict
|
|
84
|
+
// the human gave in the same instant as the abort is
|
|
85
|
+
// recorded, exactly once.
|
|
86
|
+
approvalVerdict: (decisionId) => this.#session.approvalVerdict(decisionId),
|
|
87
|
+
uncertaintyVerdict: (executionId) => this.#session.uncertaintyVerdict(executionId),
|
|
88
|
+
resolveUncertainty: (executionId) => new Promise((resolve) => {
|
|
89
|
+
this.#uncertaintyIds.push(executionId);
|
|
90
|
+
this.#session.registerUncertaintyResolver(executionId, resolve);
|
|
91
|
+
}),
|
|
92
|
+
});
|
|
93
|
+
const self = this;
|
|
94
|
+
const runLoop = async function* () {
|
|
95
|
+
for await (const ev of loop(loopConfig())) {
|
|
96
|
+
await self.#session.persist(self.runId, ev);
|
|
97
|
+
yield ev;
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
if (this.#resume) {
|
|
101
|
+
// ── B 组: recovery is PER-RUN, keyed by StoreRecord.runId ──
|
|
102
|
+
// Rebuild run boundaries; only the LAST unterminated run is
|
|
103
|
+
// recovered. Earlier runs that DID terminate have their
|
|
104
|
+
// dangling approvals closed (permission_expired) — a dead
|
|
105
|
+
// run's approval is never re-presented or resurrected.
|
|
106
|
+
const records = this.#store.load(this.#session.id);
|
|
107
|
+
const runs = new Map();
|
|
108
|
+
const order = [];
|
|
109
|
+
for (const r of records) {
|
|
110
|
+
if (!runs.has(r.runId)) {
|
|
111
|
+
runs.set(r.runId, []);
|
|
112
|
+
order.push(r.runId);
|
|
113
|
+
}
|
|
114
|
+
runs.get(r.runId).push(r.event);
|
|
115
|
+
}
|
|
116
|
+
let lastOpen;
|
|
117
|
+
for (const runId of order) {
|
|
118
|
+
const events = runs.get(runId);
|
|
119
|
+
if (!events.some((e) => e.type === "terminal"))
|
|
120
|
+
lastOpen = { runId, events };
|
|
121
|
+
}
|
|
122
|
+
if (!lastOpen)
|
|
123
|
+
return; // everything terminated — nothing to resume
|
|
124
|
+
// Adopt the ORIGINAL runId so the whole trajectory stays one
|
|
125
|
+
// run in the audit.
|
|
126
|
+
this.runId = lastOpen.runId;
|
|
127
|
+
// Close dangling approvals of TERMINATED runs.
|
|
128
|
+
for (const [runId, events] of runs) {
|
|
129
|
+
if (runId === lastOpen.runId)
|
|
130
|
+
continue;
|
|
131
|
+
if (!events.some((e) => e.type === "terminal"))
|
|
132
|
+
continue; // an open earlier run? impossible — lastOpen is the LAST
|
|
133
|
+
for (const ev of events) {
|
|
134
|
+
if (ev.type !== "permission_requested")
|
|
135
|
+
continue;
|
|
136
|
+
const dead = this.#session.log.all.some((e) => (e.type === "permission_decided" || e.type === "permission_expired") &&
|
|
137
|
+
e.decisionId === ev.decisionId);
|
|
138
|
+
if (dead)
|
|
139
|
+
continue;
|
|
140
|
+
const expired = this.#session.log.append({
|
|
141
|
+
type: "permission_expired",
|
|
142
|
+
decisionId: ev.decisionId,
|
|
143
|
+
reason: `run ${runId} terminated before the request was answered`,
|
|
144
|
+
});
|
|
145
|
+
await this.#session.persist(runId, expired);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
// Uncertain executions block until a human decides.
|
|
149
|
+
const uncertain = this.#session.uncertainExecutions();
|
|
150
|
+
if (uncertain.length > 0) {
|
|
151
|
+
throw new ResumeBlockedError(uncertain.map((u) => ({ executionId: u.executionId, callId: u.callId, name: u.name })));
|
|
152
|
+
}
|
|
153
|
+
// 1. Recovery scoped to the LAST OPEN RUN's events. The recover
|
|
154
|
+
// phase re-announces ALREADY-PERSISTED events (the stored
|
|
155
|
+
// permission_requested) for the consumer to re-prompt on —
|
|
156
|
+
// those must never be written to the store again, or seq
|
|
157
|
+
// would duplicate. Only events newer than the base log
|
|
158
|
+
// entry are durable.
|
|
159
|
+
const baseSeq = log.lastSeq;
|
|
160
|
+
const persist = async (ev) => {
|
|
161
|
+
if (ev.seq > baseSeq)
|
|
162
|
+
await this.#session.persist(this.runId, ev);
|
|
163
|
+
};
|
|
164
|
+
for await (const ev of this.#recover(log, signal, lastOpen.events)) {
|
|
165
|
+
await persist(ev);
|
|
166
|
+
yield ev;
|
|
167
|
+
}
|
|
168
|
+
// 2. Continuation: drive the LAST OPEN run to its terminal.
|
|
169
|
+
// The guard is scoped to that run — an earlier run's
|
|
170
|
+
// terminal must not suppress it (B 组).
|
|
171
|
+
if (!lastOpen.events.some((e) => e.type === "terminal")) {
|
|
172
|
+
for await (const ev of runLoop())
|
|
173
|
+
yield ev;
|
|
174
|
+
}
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
// 四: a session with an open run REFUSES new runs at the
|
|
178
|
+
// persistence layer — a second open run would be permanently
|
|
179
|
+
// orphaned (recovery only ever recovers the last one). The
|
|
180
|
+
// open run is continued via resume(), never by starting another.
|
|
181
|
+
const openRun = openRunId(this.#store.load(this.#session.id));
|
|
182
|
+
if (openRun !== undefined) {
|
|
183
|
+
throw new Error(`session ${this.#session.id} still has an open run (${openRun}) — resume() it instead of starting a new run`);
|
|
184
|
+
}
|
|
185
|
+
// 1. Durable first: the prompt enters the log and the store
|
|
186
|
+
// before any model call — a crash here leaves a restorable
|
|
187
|
+
// session. The prompt is also the first event the consumer
|
|
188
|
+
// sees, so what was asked and what happened live in the same
|
|
189
|
+
// stream.
|
|
190
|
+
const inputEvent = log.append({ type: "user_input", content: this.#input });
|
|
191
|
+
await this.#session.persist(this.runId, inputEvent);
|
|
192
|
+
yield inputEvent;
|
|
193
|
+
// 2. The loop projects from the session log — multi-turn context
|
|
194
|
+
// is the projection, not a second copy.
|
|
195
|
+
for await (const ev of runLoop())
|
|
196
|
+
yield ev;
|
|
197
|
+
}
|
|
198
|
+
finally {
|
|
199
|
+
// 第五轮(P1-5): flush verdicts the consumer submitted before the
|
|
200
|
+
// generator was abandoned — an approve()/resolveUncertain() whose
|
|
201
|
+
// durable event the loop never got to persist must STILL land on
|
|
202
|
+
// disk, exactly once.
|
|
203
|
+
try {
|
|
204
|
+
await this.#session.flushPendingVerdicts(this.runId, this.#session.log);
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
// the flush itself failed (poisoned session) — the error
|
|
208
|
+
// already poisoned everything; nothing more can be done.
|
|
209
|
+
}
|
|
210
|
+
// The run is over (or abandoned): its unanswered approvals must
|
|
211
|
+
// fall back to the direct-persist path, so a late approve() is
|
|
212
|
+
// still durable.
|
|
213
|
+
for (const decisionId of this.#decisionIds) {
|
|
214
|
+
this.#session.dropResolver(decisionId);
|
|
215
|
+
}
|
|
216
|
+
for (const executionId of this.#uncertaintyIds) {
|
|
217
|
+
this.#session.dropUncertaintyResolver(executionId);
|
|
218
|
+
}
|
|
219
|
+
this.#session.endRun(this);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
// ── Area 2: the durable recovery state machine ───────────────────────
|
|
223
|
+
/**
|
|
224
|
+
* Apply every durable decision and fill every missing receipt, in log
|
|
225
|
+
* order. A decision with no execution yet EXECUTES the persisted call
|
|
226
|
+
* (its original name/input/callId — never re-asked of the model, never
|
|
227
|
+
* re-approved); a denial writes its tool result; a succeeded/failed
|
|
228
|
+
* execution whose tool_result never landed is completed from the
|
|
229
|
+
* receipt. Undecided requests pause and await approve().
|
|
230
|
+
*/
|
|
231
|
+
async *#recover(log, signal, scope) {
|
|
232
|
+
const requests = scope.filter((e) => e.type === "permission_requested");
|
|
233
|
+
for (const pending of requests) {
|
|
234
|
+
const decided = log.all.find((e) => e.type === "permission_decided" && e.decisionId === pending.decisionId);
|
|
235
|
+
// 四: paired by events NEWER than the request — a historical
|
|
236
|
+
// same-callId execution from an earlier run must not count as THIS
|
|
237
|
+
// request's execution (the provider callId may repeat across runs).
|
|
238
|
+
const hasExecution = log.all.some((e) => e.type === "tool_execution_started" && e.callId === pending.callId && e.seq > pending.seq);
|
|
239
|
+
const hasResult = log.all.some((e) => e.type === "tool_result" && e.callId === pending.callId && e.seq > pending.seq);
|
|
240
|
+
if (decided === undefined) {
|
|
241
|
+
// Pause: announce the stored request, await the human.
|
|
242
|
+
const pendingDecision = new Promise((resolve) => {
|
|
243
|
+
this.#decisionIds.push(pending.decisionId);
|
|
244
|
+
this.#session.registerResolver(pending.decisionId, resolve);
|
|
245
|
+
});
|
|
246
|
+
yield pending;
|
|
247
|
+
// Area 4: an abort during the resumed approval wait ends the
|
|
248
|
+
// run; the request stays durable and pending.
|
|
249
|
+
if (signal.aborted) {
|
|
250
|
+
// 第五轮(P1-6): a verdict given in the same instant as the
|
|
251
|
+
// abort is still recorded — the abort must not bypass the
|
|
252
|
+
// durable fallback (aligned with the loop's abort path).
|
|
253
|
+
const verdict = this.#session.approvalVerdict(pending.decisionId);
|
|
254
|
+
if (verdict !== undefined) {
|
|
255
|
+
yield log.append({
|
|
256
|
+
type: "permission_decided",
|
|
257
|
+
decisionId: pending.decisionId,
|
|
258
|
+
callId: pending.callId,
|
|
259
|
+
decision: verdict ? "approved" : "denied",
|
|
260
|
+
...(verdict ? {} : { reason: "denied by user" }),
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
const final = await abortable(pendingDecision, signal);
|
|
266
|
+
if (final === ABORTED) {
|
|
267
|
+
// 第四轮(对抗): a verdict given in the same instant as the
|
|
268
|
+
// abort is recorded (exactly once), never lost.
|
|
269
|
+
const verdict = this.#session.approvalVerdict(pending.decisionId);
|
|
270
|
+
if (verdict !== undefined) {
|
|
271
|
+
yield log.append({
|
|
272
|
+
type: "permission_decided",
|
|
273
|
+
decisionId: pending.decisionId,
|
|
274
|
+
callId: pending.callId,
|
|
275
|
+
decision: verdict ? "approved" : "denied",
|
|
276
|
+
...(verdict ? {} : { reason: "denied by user" }),
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
// The decision is written here — exactly one writer per event.
|
|
282
|
+
yield log.append({
|
|
283
|
+
type: "permission_decided",
|
|
284
|
+
decisionId: pending.decisionId,
|
|
285
|
+
callId: pending.callId, // binds the decision to the invocation (B 组)
|
|
286
|
+
decision: final.action === "allow" ? "approved" : "denied",
|
|
287
|
+
...(final.action === "deny" && final.reason !== undefined ? { reason: final.reason } : {}),
|
|
288
|
+
});
|
|
289
|
+
if (final.action === "allow") {
|
|
290
|
+
if (!hasExecution)
|
|
291
|
+
yield* this.#executePersisted(pending.callId, pending.name, pending.input, signal);
|
|
292
|
+
}
|
|
293
|
+
else if (!hasResult) {
|
|
294
|
+
yield* this.#denialResult(pending.callId, final.reason ?? "denied by user");
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
else if (decided.decision === "approved") {
|
|
298
|
+
// Decided while no process was running: apply without pausing.
|
|
299
|
+
// An abort during recovery must stop the pending executions,
|
|
300
|
+
// exactly like the live loop's sibling guard (finding 3).
|
|
301
|
+
if (signal.aborted)
|
|
302
|
+
return;
|
|
303
|
+
if (!hasExecution)
|
|
304
|
+
yield* this.#executePersisted(pending.callId, pending.name, pending.input, signal);
|
|
305
|
+
}
|
|
306
|
+
else if (!hasResult) {
|
|
307
|
+
yield* this.#denialResult(pending.callId, decided.reason ?? "denied by user");
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
// Receipt repair: an execution that reached a terminal state but
|
|
311
|
+
// whose model-facing result never landed is completed FROM THE
|
|
312
|
+
// RECEIPT — never re-executed. Snapshot the scope first: this phase
|
|
313
|
+
// appends the repaired results, and iterating a growing array would
|
|
314
|
+
// re-visit them. 四: pairing is by executionId — a same-callId result
|
|
315
|
+
// from a different execution never suppresses the repair.
|
|
316
|
+
for (const ev of [...scope]) {
|
|
317
|
+
if (ev.type !== "tool_execution_succeeded" && ev.type !== "tool_execution_failed")
|
|
318
|
+
continue;
|
|
319
|
+
const hasResult = log.all.some((e) => e.type === "tool_result" && e.executionId === ev.executionId);
|
|
320
|
+
if (hasResult)
|
|
321
|
+
continue;
|
|
322
|
+
yield log.append(ev.type === "tool_execution_succeeded"
|
|
323
|
+
? {
|
|
324
|
+
type: "tool_result",
|
|
325
|
+
callId: ev.callId,
|
|
326
|
+
content: ev.result.content,
|
|
327
|
+
isError: false,
|
|
328
|
+
// 八: the repaired result reproduces the normal path
|
|
329
|
+
// losslessly — the tags ride on the durable receipt.
|
|
330
|
+
...(ev.tags !== undefined ? { tags: ev.tags } : {}),
|
|
331
|
+
executionId: ev.executionId,
|
|
332
|
+
}
|
|
333
|
+
: {
|
|
334
|
+
type: "tool_result",
|
|
335
|
+
callId: ev.callId,
|
|
336
|
+
content: ev.error,
|
|
337
|
+
isError: true,
|
|
338
|
+
...(ev.errorKind !== undefined ? { errorKind: ev.errorKind } : {}),
|
|
339
|
+
...(ev.tags !== undefined ? { tags: ev.tags } : {}),
|
|
340
|
+
executionId: ev.executionId,
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
// B 组 crash window: a resolution was persisted but its tool_result
|
|
344
|
+
// fill never landed — complete it so the model is never left staring
|
|
345
|
+
// at a dangling tool_use. 四: keyed by executionId, and the fill
|
|
346
|
+
// carries it, so a same-callId result from another execution is never
|
|
347
|
+
// confused with this one.
|
|
348
|
+
for (const ev of [...scope]) {
|
|
349
|
+
if (ev.type !== "tool_execution_resolved")
|
|
350
|
+
continue;
|
|
351
|
+
const hasResult = log.all.some((e) => e.type === "tool_result" && e.executionId === ev.executionId);
|
|
352
|
+
if (hasResult)
|
|
353
|
+
continue;
|
|
354
|
+
const denial = denialResult(ev.resolution === "rerun"
|
|
355
|
+
? "interrupted execution — rerun approved: the attempt is treated as NOT applied; the model may retry"
|
|
356
|
+
: "abandoned by human decision — the interrupted attempt must not be treated as applied");
|
|
357
|
+
yield log.append({
|
|
358
|
+
type: "tool_result",
|
|
359
|
+
callId: ev.callId,
|
|
360
|
+
content: denial.content,
|
|
361
|
+
isError: true,
|
|
362
|
+
errorKind: denial.errorKind,
|
|
363
|
+
executionId: ev.executionId,
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Execute a call whose approval is already durable: the original
|
|
369
|
+
* name/input/callId from the persisted permission_requested, bypassing
|
|
370
|
+
* the permission hook (it was decided) and the model (it was never
|
|
371
|
+
* asked to re-issue). Full ledgered lifecycle.
|
|
372
|
+
*/
|
|
373
|
+
async *#executePersisted(callId, name, input, signal) {
|
|
374
|
+
const log = this.#session.log;
|
|
375
|
+
const tool = this.#config.registry.get(name);
|
|
376
|
+
const executionId = `ex-${log.lastSeq + 1}`;
|
|
377
|
+
// An abort that landed while the decision was being applied must
|
|
378
|
+
// not start the side effect (finding 3).
|
|
379
|
+
if (signal.aborted)
|
|
380
|
+
return;
|
|
381
|
+
yield log.append({ type: "tool_execution_started", executionId, callId, name, input });
|
|
382
|
+
let result;
|
|
383
|
+
if (tool === undefined) {
|
|
384
|
+
result = { content: `Unknown tool: ${name}`, isError: true, errorKind: "invalid_input" };
|
|
385
|
+
}
|
|
386
|
+
else {
|
|
387
|
+
try {
|
|
388
|
+
if (signal.aborted) {
|
|
389
|
+
result = { content: "aborted before execution", isError: true, errorKind: "fatal" };
|
|
390
|
+
}
|
|
391
|
+
else {
|
|
392
|
+
result = await tool.execute(input, { signal });
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
catch (err) {
|
|
396
|
+
result = {
|
|
397
|
+
content: err instanceof Error ? err.message : String(err),
|
|
398
|
+
isError: true,
|
|
399
|
+
errorKind: "fatal",
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
if (this.#config.hooks?.onPostTool) {
|
|
403
|
+
result = await this.#config.hooks.onPostTool({ callId, name, input }, result, { sessionId: this.#session.id });
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
// 裁决 #12 修正一: the honest note rides the recovered failure too —
|
|
407
|
+
// the receipt and the repaired tool_result reproduce the live path
|
|
408
|
+
// losslessly.
|
|
409
|
+
if (result.isError && tool?.idempotent !== true) {
|
|
410
|
+
result = {
|
|
411
|
+
...result,
|
|
412
|
+
content: `${result.content}\n[non-idempotent tool failed — its side effects may have partially applied; verify before retrying]`,
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
if (result.isError) {
|
|
416
|
+
yield log.append({
|
|
417
|
+
type: "tool_execution_failed",
|
|
418
|
+
executionId,
|
|
419
|
+
callId,
|
|
420
|
+
error: result.content,
|
|
421
|
+
// P1-9: errorKind only exists on errors — runtime-guarded too.
|
|
422
|
+
...(result.isError && result.errorKind !== undefined ? { errorKind: result.errorKind } : {}),
|
|
423
|
+
safeToRetry: tool?.idempotent === true,
|
|
424
|
+
...(result.tags !== undefined ? { tags: result.tags } : {}),
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
else {
|
|
428
|
+
yield log.append({
|
|
429
|
+
type: "tool_execution_succeeded",
|
|
430
|
+
executionId,
|
|
431
|
+
callId,
|
|
432
|
+
result: { content: result.content, isError: false },
|
|
433
|
+
...(result.tags !== undefined ? { tags: result.tags } : {}),
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
yield log.append({
|
|
437
|
+
type: "tool_result",
|
|
438
|
+
callId,
|
|
439
|
+
content: result.content,
|
|
440
|
+
isError: result.isError,
|
|
441
|
+
// P1-9: errorKind only exists on errors — runtime-guarded too.
|
|
442
|
+
...(result.isError && result.errorKind !== undefined ? { errorKind: result.errorKind } : {}),
|
|
443
|
+
// 五: live tags survive the resumed path too.
|
|
444
|
+
...(result.tags !== undefined ? { tags: result.tags } : {}),
|
|
445
|
+
executionId,
|
|
446
|
+
});
|
|
447
|
+
// 裁决 #12 (ADR-0038): the failed-receipt uncertain PAUSE is REMOVED
|
|
448
|
+
// here too (it mirrored the live loop's C 组 pause) — a complete
|
|
449
|
+
// receipt IS the outcome; uncertainty belongs to the crash window
|
|
450
|
+
// alone. A retry passes the approval chain again.
|
|
451
|
+
}
|
|
452
|
+
/** The model-facing result of a durable denial — no execution happened. */
|
|
453
|
+
async *#denialResult(callId, reason) {
|
|
454
|
+
const denial = denialResult(reason);
|
|
455
|
+
yield this.#session.log.append({
|
|
456
|
+
type: "tool_result",
|
|
457
|
+
callId,
|
|
458
|
+
content: denial.content,
|
|
459
|
+
isError: true,
|
|
460
|
+
errorKind: denial.errorKind,
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
}
|
package/dist/session.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* AgentSession
|
|
2
|
+
* AgentSession — the durable multi-turn conversation (Phase C/D).
|
|
3
3
|
*
|
|
4
4
|
* A session owns ONE EventLog, seeded from disk on load and continued in
|
|
5
5
|
* memory. Each `run(input)`:
|
|
@@ -22,9 +22,14 @@
|
|
|
22
22
|
*
|
|
23
23
|
* Restart recovery is the same code path as a second run: rebuild the log
|
|
24
24
|
* from the JSONL, continue numbering where the file ended.
|
|
25
|
+
*
|
|
26
|
+
* 手感批 B4 (pure move): the Run class lives in run.ts, the recovery
|
|
27
|
+
* support in recovery.ts, the E1/E2 composition helpers in compose.ts —
|
|
28
|
+
* same package, same exports (index.ts re-exports all four).
|
|
25
29
|
*/
|
|
26
30
|
import { EventLog, type AbortSignalLike, type Adapter, type Event, type KisoExtension, type Message, type PermissionDecision, type Tool } from "@vincemakes/kiso-core";
|
|
27
31
|
import { type SessionStore } from "./store.js";
|
|
32
|
+
import { Run } from "./run.js";
|
|
28
33
|
/** A session whose disk write was rejected (stale handle) is PERMANENTLY
|
|
29
34
|
* poisoned: its in-memory log no longer matches the disk, so no further
|
|
30
35
|
* run may proceed — reload the session (一). */
|
|
@@ -49,6 +54,13 @@ export interface ApprovalRequest {
|
|
|
49
54
|
readonly name: string;
|
|
50
55
|
readonly input: Readonly<Record<string, unknown>>;
|
|
51
56
|
}
|
|
57
|
+
/** The /compact result — what the NoticeCell shows (ADR-0044). */
|
|
58
|
+
export interface SummarizeResult {
|
|
59
|
+
readonly coversToSeq: number;
|
|
60
|
+
readonly summary: string;
|
|
61
|
+
/** The estimated tokens the compression saved (chars/4 proxy). */
|
|
62
|
+
readonly savedTokens: number;
|
|
63
|
+
}
|
|
52
64
|
export declare class AgentSession {
|
|
53
65
|
#private;
|
|
54
66
|
readonly id: string;
|
|
@@ -78,6 +90,21 @@ export declare class AgentSession {
|
|
|
78
90
|
* Yields nothing when the session already completed.
|
|
79
91
|
*/
|
|
80
92
|
resume(): Run;
|
|
93
|
+
/**
|
|
94
|
+
* /compact (ADR-0044): compress the older conversation with a model
|
|
95
|
+
* summary. Covers the range (previous summary point, boundary] —
|
|
96
|
+
* boundary = the event before the keepRounds-th most recent round —
|
|
97
|
+
* and persists ONE `summarized` event. The summary call is OFF-LOOP
|
|
98
|
+
* through the session's OWN adapter: it writes nothing; a failure
|
|
99
|
+
* throws and the session is unchanged ("nothing happened"). Returns
|
|
100
|
+
* null when fewer than keepRounds+1 uncovered rounds exist (nothing
|
|
101
|
+
* worth covering yet). Crash semantics: a crash BEFORE the persist is
|
|
102
|
+
* "nothing happened"; after it, a resume projects the compressed view.
|
|
103
|
+
*/
|
|
104
|
+
summarize(options?: {
|
|
105
|
+
keepRounds?: number;
|
|
106
|
+
signal?: AbortSignalLike;
|
|
107
|
+
}): Promise<SummarizeResult | null>;
|
|
81
108
|
/**
|
|
82
109
|
* Pauses that still await a human decision (durable, survives restart).
|
|
83
110
|
* B 组: a request whose RUN has terminated is DEAD — it is neither
|
|
@@ -136,6 +163,10 @@ export interface SessionConfig {
|
|
|
136
163
|
readonly maxTurns?: number;
|
|
137
164
|
readonly maxTokens?: number;
|
|
138
165
|
readonly temperature?: number;
|
|
166
|
+
/**
|
|
167
|
+
* DEPRECATED (ADR-0044): forwarded to the loop's deprecated field,
|
|
168
|
+
* which IGNORES it — kept for type compatibility, removed at 1.0.
|
|
169
|
+
*/
|
|
139
170
|
readonly compaction?: {
|
|
140
171
|
readonly thresholdTokens: number;
|
|
141
172
|
};
|
|
@@ -152,15 +183,3 @@ export interface SessionConfig {
|
|
|
152
183
|
*/
|
|
153
184
|
readonly extensions?: readonly KisoExtension[];
|
|
154
185
|
}
|
|
155
|
-
/**
|
|
156
|
-
* A single turn. Async-iterable, so `for await (const ev of session.run(x))`
|
|
157
|
-
* is the natural shape; the handle also carries the runId and the abort.
|
|
158
|
-
*/
|
|
159
|
-
export declare class Run implements AsyncIterable<Event> {
|
|
160
|
-
#private;
|
|
161
|
-
runId: string;
|
|
162
|
-
constructor(store: SessionStore, adapter: Adapter, config: SessionConfig, session: AgentSession, input: string | undefined, externalSignal: AbortSignalLike | undefined, resume: boolean);
|
|
163
|
-
/** Cancel the run: propagates to the adapter (SDK) and future executions. */
|
|
164
|
-
abort(): void;
|
|
165
|
-
[Symbol.asyncIterator](): AsyncIterator<Event>;
|
|
166
|
-
}
|