dsh-completion-guard 0.2.1

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/index.js ADDED
@@ -0,0 +1,1125 @@
1
+ import { A as classifyClause, B as normalizeClause, C as renderRecoveryPacket, D as isVerifyingCapability, E as evidenceMatchesItem, F as segmentClauses, H as sanitizeUrl, I as COMMAND_SURFACE_MANIFEST, L as validateManifest, M as extractMethod, N as extractOperation, O as captureClause, P as isInformationalMessage, R as canonicalizePath, S as recoveryDigest, T as evidenceCoverage, U as sha256, V as sanitizeClauseText, W as createProjection, _ as classifyUserInteraction, a as goalCompletionDenial, b as closingHint, c as supersedeItem, d as extractToolSubject, f as isDeterministicCheck, g as parseShellCommand, h as parsePwshCommand, i as latestAssistantText, j as extractArtifactPaths, k as captureItem, l as evidenceFromPersistedToolResult, m as isRunExecutable, n as decideTurnStopping, o as hasCurrentCertificate, p as withDurability, r as isWholeTaskCompletionClaim, s as deriveProjection, t as classifyCompletionClaim, u as extractTextContent, v as certifyCheckpoint, w as bindingSatisfies, x as openItems, y as DEFAULT_RECOVERY_CHAR_BUDGET, z as digestStrings } from "./domain-BN3_AuUr.js";
2
+ import { boundContextSummary, createUserMessage } from "@deepseek-ai/dsh-llm";
3
+ import { defineTool } from "@deepseek-ai/dsh-tools";
4
+
5
+ //#region src/tools/checkpoint.ts
6
+ function createCheckpointTool(getProjection, onRejected) {
7
+ return defineTool({
8
+ name: "context_guard_checkpoint",
9
+ description: "Request a completion certificate from existing durable evidence.",
10
+ parameters: { bindings: {
11
+ type: "array",
12
+ required: true,
13
+ items: {
14
+ type: "object",
15
+ additionalProperties: false,
16
+ properties: {
17
+ item_id: {
18
+ type: "string",
19
+ required: true
20
+ },
21
+ evidence_ids: {
22
+ type: "array",
23
+ required: true,
24
+ items: { type: "string" }
25
+ }
26
+ }
27
+ }
28
+ } },
29
+ output: {
30
+ schema: {
31
+ type: "object",
32
+ additionalProperties: false,
33
+ properties: {
34
+ status: {
35
+ type: "string",
36
+ enum: [
37
+ "certified",
38
+ "incomplete",
39
+ "unknown"
40
+ ]
41
+ },
42
+ contract_revision: { type: "integer" },
43
+ open_items: {
44
+ type: "array",
45
+ items: { type: "string" }
46
+ },
47
+ available_evidence: {
48
+ type: "array",
49
+ items: {
50
+ type: "object",
51
+ additionalProperties: false,
52
+ properties: {
53
+ id: { type: "string" },
54
+ tool: { type: "string" },
55
+ subjects: {
56
+ type: "array",
57
+ items: { type: "string" }
58
+ },
59
+ surfaces: {
60
+ type: "array",
61
+ items: { type: "string" }
62
+ },
63
+ outcome: { type: "string" },
64
+ capabilities: {
65
+ type: "array",
66
+ items: { type: "string" }
67
+ }
68
+ }
69
+ }
70
+ },
71
+ rejected_bindings: {
72
+ type: "array",
73
+ items: {
74
+ type: "object",
75
+ additionalProperties: false,
76
+ properties: {
77
+ item_id: { type: "string" },
78
+ reason: { type: "string" },
79
+ hint: { type: "string" }
80
+ }
81
+ }
82
+ }
83
+ }
84
+ },
85
+ render: (_args, value) => [{
86
+ type: "text",
87
+ text: JSON.stringify(value)
88
+ }]
89
+ },
90
+ async execute(args) {
91
+ const projection = getProjection();
92
+ if (!projection) return {
93
+ status: "unknown",
94
+ contract_revision: 0,
95
+ open_items: [],
96
+ available_evidence: [],
97
+ rejected_bindings: []
98
+ };
99
+ const result = certifyCheckpoint(projection, args.bindings.map((binding) => ({
100
+ itemId: binding.item_id,
101
+ evidenceIds: binding.evidence_ids
102
+ })), `C${projection.checkpoints.length + 1}`);
103
+ if (!result.checkpoint) onRejected();
104
+ const available_evidence = [...projection.evidence.values()].filter((evidence) => evidence.epoch === projection.epoch && evidence.outcome === "success").sort((a, b) => a.id < b.id ? -1 : 1).map((evidence) => ({
105
+ id: evidence.id,
106
+ tool: evidence.toolName,
107
+ subjects: evidence.subjects,
108
+ surfaces: evidence.surfaces,
109
+ outcome: evidence.outcome,
110
+ capabilities: evidence.capabilities
111
+ }));
112
+ return {
113
+ status: result.status,
114
+ contract_revision: result.contractRevision,
115
+ open_items: result.openItems,
116
+ available_evidence,
117
+ rejected_bindings: result.rejectedBindings.map((binding) => ({
118
+ item_id: binding.itemId,
119
+ reason: binding.reason,
120
+ ...binding.hint !== void 0 ? { hint: binding.hint } : {}
121
+ }))
122
+ };
123
+ }
124
+ });
125
+ }
126
+
127
+ //#endregion
128
+ //#region src/commands/context-guard.ts
129
+ function pendingCount(projection) {
130
+ return [...projection.items.values()].filter((item) => item.status === "pending").length;
131
+ }
132
+ function createContextGuardCommand(projectionFor, setEnabled, clearContract) {
133
+ return {
134
+ name: "context-guard",
135
+ description: "Enable, disable, clear, inspect, or diagnose Context Guard for this session.",
136
+ recordInput: true,
137
+ input: { hint: "on|off|clear|status|diagnose" },
138
+ handler: ({ agent, rawInput }) => {
139
+ const projection = projectionFor(agent);
140
+ const [subcommand] = rawInput.trim().split(/\s+/, 1);
141
+ const resolved = subcommand || "status";
142
+ if (resolved === "on") {
143
+ setEnabled(agent, true);
144
+ return {
145
+ kind: "success",
146
+ text: "Context Guard enabled."
147
+ };
148
+ }
149
+ if (resolved === "off") {
150
+ setEnabled(agent, false);
151
+ return {
152
+ kind: "success",
153
+ text: "Context Guard disabled; history retained."
154
+ };
155
+ }
156
+ if (resolved === "clear") {
157
+ const before = pendingCount(projection);
158
+ clearContract(agent);
159
+ const after = pendingCount(projectionFor(agent));
160
+ return {
161
+ kind: "success",
162
+ text: `Context Guard contract cleared: ${before - after} requirement/acceptance item(s) superseded; ${after} pending remain (prohibitions retained).`
163
+ };
164
+ }
165
+ if (resolved !== "status" && resolved !== "diagnose") return {
166
+ kind: "error",
167
+ text: "Usage: /context-guard on|off|clear|status|diagnose"
168
+ };
169
+ const passed = [...projection.items.values()].filter((item) => item.status === "passed").length;
170
+ const response = {
171
+ enabled: projection.enabled,
172
+ epoch: projection.epoch,
173
+ contract_revision: projection.contractRevision,
174
+ pending: pendingCount(projection),
175
+ passed,
176
+ evidence: projection.evidence.size,
177
+ integrity: projection.integrity,
178
+ last_source_seq: projection.lastObservedSourceSeq
179
+ };
180
+ return {
181
+ kind: "success",
182
+ text: JSON.stringify(response)
183
+ };
184
+ }
185
+ };
186
+ }
187
+
188
+ //#endregion
189
+ //#region node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.2/node_modules/@deepseek-ai/cosmokit/lib/index.js
190
+ /** Return true when a value is `null` or `undefined`. */
191
+ function isNullable(value) {
192
+ return value === null || value === void 0;
193
+ }
194
+ /** Return true for non-array object values. */
195
+ function isPlainObject(data) {
196
+ return data && typeof data === "object" && !Array.isArray(data);
197
+ }
198
+ /** Filter object entries and return a new object. */
199
+ function filterKeys(object, filter) {
200
+ return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
201
+ }
202
+ /** Map object values while preserving the original key set. */
203
+ function mapValues(object, transform) {
204
+ return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
205
+ }
206
+ /** Pick selected keys from an object, optionally including `undefined` values. */
207
+ function pick(source, keys, forced) {
208
+ if (!keys) return { ...source };
209
+ const result = {};
210
+ for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
211
+ return result;
212
+ }
213
+ /** Test values using `instanceof` with a `toStringTag` fallback. */
214
+ function is(type, value) {
215
+ if (arguments.length === 1) return (value$1) => is(type, value$1);
216
+ return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
217
+ }
218
+ function isArrayBufferLike(value) {
219
+ return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
220
+ }
221
+ function isArrayBufferSource(value) {
222
+ return isArrayBufferLike(value) || ArrayBuffer.isView(value);
223
+ }
224
+ /** Binary source detection and base64/hex conversion helpers. */
225
+ var Binary;
226
+ (function(Binary$1) {
227
+ Binary$1.is = isArrayBufferLike;
228
+ Binary$1.isSource = isArrayBufferSource;
229
+ function fromSource(source) {
230
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
231
+ else return source;
232
+ }
233
+ Binary$1.fromSource = fromSource;
234
+ function toBase64(source) {
235
+ source = fromSource(source);
236
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
237
+ let binary = "";
238
+ const bytes = new Uint8Array(source);
239
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
240
+ return btoa(binary);
241
+ }
242
+ Binary$1.toBase64 = toBase64;
243
+ function fromBase64(source) {
244
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
245
+ return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
246
+ }
247
+ Binary$1.fromBase64 = fromBase64;
248
+ function toHex(source) {
249
+ source = fromSource(source);
250
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
251
+ return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
252
+ }
253
+ Binary$1.toHex = toHex;
254
+ function fromHex(source) {
255
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
256
+ const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
257
+ const buffer = [];
258
+ for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
259
+ return Uint8Array.from(buffer).buffer;
260
+ }
261
+ Binary$1.fromHex = fromHex;
262
+ })(Binary || (Binary = {}));
263
+ /** Decode a base64 string into binary data. */
264
+ const base64ToArrayBuffer = Binary.fromBase64;
265
+ /** Encode binary data as base64. */
266
+ const arrayBufferToBase64 = Binary.toBase64;
267
+ /** Decode a hex string into binary data. */
268
+ const hexToArrayBuffer = Binary.fromHex;
269
+ /** Encode binary data as hex. */
270
+ const arrayBufferToHex = Binary.toHex;
271
+ /** Deep-clone common JavaScript values while preserving prototypes and cycles. */
272
+ function clone(source, refs = /* @__PURE__ */ new Map()) {
273
+ if (!source || typeof source !== "object") return source;
274
+ if (is("Date", source)) return new Date(source.valueOf());
275
+ if (is("RegExp", source)) return new RegExp(source.source, source.flags);
276
+ if (isArrayBufferLike(source)) return source.slice(0);
277
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
278
+ const cached = refs.get(source);
279
+ if (cached) return cached;
280
+ if (Array.isArray(source)) {
281
+ const result$1 = [];
282
+ refs.set(source, result$1);
283
+ source.forEach((value, index) => {
284
+ result$1[index] = Reflect.apply(clone, null, [value, refs]);
285
+ });
286
+ return result$1;
287
+ }
288
+ const result = Object.create(Object.getPrototypeOf(source));
289
+ refs.set(source, result);
290
+ for (const key of Reflect.ownKeys(source)) {
291
+ const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
292
+ if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
293
+ Reflect.defineProperty(result, key, descriptor);
294
+ }
295
+ return result;
296
+ }
297
+ /** Deeply compare arrays, dates, regexps, buffers, and plain object fields. */
298
+ function deepEqual(a, b, strict) {
299
+ if (a === b) return true;
300
+ if (!strict && isNullable(a) && isNullable(b)) return true;
301
+ if (typeof a !== typeof b) return false;
302
+ if (typeof a !== "object") return false;
303
+ if (!a || !b) return false;
304
+ function check(test, then) {
305
+ return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
306
+ }
307
+ return check(Array.isArray, (a$1, b$1) => a$1.length === b$1.length && a$1.every((item, index) => deepEqual(item, b$1[index]))) ?? check(is("Date"), (a$1, b$1) => a$1.valueOf() === b$1.valueOf()) ?? check(is("RegExp"), (a$1, b$1) => a$1.source === b$1.source && a$1.flags === b$1.flags) ?? check(isArrayBufferLike, (a$1, b$1) => {
308
+ if (a$1.byteLength !== b$1.byteLength) return false;
309
+ const viewA = new Uint8Array(a$1);
310
+ const viewB = new Uint8Array(b$1);
311
+ for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
312
+ return true;
313
+ }) ?? Object.keys({
314
+ ...a,
315
+ ...b
316
+ }).every((key) => deepEqual(a[key], b[key], strict));
317
+ }
318
+ /** Time constants plus parsing and formatting helpers. */
319
+ var Time;
320
+ (function(Time$1) {
321
+ Time$1.millisecond = 1;
322
+ Time$1.second = 1e3;
323
+ Time$1.minute = Time$1.second * 60;
324
+ Time$1.hour = Time$1.minute * 60;
325
+ Time$1.day = Time$1.hour * 24;
326
+ Time$1.week = Time$1.day * 7;
327
+ let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
328
+ function setTimezoneOffset(offset) {
329
+ timezoneOffset = offset;
330
+ }
331
+ Time$1.setTimezoneOffset = setTimezoneOffset;
332
+ function getTimezoneOffset() {
333
+ return timezoneOffset;
334
+ }
335
+ Time$1.getTimezoneOffset = getTimezoneOffset;
336
+ function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
337
+ if (typeof date === "number") date = new Date(date);
338
+ if (offset === void 0) offset = timezoneOffset;
339
+ return Math.floor((date.valueOf() / Time$1.minute - offset) / 1440);
340
+ }
341
+ Time$1.getDateNumber = getDateNumber;
342
+ function fromDateNumber(value, offset) {
343
+ const date = new Date(value * Time$1.day);
344
+ if (offset === void 0) offset = timezoneOffset;
345
+ return new Date(+date + offset * Time$1.minute);
346
+ }
347
+ Time$1.fromDateNumber = fromDateNumber;
348
+ const numeric = /\d+(?:\.\d+)?/.source;
349
+ const timeRegExp = /* @__PURE__ */ new RegExp(`^${[
350
+ "w(?:eek(?:s)?)?",
351
+ "d(?:ay(?:s)?)?",
352
+ "h(?:our(?:s)?)?",
353
+ "m(?:in(?:ute)?(?:s)?)?",
354
+ "s(?:ec(?:ond)?(?:s)?)?"
355
+ ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
356
+ function parseTime(source) {
357
+ const capture = timeRegExp.exec(source);
358
+ if (!capture) return 0;
359
+ return (parseFloat(capture[1]) * Time$1.week || 0) + (parseFloat(capture[2]) * Time$1.day || 0) + (parseFloat(capture[3]) * Time$1.hour || 0) + (parseFloat(capture[4]) * Time$1.minute || 0) + (parseFloat(capture[5]) * Time$1.second || 0);
360
+ }
361
+ Time$1.parseTime = parseTime;
362
+ function parseDate(date) {
363
+ const parsed = parseTime(date);
364
+ if (parsed) date = Date.now() + parsed;
365
+ else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
366
+ else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
367
+ return date ? new Date(date) : /* @__PURE__ */ new Date();
368
+ }
369
+ Time$1.parseDate = parseDate;
370
+ function format(ms) {
371
+ const abs = Math.abs(ms);
372
+ if (abs >= Time$1.day - Time$1.hour / 2) return Math.round(ms / Time$1.day) + "d";
373
+ else if (abs >= Time$1.hour - Time$1.minute / 2) return Math.round(ms / Time$1.hour) + "h";
374
+ else if (abs >= Time$1.minute - Time$1.second / 2) return Math.round(ms / Time$1.minute) + "m";
375
+ else if (abs >= Time$1.second) return Math.round(ms / Time$1.second) + "s";
376
+ return ms + "ms";
377
+ }
378
+ Time$1.format = format;
379
+ function toDigits(source, length = 2) {
380
+ return source.toString().padStart(length, "0");
381
+ }
382
+ Time$1.toDigits = toDigits;
383
+ function template(template$1, time = /* @__PURE__ */ new Date()) {
384
+ return template$1.replace("yyyy", time.getFullYear().toString()).replace("yy", time.getFullYear().toString().slice(2)).replace("MM", toDigits(time.getMonth() + 1)).replace("dd", toDigits(time.getDate())).replace("hh", toDigits(time.getHours())).replace("mm", toDigits(time.getMinutes())).replace("ss", toDigits(time.getSeconds())).replace("SSS", toDigits(time.getMilliseconds(), 3));
385
+ }
386
+ Time$1.template = template;
387
+ })(Time || (Time = {}));
388
+
389
+ //#endregion
390
+ //#region node_modules/.pnpm/@deepseek-ai+schemastery@3.18.1/node_modules/@deepseek-ai/schemastery/lib/index.mjs
391
+ const kSchema = Symbol.for("schemastery");
392
+ const kValidationError = Symbol.for("ValidationError");
393
+ globalThis.__schemastery_index__ ??= 0;
394
+ globalThis.__schemastery_refs__ = void 0;
395
+ var ValidationError = class extends TypeError {
396
+ options;
397
+ name = "ValidationError";
398
+ constructor(message, options) {
399
+ let prefix = "$";
400
+ for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
401
+ else if (typeof segment === "number") prefix += "[" + segment + "]";
402
+ else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
403
+ if (prefix.startsWith(".")) prefix = prefix.slice(1);
404
+ super((prefix === "$" ? "" : `${prefix} `) + message);
405
+ this.options = options;
406
+ }
407
+ static is(error) {
408
+ return !!error?.[kValidationError];
409
+ }
410
+ };
411
+ Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
412
+ const Schema = function(options) {
413
+ const schema = function(data, options$1 = {}) {
414
+ return Schema.resolve(data, schema, options$1)[0];
415
+ };
416
+ if (options.refs) {
417
+ const refs = mapValues(options.refs, (options$1) => new Schema(options$1));
418
+ const getRef = (uid) => refs[uid];
419
+ for (const key in refs) {
420
+ const options$1 = refs[key];
421
+ options$1.sKey = getRef(options$1.sKey);
422
+ options$1.inner = getRef(options$1.inner);
423
+ options$1.list = options$1.list && options$1.list.map(getRef);
424
+ options$1.dict = options$1.dict && mapValues(options$1.dict, getRef);
425
+ }
426
+ return refs[options.uid];
427
+ }
428
+ Object.assign(schema, options);
429
+ if (typeof schema.callback === "string") try {
430
+ schema.callback = new Function("return " + schema.callback)();
431
+ } catch {}
432
+ Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
433
+ Object.setPrototypeOf(schema, Schema.prototype);
434
+ schema.meta ||= {};
435
+ schema.toString = schema.toString.bind(schema);
436
+ return schema;
437
+ };
438
+ Schema.prototype = Object.create(Function.prototype);
439
+ Schema.prototype[kSchema] = true;
440
+ Object.defineProperty(Schema.prototype, "~standard", { get() {
441
+ return {
442
+ version: 1,
443
+ vendor: "schemastery",
444
+ validate: (value) => {
445
+ try {
446
+ return { value: Schema.resolve(value, this, {})[0] };
447
+ } catch (error) {
448
+ if (ValidationError.is(error)) return { issues: [{
449
+ message: error.message,
450
+ path: error.options.path
451
+ }] };
452
+ throw error;
453
+ }
454
+ }
455
+ };
456
+ } });
457
+ Schema.ValidationError = ValidationError;
458
+ Schema.prototype.toJSON = function toJSON() {
459
+ if (globalThis.__schemastery_refs__) {
460
+ globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
461
+ return this.uid;
462
+ }
463
+ globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
464
+ globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
465
+ const result = {
466
+ uid: this.uid,
467
+ refs: globalThis.__schemastery_refs__
468
+ };
469
+ globalThis.__schemastery_refs__ = void 0;
470
+ return result;
471
+ };
472
+ Schema.prototype.set = function set(key, value) {
473
+ this.dict[key] = value;
474
+ return this;
475
+ };
476
+ Schema.prototype.push = function push(value) {
477
+ this.list.push(value);
478
+ return this;
479
+ };
480
+ function mergeDesc(original, messages) {
481
+ const result = typeof original === "string" ? { "": original } : { ...original };
482
+ for (const locale in messages) {
483
+ const value = messages[locale];
484
+ if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
485
+ else if (typeof value === "string") result[locale] = value;
486
+ }
487
+ return result;
488
+ }
489
+ function getInner(value) {
490
+ return value?.$value ?? value?.$inner;
491
+ }
492
+ function extractKeys(data) {
493
+ return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
494
+ }
495
+ Schema.prototype.i18n = function i18n(messages) {
496
+ const schema = Schema(this);
497
+ const desc = mergeDesc(schema.meta.description, messages);
498
+ if (Object.keys(desc).length) schema.meta.description = desc;
499
+ if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
500
+ return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
501
+ });
502
+ if (schema.list) schema.list = schema.list.map((inner, index) => {
503
+ return inner.i18n(mapValues(messages, (data = {}) => {
504
+ if (Array.isArray(getInner(data))) return getInner(data)[index];
505
+ if (Array.isArray(data)) return data[index];
506
+ return extractKeys(data);
507
+ }));
508
+ });
509
+ if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
510
+ if (getInner(data)) return getInner(data);
511
+ return extractKeys(data);
512
+ }));
513
+ if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
514
+ return schema;
515
+ };
516
+ Schema.prototype.extra = function extra(key, value) {
517
+ const schema = Schema(this);
518
+ schema.meta = {
519
+ ...schema.meta,
520
+ [key]: value
521
+ };
522
+ return schema;
523
+ };
524
+ for (const key of [
525
+ "required",
526
+ "disabled",
527
+ "collapse",
528
+ "hidden",
529
+ "loose"
530
+ ]) Object.assign(Schema.prototype, { [key](value = true) {
531
+ const schema = Schema(this);
532
+ schema.meta = {
533
+ ...schema.meta,
534
+ [key]: value
535
+ };
536
+ return schema;
537
+ } });
538
+ Schema.prototype.deprecated = function deprecated() {
539
+ const schema = Schema(this);
540
+ schema.meta.badges ||= [];
541
+ schema.meta.badges.push({
542
+ text: "deprecated",
543
+ type: "danger"
544
+ });
545
+ return schema;
546
+ };
547
+ Schema.prototype.experimental = function experimental() {
548
+ const schema = Schema(this);
549
+ schema.meta.badges ||= [];
550
+ schema.meta.badges.push({
551
+ text: "experimental",
552
+ type: "warning"
553
+ });
554
+ return schema;
555
+ };
556
+ Schema.prototype.pattern = function pattern(regexp) {
557
+ const schema = Schema(this);
558
+ const pattern$1 = pick(regexp, ["source", "flags"]);
559
+ schema.meta = {
560
+ ...schema.meta,
561
+ pattern: pattern$1
562
+ };
563
+ return schema;
564
+ };
565
+ Schema.prototype.simplify = function simplify(value) {
566
+ if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
567
+ if (isNullable(value)) return value;
568
+ if (this.type === "object" || this.type === "dict") {
569
+ const result = {};
570
+ for (const key in value) {
571
+ const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
572
+ if (this.type === "dict" || !isNullable(item)) result[key] = item;
573
+ }
574
+ if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
575
+ return result;
576
+ } else if (this.type === "array" || this.type === "tuple") {
577
+ const result = [];
578
+ value.forEach((value$1, index) => {
579
+ const schema = this.type === "array" ? this.inner : this.list[index];
580
+ const item = schema ? schema.simplify(value$1) : value$1;
581
+ result.push(item);
582
+ });
583
+ return result;
584
+ } else if (this.type === "intersect") {
585
+ const result = {};
586
+ for (const item of this.list) Object.assign(result, item.simplify(value));
587
+ return result;
588
+ } else if (this.type === "union") for (const schema of this.list) try {
589
+ Schema.resolve(value, schema, {});
590
+ return schema.simplify(value);
591
+ } catch {}
592
+ return value;
593
+ };
594
+ Schema.prototype.toString = function toString(inline) {
595
+ return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
596
+ };
597
+ Schema.prototype.role = function role(role$1, extra) {
598
+ const schema = Schema(this);
599
+ schema.meta = {
600
+ ...schema.meta,
601
+ role: role$1,
602
+ extra
603
+ };
604
+ return schema;
605
+ };
606
+ for (const key of [
607
+ "default",
608
+ "link",
609
+ "comment",
610
+ "description",
611
+ "max",
612
+ "min",
613
+ "step"
614
+ ]) Object.assign(Schema.prototype, { [key](value) {
615
+ const schema = Schema(this);
616
+ schema.meta = {
617
+ ...schema.meta,
618
+ [key]: value
619
+ };
620
+ return schema;
621
+ } });
622
+ const resolvers = {};
623
+ Schema.extend = function extend(type, resolve) {
624
+ resolvers[type] = resolve;
625
+ };
626
+ Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
627
+ if (!schema) return [data];
628
+ if (options.ignore?.(data, schema)) return [data];
629
+ if (isNullable(data) && schema.type !== "lazy") {
630
+ if (schema.meta.required) throw new ValidationError(`missing required value`, options);
631
+ let current = schema;
632
+ let fallback = schema.meta.default;
633
+ while (current?.type === "intersect" && isNullable(fallback)) {
634
+ current = current.list[0];
635
+ fallback = current?.meta.default;
636
+ }
637
+ if (isNullable(fallback)) return [data];
638
+ data = clone(fallback);
639
+ }
640
+ const callback = resolvers[schema.type];
641
+ if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
642
+ try {
643
+ return callback(data, schema, options, strict);
644
+ } catch (error) {
645
+ if (!schema.meta.loose) throw error;
646
+ return [schema.meta.default];
647
+ }
648
+ };
649
+ Schema.from = function from(source) {
650
+ if (isNullable(source)) return Schema.any();
651
+ else if ([
652
+ "string",
653
+ "number",
654
+ "boolean"
655
+ ].includes(typeof source)) return Schema.const(source).required();
656
+ else if (source[kSchema]) return source;
657
+ else if (typeof source === "function") switch (source) {
658
+ case String: return Schema.string().required();
659
+ case Number: return Schema.number().required();
660
+ case Boolean: return Schema.boolean().required();
661
+ case Function: return Schema.function().required();
662
+ default: return Schema.is(source).required();
663
+ }
664
+ else throw new TypeError(`cannot infer schema from ${source}`);
665
+ };
666
+ Schema.lazy = function lazy(builder) {
667
+ const toJSON = () => {
668
+ if (!schema.inner[kSchema]) {
669
+ schema.inner = schema.builder();
670
+ schema.inner.meta = {
671
+ ...schema.meta,
672
+ ...schema.inner.meta
673
+ };
674
+ }
675
+ return schema.inner.toJSON();
676
+ };
677
+ const schema = new Schema({
678
+ type: "lazy",
679
+ builder,
680
+ inner: { toJSON }
681
+ });
682
+ return schema;
683
+ };
684
+ Schema.natural = function natural() {
685
+ return Schema.number().step(1).min(0);
686
+ };
687
+ Schema.percent = function percent() {
688
+ return Schema.number().step(.01).min(0).max(1).role("slider");
689
+ };
690
+ Schema.date = function date() {
691
+ return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
692
+ const date$1 = new Date(value);
693
+ if (isNaN(+date$1)) throw new ValidationError(`invalid date "${value}"`, options);
694
+ return date$1;
695
+ }, true)]);
696
+ };
697
+ Schema.regExp = function regExp(flag = "") {
698
+ return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
699
+ try {
700
+ return new RegExp(value, flag);
701
+ } catch (e) {
702
+ throw new ValidationError(e.message, options);
703
+ }
704
+ }, true)]);
705
+ };
706
+ Schema.arrayBuffer = function arrayBuffer(encoding) {
707
+ return Schema.union([
708
+ Schema.is(ArrayBuffer),
709
+ Schema.is(SharedArrayBuffer),
710
+ Schema.transform(Schema.any(), (value, options) => {
711
+ if (Binary.isSource(value)) return Binary.fromSource(value);
712
+ throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
713
+ }, true),
714
+ ...encoding ? [Schema.transform(Schema.string(), (value, options) => {
715
+ try {
716
+ return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
717
+ } catch (e) {
718
+ throw new ValidationError(e.message, options);
719
+ }
720
+ }, true)] : []
721
+ ]);
722
+ };
723
+ Schema.extend("lazy", (data, schema, options, strict) => {
724
+ if (!schema.inner[kSchema]) {
725
+ schema.inner = schema.builder();
726
+ schema.inner.meta = {
727
+ ...schema.meta,
728
+ ...schema.inner.meta
729
+ };
730
+ }
731
+ return Schema.resolve(data, schema.inner, options, strict);
732
+ });
733
+ Schema.extend("any", (data) => {
734
+ return [data];
735
+ });
736
+ Schema.extend("never", (data, _, options) => {
737
+ throw new ValidationError(`expected nullable but got ${data}`, options);
738
+ });
739
+ Schema.extend("const", (data, { value }, options) => {
740
+ if (deepEqual(data, value)) return [value];
741
+ throw new ValidationError(`expected ${value} but got ${data}`, options);
742
+ });
743
+ function checkWithinRange(data, meta, description, options, skipMin = false) {
744
+ const { max = Infinity, min = -Infinity } = meta;
745
+ if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
746
+ if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
747
+ }
748
+ Schema.extend("string", (data, { meta }, options) => {
749
+ if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
750
+ if (meta.pattern) {
751
+ const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
752
+ if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
753
+ }
754
+ checkWithinRange(data.length, meta, "string length", options);
755
+ return [data];
756
+ });
757
+ function decimalShift(data, digits) {
758
+ const str = data.toString();
759
+ if (str.includes("e")) return data * Math.pow(10, digits);
760
+ const index = str.indexOf(".");
761
+ if (index === -1) return data * Math.pow(10, digits);
762
+ const frac = str.slice(index + 1);
763
+ const integer = str.slice(0, index);
764
+ if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
765
+ return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
766
+ }
767
+ function isMultipleOf(data, min, step) {
768
+ step = Math.abs(step);
769
+ if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
770
+ const index = step.toString().indexOf(".");
771
+ const digits = step.toString().slice(index + 1).length;
772
+ return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
773
+ }
774
+ Schema.extend("number", (data, { meta }, options) => {
775
+ if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
776
+ checkWithinRange(data, meta, "number", options);
777
+ const { step } = meta;
778
+ if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
779
+ return [data];
780
+ });
781
+ Schema.extend("boolean", (data, _, options) => {
782
+ if (typeof data === "boolean") return [data];
783
+ throw new ValidationError(`expected boolean but got ${data}`, options);
784
+ });
785
+ Schema.extend("bitset", (data, { bits, meta }, options) => {
786
+ let value = 0, keys = [];
787
+ if (typeof data === "number") {
788
+ value = data;
789
+ for (const key in bits) if (data & bits[key]) keys.push(key);
790
+ } else if (Array.isArray(data)) {
791
+ keys = data;
792
+ for (const key of keys) {
793
+ if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
794
+ if (key in bits) value |= bits[key];
795
+ }
796
+ } else throw new ValidationError(`expected number or array but got ${data}`, options);
797
+ if (value === meta.default) return [value];
798
+ return [value, keys];
799
+ });
800
+ Schema.extend("function", (data, _, options) => {
801
+ if (typeof data === "function") return [data];
802
+ throw new ValidationError(`expected function but got ${data}`, options);
803
+ });
804
+ Schema.extend("is", (data, { constructor }, options) => {
805
+ if (typeof constructor === "function") {
806
+ if (data instanceof constructor) return [data];
807
+ throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
808
+ } else {
809
+ if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
810
+ let prototype = Object.getPrototypeOf(data);
811
+ while (prototype) {
812
+ if (prototype.constructor?.name === constructor) return [data];
813
+ prototype = Object.getPrototypeOf(prototype);
814
+ }
815
+ throw new ValidationError(`expected ${constructor} but got ${data}`, options);
816
+ }
817
+ });
818
+ function property(data, key, schema, options) {
819
+ try {
820
+ const [value, adapted] = Schema.resolve(data[key], schema, {
821
+ ...options,
822
+ path: [...options.path || [], key]
823
+ });
824
+ if (adapted !== void 0) data[key] = adapted;
825
+ return value;
826
+ } catch (e) {
827
+ if (!options?.autofix) throw e;
828
+ delete data[key];
829
+ return schema.meta.default;
830
+ }
831
+ }
832
+ Schema.extend("array", (data, { inner, meta }, options) => {
833
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
834
+ checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
835
+ return [data.map((_, index) => property(data, index, inner, options))];
836
+ });
837
+ Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
838
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
839
+ const result = {};
840
+ for (const key in data) {
841
+ let rKey;
842
+ try {
843
+ rKey = Schema.resolve(key, sKey, options)[0];
844
+ } catch (error) {
845
+ if (strict) continue;
846
+ throw error;
847
+ }
848
+ result[rKey] = property(data, key, inner, options);
849
+ data[rKey] = data[key];
850
+ if (key !== rKey) delete data[key];
851
+ }
852
+ return [result];
853
+ });
854
+ Schema.extend("tuple", (data, { list }, options, strict) => {
855
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
856
+ const result = list.map((inner, index) => property(data, index, inner, options));
857
+ if (strict) return [result];
858
+ result.push(...data.slice(list.length));
859
+ return [result];
860
+ });
861
+ function merge(result, data) {
862
+ for (const key in data) {
863
+ if (key in result) continue;
864
+ result[key] = data[key];
865
+ }
866
+ }
867
+ Schema.extend("object", (data, { dict }, options, strict) => {
868
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
869
+ const result = {};
870
+ for (const key in dict) {
871
+ const value = property(data, key, dict[key], options);
872
+ if (!isNullable(value) || key in data) result[key] = value;
873
+ }
874
+ if (!strict) merge(result, data);
875
+ return [result];
876
+ });
877
+ Schema.extend("union", (data, { list, toString }, options, strict) => {
878
+ const messages = [];
879
+ for (const inner of list) try {
880
+ return Schema.resolve(data, inner, options, strict);
881
+ } catch (error) {
882
+ messages.push(error);
883
+ }
884
+ throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
885
+ });
886
+ Schema.extend("intersect", (data, { list, toString }, options, strict) => {
887
+ if (!list.length) return [data];
888
+ let result;
889
+ for (const inner of list) {
890
+ const value = Schema.resolve(data, inner, options, true)[0];
891
+ if (isNullable(value)) continue;
892
+ if (isNullable(result)) result = value;
893
+ else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
894
+ else if (typeof value === "object") merge(result ??= {}, value);
895
+ else if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
896
+ }
897
+ if (!strict && isPlainObject(data)) merge(result, data);
898
+ return [result];
899
+ });
900
+ Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
901
+ const [result, adapted = data] = Schema.resolve(data, inner, options, true);
902
+ if (preserve) return [callback(result)];
903
+ else return [callback(result), callback(adapted)];
904
+ });
905
+ const formatters = {};
906
+ function defineMethod(name$1, keys, format) {
907
+ formatters[name$1] = format;
908
+ Object.assign(Schema, { [name$1](...args) {
909
+ const schema = new Schema({ type: name$1 });
910
+ keys.forEach((key, index) => {
911
+ switch (key) {
912
+ case "sKey":
913
+ schema.sKey = args[index] ?? Schema.string();
914
+ break;
915
+ case "inner":
916
+ schema.inner = Schema.from(args[index]);
917
+ break;
918
+ case "list":
919
+ schema.list = args[index].map(Schema.from);
920
+ break;
921
+ case "dict":
922
+ schema.dict = mapValues(args[index], Schema.from);
923
+ break;
924
+ case "bits":
925
+ schema.bits = {};
926
+ for (const key$1 in args[index]) {
927
+ if (typeof args[index][key$1] !== "number") continue;
928
+ schema.bits[key$1] = args[index][key$1];
929
+ }
930
+ break;
931
+ case "callback": {
932
+ const callback = schema.callback = args[index];
933
+ callback["toJSON"] ||= () => callback.toString();
934
+ break;
935
+ }
936
+ case "constructor": {
937
+ const constructor = schema.constructor = args[index];
938
+ if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
939
+ break;
940
+ }
941
+ default: schema[key] = args[index];
942
+ }
943
+ });
944
+ if (name$1 === "object" || name$1 === "dict") schema.meta.default = {};
945
+ else if (name$1 === "array" || name$1 === "tuple") schema.meta.default = [];
946
+ else if (name$1 === "bitset") schema.meta.default = 0;
947
+ return schema;
948
+ } });
949
+ }
950
+ defineMethod("is", ["constructor"], ({ constructor }) => {
951
+ if (typeof constructor === "function") return constructor.name;
952
+ else return constructor;
953
+ });
954
+ defineMethod("any", [], () => "any");
955
+ defineMethod("never", [], () => "never");
956
+ defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
957
+ defineMethod("string", [], () => "string");
958
+ defineMethod("number", [], () => "number");
959
+ defineMethod("boolean", [], () => "boolean");
960
+ defineMethod("bitset", ["bits"], () => "bitset");
961
+ defineMethod("function", [], () => "function");
962
+ defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
963
+ defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
964
+ defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
965
+ defineMethod("object", ["dict"], ({ dict }) => {
966
+ if (Object.keys(dict).length === 0) return "{}";
967
+ return `{ ${Object.entries(dict).map(([key, inner]) => {
968
+ return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
969
+ }).join(", ")} }`;
970
+ });
971
+ defineMethod("union", ["list"], ({ list }, inline) => {
972
+ const result = list.map(({ toString: format }) => format()).join(" | ");
973
+ return inline ? `(${result})` : result;
974
+ });
975
+ defineMethod("intersect", ["list"], ({ list }) => {
976
+ return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
977
+ });
978
+ defineMethod("transform", [
979
+ "inner",
980
+ "callback",
981
+ "preserve"
982
+ ], ({ inner }, isInner) => inner.toString(isInner));
983
+
984
+ //#endregion
985
+ //#region src/config.ts
986
+ const Config = Schema.object({ activation: Schema.string().default("opt-in") });
987
+ function resolveConfig(config) {
988
+ const activation = config.activation ?? "opt-in";
989
+ if (activation !== "opt-in" && activation !== "always") throw new TypeError(`activation must be "opt-in" or "always", received ${JSON.stringify(activation)}`);
990
+ return { activation };
991
+ }
992
+
993
+ //#endregion
994
+ //#region src/runtime.ts
995
+ const MAX_CONTINUATION_ATTEMPTS_PER_TURN = 2;
996
+ const name = "context-guard";
997
+ const inject = ["sessions", "commands"];
998
+ function createRuntime(agent, config) {
999
+ const projection = createProjection();
1000
+ const session = agent.session;
1001
+ let pendingRecovery = false;
1002
+ let durabilityConfirmed = false;
1003
+ let observedEpoch = -1;
1004
+ let observedCompactionSeq = -1;
1005
+ const continuationAttempts = projection.continuationAttempts;
1006
+ const rebuild = () => {
1007
+ const header = session.header;
1008
+ const priorRecoveryDigest = projection.lastRecoveryDigest;
1009
+ const derived = deriveProjection(session.events, { activation: config.activation }, { cwd: typeof header?.cwd === "string" ? header.cwd : "" }, durabilityConfirmed);
1010
+ Object.assign(projection, derived.projection);
1011
+ projection.continuationAttempts = continuationAttempts;
1012
+ projection.lastRecoveryDigest = priorRecoveryDigest;
1013
+ if (observedEpoch >= 0 && derived.projection.epoch > observedEpoch) {
1014
+ pendingRecovery = true;
1015
+ projection.lastRecoveryDigest = void 0;
1016
+ }
1017
+ observedEpoch = derived.projection.epoch;
1018
+ if (derived.lastCompactionSeq > observedCompactionSeq) {
1019
+ pendingRecovery = true;
1020
+ observedCompactionSeq = derived.lastCompactionSeq;
1021
+ }
1022
+ };
1023
+ const sync = () => {
1024
+ rebuild();
1025
+ };
1026
+ const setEnabled = (_enabled) => {
1027
+ rebuild();
1028
+ };
1029
+ const setDurability = (confirmed) => {
1030
+ durabilityConfirmed = confirmed;
1031
+ };
1032
+ const markRecoveryNeeded = () => {
1033
+ pendingRecovery = true;
1034
+ };
1035
+ const consumeRecovery = () => {
1036
+ const was = pendingRecovery;
1037
+ pendingRecovery = false;
1038
+ return was;
1039
+ };
1040
+ rebuild();
1041
+ return {
1042
+ projection,
1043
+ session,
1044
+ sync,
1045
+ setEnabled,
1046
+ setDurability,
1047
+ markRecoveryNeeded,
1048
+ consumeRecovery
1049
+ };
1050
+ }
1051
+ function apply(ctx, rawConfig = {}) {
1052
+ const config = resolveConfig(rawConfig);
1053
+ const runtimes = /* @__PURE__ */ new Map();
1054
+ const ensure = (agent) => {
1055
+ let runtime = runtimes.get(agent);
1056
+ if (!runtime) {
1057
+ runtime = createRuntime(agent, config);
1058
+ runtimes.set(agent, runtime);
1059
+ }
1060
+ return runtime;
1061
+ };
1062
+ ctx.commands.register(createContextGuardCommand((agent) => ensure(agent).projection, (agent, enabled) => ensure(agent).setEnabled(enabled), (agent) => ensure(agent).sync()));
1063
+ ctx.on("agent/session-start", ({ agent, source }) => {
1064
+ const runtime = ensure(agent);
1065
+ runtime.sync();
1066
+ if (source === "resume" || source === "compact") {
1067
+ runtime.projection.lastRecoveryDigest = void 0;
1068
+ runtime.markRecoveryNeeded();
1069
+ }
1070
+ agent.ctx.tools.register(createCheckpointTool(() => runtime.projection, () => runtime.markRecoveryNeeded()));
1071
+ agent.ctx.tools.guard((exec) => goalCompletionDenial(runtime.projection, exec.name, exec.arguments));
1072
+ });
1073
+ ctx.on("agent/pre-step", async ({ agent }, next) => {
1074
+ const durability = await ctx.sessions.flush(agent.session);
1075
+ const runtime = ensure(agent);
1076
+ runtime.setDurability(durability);
1077
+ runtime.sync();
1078
+ const decision = await next();
1079
+ if (decision.kind === "enter" && runtime.projection.enabled && runtime.consumeRecovery()) {
1080
+ const recovery = renderRecoveryPacket(runtime.projection, { charBudget: 4e3 });
1081
+ const digest = recovery ? recoveryDigest(recovery, runtime.projection) : void 0;
1082
+ if (recovery && digest !== runtime.projection.lastRecoveryDigest) {
1083
+ runtime.projection.lastRecoveryDigest = digest;
1084
+ decision.messages = [...decision.messages, createUserMessage({
1085
+ content: [{
1086
+ type: "text",
1087
+ text: `Open task requirements (recovered after compaction or resume):\n${recovery}`
1088
+ }],
1089
+ source: {
1090
+ kind: "plugin",
1091
+ plugin: "context-guard",
1092
+ form: "notice",
1093
+ summary: boundContextSummary("recovering open task requirements")
1094
+ }
1095
+ })];
1096
+ }
1097
+ }
1098
+ return decision;
1099
+ });
1100
+ ctx.on("agent/turn-stopping", async ({ agent, turn }) => {
1101
+ const durability = await ctx.sessions.flush(agent.session);
1102
+ const runtime = ensure(agent);
1103
+ runtime.setDurability(durability);
1104
+ runtime.sync();
1105
+ const assistantText = latestAssistantText(runtime.session.events);
1106
+ if (decideTurnStopping(runtime.projection, assistantText, turn, MAX_CONTINUATION_ATTEMPTS_PER_TURN).action === "continue") {
1107
+ const recovery = renderRecoveryPacket(runtime.projection, { charBudget: 4e3 });
1108
+ agent.steer(createUserMessage({
1109
+ content: [{
1110
+ type: "text",
1111
+ text: `Completion is not certified. ${recovery}`
1112
+ }],
1113
+ source: {
1114
+ kind: "plugin",
1115
+ plugin: "context-guard",
1116
+ form: "notice",
1117
+ summary: boundContextSummary("completion requires a Context Guard checkpoint")
1118
+ }
1119
+ }));
1120
+ }
1121
+ });
1122
+ }
1123
+
1124
+ //#endregion
1125
+ export { COMMAND_SURFACE_MANIFEST, Config, DEFAULT_RECOVERY_CHAR_BUDGET, apply, bindingSatisfies, canonicalizePath, captureClause, captureItem, certifyCheckpoint, classifyClause, classifyCompletionClaim, classifyUserInteraction, closingHint, createProjection, decideTurnStopping, deriveProjection, digestStrings, evidenceCoverage, evidenceFromPersistedToolResult, evidenceMatchesItem, extractArtifactPaths, extractMethod, extractOperation, extractTextContent, extractToolSubject, goalCompletionDenial, hasCurrentCertificate, inject, isDeterministicCheck, isInformationalMessage, isRunExecutable, isVerifyingCapability, isWholeTaskCompletionClaim, latestAssistantText, name, normalizeClause, openItems, parsePwshCommand, parseShellCommand, recoveryDigest, renderRecoveryPacket, sanitizeClauseText, sanitizeUrl, segmentClauses, sha256, supersedeItem, validateManifest, withDurability };