ceulen 0.29.1 → 0.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +105 -5
- package/extensions/lib/test/audit-attestations.test.sh +187 -0
- package/extensions/lib/test/check-provenance-fixtures.test.sh +81 -0
- package/extensions/lib/test/smoke-install.test.sh +103 -0
- package/extensions/modules/repair/configPanel.ts +32 -2
- package/extensions/modules/repair/index.ts +126 -0
- package/extensions/modules/repair/lib/clock.ts +106 -0
- package/extensions/modules/repair/lib/repeat-reminder.ts +90 -0
- package/extensions/modules/repair/lib/settings.ts +22 -1
- package/extensions/modules/repair/lib/spill-store.ts +72 -0
- package/extensions/modules/repair/lib/spill.ts +287 -0
- package/extensions/modules/repair/test/clock.test.ts +85 -0
- package/extensions/modules/repair/test/dsh-enrichments.test.ts +375 -0
- package/extensions/modules/repair/test/repeat-reminder.test.ts +100 -0
- package/extensions/modules/repair/test/settings.test.ts +5 -1
- package/extensions/modules/repair/test/spill-utf8.test.ts +297 -0
- package/extensions/modules/repair/test/spill.test.ts +208 -0
- package/package.json +2 -2
- package/scripts/audit-attestations.sh +139 -0
- package/scripts/check-provenance-fixtures.sh +93 -0
- package/scripts/smoke-install.sh +90 -0
- package/scripts/verify-provenance.sh +45 -0
|
@@ -17,6 +17,13 @@
|
|
|
17
17
|
* - apply_patch (Codex-style V4D diffs) and str_replace_editor (DSH Minimal
|
|
18
18
|
* pair) as new tools.
|
|
19
19
|
* - a `tool_call` guard hook and the `/repair` status command.
|
|
20
|
+
* - three DeepSeek Harness enrichments (2026-11): a `tool_result` SPILL policy
|
|
21
|
+
* (oversized results keep head+tail, the full text lands in a retrievable
|
|
22
|
+
* file), a `tool_result` REPEAT-CALL reminder (advisory footer at the
|
|
23
|
+
* 3rd/5th/8th identical call — targets Flash's loop failure mode), and a
|
|
24
|
+
* `before_agent_start` CLOCK (pi injects no date/time anywhere). Spill is
|
|
25
|
+
* scoped to RETURNED content: stock read/bash truncate inside the tool
|
|
26
|
+
* before `tool_result` fires, so their dropped bytes are already gone.
|
|
20
27
|
*
|
|
21
28
|
* Settings (`repair` section, lib/settings.ts) are read PER TOOL CALL, so the
|
|
22
29
|
* /config toggles apply to the next turn. Exception: the bash description
|
|
@@ -43,6 +50,10 @@ import {
|
|
|
43
50
|
import { Type } from "typebox";
|
|
44
51
|
import { abortAllBgJobs, bashAutoBgClause, setBgDeliveryEnabled, wrapWithAutoBg } from "./lib/auto-bg.js";
|
|
45
52
|
import { killPersistentShells, persistentBashClause, wrapWithPersistentShell } from "./lib/persistent-bash.js";
|
|
53
|
+
import { DEFAULT_CLOCK_REFRESH_MS, renderClock, shouldInject, type ClockState } from "./lib/clock.js";
|
|
54
|
+
import { advanceChain, type RepeatChain } from "./lib/repeat-reminder.js";
|
|
55
|
+
import { DEFAULT_SPILL_MAX_TOKENS, estimateTokens, formatSpillNotice, longestLineLength, retainContent, shortestLineLength } from "./lib/spill.js";
|
|
56
|
+
import { saveSpill } from "./lib/spill-store.js";
|
|
46
57
|
import {
|
|
47
58
|
computeRetryEdit,
|
|
48
59
|
isEditMismatchError,
|
|
@@ -668,6 +679,15 @@ export default function repairModule(pi: ExtensionAPI) {
|
|
|
668
679
|
// unresolvable misses on the same file (26% retry-fail tail).
|
|
669
680
|
const editMismatchCounts = new Map<string, number>();
|
|
670
681
|
|
|
682
|
+
// Per-session advisory/awareness state, keyed by session id (persistent-bash
|
|
683
|
+
// pattern). Keyed maps cannot collide across sessions, so no isChildSession
|
|
684
|
+
// gate is needed — the a2a contamination incident was UNKEYED module scope.
|
|
685
|
+
const repeatChains = new Map<string, RepeatChain>();
|
|
686
|
+
const clockStates = new Map<string, ClockState>();
|
|
687
|
+
const sessionKey = (id?: string): string => id ?? process.env.PI_SESSION_ID ?? "_default_";
|
|
688
|
+
/** Separator between retained head and tail in a spilled result. */
|
|
689
|
+
const GAP_TEXT = "\n\n[...]\n\n";
|
|
690
|
+
|
|
671
691
|
const onRepair = (toolName: string, repairs: readonly RepairKind[]) => {
|
|
672
692
|
repairCounts.set(toolName, (repairCounts.get(toolName) ?? 0) + 1);
|
|
673
693
|
};
|
|
@@ -867,6 +887,109 @@ export default function repairModule(pi: ExtensionAPI) {
|
|
|
867
887
|
}
|
|
868
888
|
});
|
|
869
889
|
|
|
890
|
+
// ── tool_result: spill + repeat-tool-reminder (ALL models) ──
|
|
891
|
+
// Both are ADVISORY: they rewrite the model-visible result and never block.
|
|
892
|
+
pi.on("tool_result", async (event, ctx) => {
|
|
893
|
+
const live = readRepairSettings(ctx?.cwd);
|
|
894
|
+
const key = sessionKey(ctx?.sessionManager?.getSessionId?.());
|
|
895
|
+
// Nested calls (a codemode script fanning out) are the parent's business;
|
|
896
|
+
// DSH skips them for both features and so do we.
|
|
897
|
+
const nested = typeof (event as any).parentToolCallId === "string";
|
|
898
|
+
|
|
899
|
+
let content = [...event.content];
|
|
900
|
+
let changed = false;
|
|
901
|
+
|
|
902
|
+
// Repeat-tool-reminder: counts EXACT repeats of ALLOWED calls, which the
|
|
903
|
+
// blocking guards (permission doom-loop, munin dampener) never see.
|
|
904
|
+
if (live.repeatReminder && !nested) {
|
|
905
|
+
const advanced = advanceChain(repeatChains.get(key), event.toolName, event.input);
|
|
906
|
+
if (advanced) {
|
|
907
|
+
repeatChains.set(key, advanced.chain);
|
|
908
|
+
if (advanced.footer) {
|
|
909
|
+
const lastText = [...content].reverse().find((b): b is { type: "text"; text: string } => b.type === "text");
|
|
910
|
+
content = lastText
|
|
911
|
+
? content.map((b) => (b === lastText ? { ...b, text: `${lastText.text}${advanced.footer}` } : b))
|
|
912
|
+
: [...content, { type: "text", text: advanced.footer }];
|
|
913
|
+
changed = true;
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
// Spill: bound an oversized result and name the file holding it. Scope is
|
|
919
|
+
// RETURNED content — stock read/bash truncate inside the tool before this
|
|
920
|
+
// hook fires, so their dropped bytes are unrecoverable here and those
|
|
921
|
+
// results are excluded (see lib/spill.ts header).
|
|
922
|
+
if (live.spillMaxTokens > 0) {
|
|
923
|
+
const details = event.details as { fullOutputPath?: unknown; truncation?: { truncated?: unknown } } | undefined;
|
|
924
|
+
// Any tool that already spilled itself (bash, codemode, grep…) reports
|
|
925
|
+
// fullOutputPath in details. codemode is the one that surprised a live
|
|
926
|
+
// probe: it truncates at 10,000 tokens (execute.js:248) and sets this
|
|
927
|
+
// too, so it can never reach the seam oversized.
|
|
928
|
+
const selfTruncated = typeof details?.fullOutputPath === "string";
|
|
929
|
+
// Metadata, never notice text: a wrapped read of a file CONTAINING
|
|
930
|
+
// "Use offset=" must still spill (the wrapper strips details.truncation
|
|
931
|
+
// on its own views; the stock pass-through keeps it).
|
|
932
|
+
const selfTruncatedByRead = event.toolName === "read" && details?.truncation?.truncated === true;
|
|
933
|
+
const hasImages = content.some((b) => b.type === "image");
|
|
934
|
+
if (!selfTruncated && !selfTruncatedByRead && !hasImages) {
|
|
935
|
+
const textBlocks = content.filter((b): b is { type: "text"; text: string } => b.type === "text" && typeof b.text === "string");
|
|
936
|
+
if (textBlocks.length > 0 && estimateTokens(textBlocks) > live.spillMaxTokens) {
|
|
937
|
+
const full = textBlocks.map((b) => b.text).join("\n");
|
|
938
|
+
try {
|
|
939
|
+
const file = await saveSpill(event.toolName, event.toolCallId, full);
|
|
940
|
+
// Reserve the notice + gap BEFORE retaining so the patched result
|
|
941
|
+
// fits the caller's budget rather than overshooting it.
|
|
942
|
+
const longest = longestLineLength(full);
|
|
943
|
+
// Shortest line drives the LINE cap: short lines mean many lines
|
|
944
|
+
// per byte window, and pi's bash drops a page's HEAD past 2000
|
|
945
|
+
// lines while our offset has already advanced past it.
|
|
946
|
+
const shortest = shortestLineLength(full);
|
|
947
|
+
const worstNotice = formatSpillNotice(full.length, file, longest, live.spillMaxTokens, shortest);
|
|
948
|
+
const reserved = estimateTokens([{ type: "text", text: GAP_TEXT }, { type: "text", text: worstNotice }]);
|
|
949
|
+
const retained = retainContent(textBlocks.map((b) => b.text), Math.max(0, live.spillMaxTokens - reserved));
|
|
950
|
+
const notice = formatSpillNotice(retained.omittedBytes, file, longest, live.spillMaxTokens, shortest);
|
|
951
|
+
content =
|
|
952
|
+
retained.head.length + retained.tail.length === 0
|
|
953
|
+
? [{ type: "text", text: notice.trimStart() }]
|
|
954
|
+
: [...retained.head, { type: "text", text: GAP_TEXT }, ...retained.tail, { type: "text", text: notice }];
|
|
955
|
+
changed = true;
|
|
956
|
+
} catch {
|
|
957
|
+
/* fail-open: an unwritable store must never cost the model its result */
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
return changed ? { content } : undefined;
|
|
964
|
+
});
|
|
965
|
+
|
|
966
|
+
// ── before_agent_start: clock injection + repeat-chain reset ──
|
|
967
|
+
pi.on("before_agent_start", (event, ctx) => {
|
|
968
|
+
const key = sessionKey(ctx?.sessionManager?.getSessionId?.());
|
|
969
|
+
// A new user message means the previous context is gone: repetition across
|
|
970
|
+
// an interjection is not a loop (DSH's reset rule). Only real user runs
|
|
971
|
+
// reset — cron fires and follow-ups are not interjections.
|
|
972
|
+
if (event.messageType === "user") repeatChains.delete(key);
|
|
973
|
+
|
|
974
|
+
const live = readRepairSettings(ctx?.cwd);
|
|
975
|
+
const now = Date.now();
|
|
976
|
+
const state = clockStates.get(key);
|
|
977
|
+
const refreshMs = live.clockRefreshMs === undefined ? DEFAULT_CLOCK_REFRESH_MS : live.clockRefreshMs;
|
|
978
|
+
if (live.clock && shouldInject(state, now, refreshMs)) {
|
|
979
|
+
const elapsed = state?.lastActivity === undefined ? undefined : now - state.lastActivity;
|
|
980
|
+
clockStates.set(key, { lastInjection: now, lastActivity: now });
|
|
981
|
+
return {
|
|
982
|
+
message: {
|
|
983
|
+
customType: "ceulen-clock",
|
|
984
|
+
content: renderClock(now, elapsed),
|
|
985
|
+
display: false,
|
|
986
|
+
},
|
|
987
|
+
};
|
|
988
|
+
}
|
|
989
|
+
if (state) clockStates.set(key, { ...state, lastActivity: now });
|
|
990
|
+
return undefined;
|
|
991
|
+
});
|
|
992
|
+
|
|
870
993
|
// ── /repair (bare = status) ──
|
|
871
994
|
pi.registerCommand("repair", {
|
|
872
995
|
description: "Show tool-hardening status: repair counts, guards, bash auto-background, persistent shell.",
|
|
@@ -883,6 +1006,9 @@ export default function repairModule(pi: ExtensionAPI) {
|
|
|
883
1006
|
` Auto-generated write guard: ${live.autoGenGuard ? "on" : "off"}`,
|
|
884
1007
|
` Auto-background bash: ${live.autoBg ? `on @${live.autoBgSecs}s` : "off"}${live.autoBg !== autoBgOn || live.autoBgSecs !== autoBgSecs ? ` (bound at load: ${autoBgOn ? `on @${autoBgSecs}s` : "off"} — next session applies)` : ""}`,
|
|
885
1008
|
` Persistent bash: ${live.persistentBash ? "on" : "off"}${live.persistentBash !== persistentBashOn ? ` (bound at load: ${persistentBashOn ? "on" : "off"} — next session applies)` : ""}${persistentBashOn && (live.autoBg || autoBgOn) ? " · auto-background suspended while persistent is on" : ""}`,
|
|
1009
|
+
` Tool-result spill: ${live.spillMaxTokens > 0 ? `over ${live.spillMaxTokens} tok → saved to a file` : "off"}`,
|
|
1010
|
+
` Repeat-call reminder: ${live.repeatReminder ? "on (3rd/5th/8th identical call)" : "off"}`,
|
|
1011
|
+
` Model-visible clock: ${live.clock ? `on @${Math.round(live.clockRefreshMs / 1000)}s` : "off"}`,
|
|
886
1012
|
"",
|
|
887
1013
|
`**Repairs this session:** ${total} total`,
|
|
888
1014
|
];
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// Time context — the model-visible clock pi does not inject anywhere.
|
|
2
|
+
//
|
|
3
|
+
// Ported from DeepSeek Harness `packages/context/time-context` (renderText +
|
|
4
|
+
// the 10-minute durable refresh). pi's system prompt carries no date/time at
|
|
5
|
+
// all (dist/core/system-prompt.js renders with `timestamp: 0`), so a long
|
|
6
|
+
// session — goal mode, cron loops, multi-hour refactors — has no way to know
|
|
7
|
+
// when "today" is or how long it has been running.
|
|
8
|
+
//
|
|
9
|
+
// Deliberate reductions from DSH: no browser-timezone negotiation (that is a
|
|
10
|
+
// web-app concept; a TUI has one process zone), no session projection (pi
|
|
11
|
+
// rehydrates nothing here — the maps are per-process and per-session-id), and
|
|
12
|
+
// no turn/step numbering in the line (pi's turn index is not model-meaningful
|
|
13
|
+
// and would churn with every turn).
|
|
14
|
+
//
|
|
15
|
+
// Cache-safety: one injected message per refresh WINDOW (default 10 minutes),
|
|
16
|
+
// appended after the user message, so a long session adds a handful of small
|
|
17
|
+
// messages instead of one per turn. This is DSH's append-only policy verbatim.
|
|
18
|
+
|
|
19
|
+
/** Default minutes-scale refresh window (DSH refreshIntervalMs default). */
|
|
20
|
+
export const DEFAULT_CLOCK_REFRESH_MS = 600_000;
|
|
21
|
+
|
|
22
|
+
/** Compact whole-second duration: `2d 3h 5m 7s` (DSH formatDuration). */
|
|
23
|
+
export function formatDuration(elapsedMs: number): string {
|
|
24
|
+
// A backward wall-clock reading is a property of the clock, not the span.
|
|
25
|
+
const total = Math.max(0, Math.floor(elapsedMs / 1000));
|
|
26
|
+
const days = Math.floor(total / 86_400);
|
|
27
|
+
const hours = Math.floor((total % 86_400) / 3_600);
|
|
28
|
+
const minutes = Math.floor((total % 3_600) / 60);
|
|
29
|
+
const seconds = total % 60;
|
|
30
|
+
const parts: string[] = [];
|
|
31
|
+
if (days > 0) parts.push(`${days}d`);
|
|
32
|
+
if (hours > 0) parts.push(`${hours}h`);
|
|
33
|
+
if (minutes > 0) parts.push(`${minutes}m`);
|
|
34
|
+
parts.push(`${seconds}s`);
|
|
35
|
+
return parts.join(" ");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* ISO-8601 timestamp with a numeric UTC offset and the IANA zone name.
|
|
40
|
+
* The numeric offset is what a model does arithmetic with; the zone name is
|
|
41
|
+
* what makes a DST boundary legible — DSH keeps both for the same reason.
|
|
42
|
+
*/
|
|
43
|
+
export function formatTimestamp(now: number, timeZone?: string): string {
|
|
44
|
+
const date = new Date(now);
|
|
45
|
+
const zone = timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
46
|
+
const iso = isoWithOffset(date, zone);
|
|
47
|
+
return `${iso} (${zone})`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** `YYYY-MM-DDTHH:mm:ss±HH:MM` for an instant rendered in `timeZone`. */
|
|
51
|
+
function isoWithOffset(date: Date, timeZone: string): string {
|
|
52
|
+
let parts: Intl.DateTimeFormatPart[];
|
|
53
|
+
try {
|
|
54
|
+
parts = new Intl.DateTimeFormat("en-CA", {
|
|
55
|
+
timeZone,
|
|
56
|
+
year: "numeric",
|
|
57
|
+
month: "2-digit",
|
|
58
|
+
day: "2-digit",
|
|
59
|
+
hour: "2-digit",
|
|
60
|
+
minute: "2-digit",
|
|
61
|
+
second: "2-digit",
|
|
62
|
+
hour12: false,
|
|
63
|
+
}).formatToParts(date);
|
|
64
|
+
} catch {
|
|
65
|
+
// Unknown zone → fall back to the process zone rather than dropping the clock.
|
|
66
|
+
return isoWithOffset(date, Intl.DateTimeFormat().resolvedOptions().timeZone);
|
|
67
|
+
}
|
|
68
|
+
const get = (type: string): string => parts.find((p) => p.type === type)?.value ?? "00";
|
|
69
|
+
// Intl renders midnight as 24 in some ICU builds; normalise to 00.
|
|
70
|
+
const hour = get("hour") === "24" ? "00" : get("hour");
|
|
71
|
+
const stamp = `${get("year")}-${get("month")}-${get("day")}T${hour}:${get("minute")}:${get("second")}`;
|
|
72
|
+
return `${stamp}${offsetFor(date, timeZone)}`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Numeric UTC offset (`+07:00`) of `timeZone` at instant `date`. */
|
|
76
|
+
function offsetFor(date: Date, timeZone: string): string {
|
|
77
|
+
try {
|
|
78
|
+
const name = new Intl.DateTimeFormat("en-US", { timeZone, timeZoneName: "longOffset" })
|
|
79
|
+
.formatToParts(date)
|
|
80
|
+
.find((p) => p.type === "timeZoneName")?.value;
|
|
81
|
+
const match = name?.match(/GMT([+-]\d{2}:\d{2})?/);
|
|
82
|
+
if (match) return match[1] ?? "+00:00";
|
|
83
|
+
} catch { /* fall through to UTC */ }
|
|
84
|
+
return "+00:00";
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The two-line clock message body. */
|
|
88
|
+
export function renderClock(now: number, elapsedMs: number | undefined, timeZone?: string): string {
|
|
89
|
+
const elapsed = elapsedMs === undefined ? "unavailable" : formatDuration(elapsedMs);
|
|
90
|
+
return `Time: ${formatTimestamp(now, timeZone)}\nElapsed since last activity: ${elapsed}`;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Per-session clock bookkeeping. */
|
|
94
|
+
export interface ClockState {
|
|
95
|
+
lastInjection: number;
|
|
96
|
+
lastActivity?: number;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Whether this session is due for an injection given its refresh window. */
|
|
100
|
+
export function shouldInject(state: ClockState | undefined, now: number, refreshMs: number): boolean {
|
|
101
|
+
if (refreshMs <= 0) return true;
|
|
102
|
+
if (state === undefined) return true;
|
|
103
|
+
const since = now - state.lastInjection;
|
|
104
|
+
// A backward clock reading must not park the clock forever.
|
|
105
|
+
return since < 0 || since >= refreshMs;
|
|
106
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Repeat-tool-reminder — advisory loop guard for EXACT repeated tool calls.
|
|
2
|
+
//
|
|
3
|
+
// Ported from DeepSeek Harness `packages/guard/repeat-tool-reminder`. The pi
|
|
4
|
+
// seam differs from DSH's (`tools/post-execute` can attach additionalContexts
|
|
5
|
+
// there; pi's `tool_result` result can only patch content), so the advisory
|
|
6
|
+
// channel is a FOOTER appended to the result text: the call still executes and
|
|
7
|
+
// its real output survives — unlike ceulen's two blocking guards (permission's
|
|
8
|
+
// doom-loop on denied calls, munin's dampener on munin tools), which refuse.
|
|
9
|
+
//
|
|
10
|
+
// Counting is on post-execution for that reason: a model hammering a call that
|
|
11
|
+
// SUCCEEDS is the DeepSeek Flash loop failure mode, and a refusal would erase
|
|
12
|
+
// the evidence the model needs to change approach.
|
|
13
|
+
|
|
14
|
+
/** Consecutive-repeat counts that trigger a reminder (DSH default). */
|
|
15
|
+
export const REPEAT_THRESHOLDS = [3, 5, 8] as const;
|
|
16
|
+
/** Canonical arguments quoted in the detailed reminder (DSH cap). */
|
|
17
|
+
export const ARGUMENTS_PREVIEW_CHARS = 500;
|
|
18
|
+
/** The munin module's own dampener owns its tools — never double-advise. */
|
|
19
|
+
const MUNIN_PREFIX = "munin_";
|
|
20
|
+
|
|
21
|
+
/** Deep key-sort so two argument objects differing only in property order
|
|
22
|
+
* canonicalize identically (DSH sortJsonValue; arguments arrive as the loop's
|
|
23
|
+
* JSON.parse output, so JSON's value domain is the whole input domain). */
|
|
24
|
+
export function sortJsonValue(value: unknown): unknown {
|
|
25
|
+
if (Array.isArray(value)) return value.map(sortJsonValue);
|
|
26
|
+
if (value !== null && typeof value === "object") {
|
|
27
|
+
const record = value as Record<string, unknown>;
|
|
28
|
+
const sorted: Record<string, unknown> = {};
|
|
29
|
+
for (const key of Object.keys(record).sort()) sorted[key] = sortJsonValue(record[key]);
|
|
30
|
+
return sorted;
|
|
31
|
+
}
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Canonical string form of a call's arguments: deep key-sort, then stringify. */
|
|
36
|
+
export function canonicalizeArguments(args: unknown): string {
|
|
37
|
+
return JSON.stringify(sortJsonValue(args));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Identity key of one call: tool name + canonical arguments. */
|
|
41
|
+
export function callKey(toolName: string, args: unknown): string {
|
|
42
|
+
return JSON.stringify([toolName, canonicalizeArguments(args)]);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Whether a tool participates in the chain (munin tools are excluded). */
|
|
46
|
+
export function isTrackedTool(toolName: string): boolean {
|
|
47
|
+
return !toolName.startsWith(MUNIN_PREFIX);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const GENTLE_REMINDER =
|
|
51
|
+
"Same tool call repeated with identical arguments — analyze the previous result "
|
|
52
|
+
+ "before calling again: if the task is not complete, try a different approach or "
|
|
53
|
+
+ "different arguments instead of repeating the call.";
|
|
54
|
+
|
|
55
|
+
function previewArguments(canonical: string): string {
|
|
56
|
+
if (canonical.length <= ARGUMENTS_PREVIEW_CHARS) return canonical;
|
|
57
|
+
return `${canonical.slice(0, ARGUMENTS_PREVIEW_CHARS)}… (+${canonical.length - ARGUMENTS_PREVIEW_CHARS} more chars)`;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The reminder text for a chain that just hit `count`, or undefined. */
|
|
61
|
+
export function reminderFor(toolName: string, count: number, canonical: string): string | undefined {
|
|
62
|
+
if (!(REPEAT_THRESHOLDS as readonly number[]).includes(count)) return undefined;
|
|
63
|
+
const body = count === REPEAT_THRESHOLDS[0]
|
|
64
|
+
? GENTLE_REMINDER
|
|
65
|
+
: `Repeated tool call detected:\n- tool: ${toolName}\n- consecutive_calls: ${count}\n- arguments: ${previewArguments(canonical)}\nThe repeated calls are not making progress. Do not call this tool with these exact arguments again — inspect the latest result and choose a different action, different arguments, or finish the task.`;
|
|
66
|
+
return `\n\n[ceulen] ${body}`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** One session's consecutive-repeat chain. */
|
|
70
|
+
export interface RepeatChain {
|
|
71
|
+
key: string;
|
|
72
|
+
count: number;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Advance a chain for one call and return the footer to append, if any.
|
|
77
|
+
* Untracked tools are TRANSPARENT (neither count nor reset), matching DSH.
|
|
78
|
+
*/
|
|
79
|
+
export function advanceChain(
|
|
80
|
+
chain: RepeatChain | undefined,
|
|
81
|
+
toolName: string,
|
|
82
|
+
args: unknown,
|
|
83
|
+
): { chain: RepeatChain; footer?: string } | undefined {
|
|
84
|
+
if (!isTrackedTool(toolName)) return undefined;
|
|
85
|
+
const key = callKey(toolName, args);
|
|
86
|
+
const count = chain !== undefined && chain.key === key ? chain.count + 1 : 1;
|
|
87
|
+
const next: RepeatChain = { key, count };
|
|
88
|
+
const footer = reminderFor(toolName, count, canonicalizeArguments(args));
|
|
89
|
+
return footer === undefined ? { chain: next } : { chain: next, footer };
|
|
90
|
+
}
|
|
@@ -34,6 +34,14 @@ export interface RepairSettings {
|
|
|
34
34
|
/** One persistent bash shell per session (cwd/env/jobs survive across calls).
|
|
35
35
|
* Binds at load — the shell description sits in the cache-safe request head. */
|
|
36
36
|
persistentBash: boolean;
|
|
37
|
+
/** Token budget for one tool result; excess is spilled to a retrievable file. 0 = off. */
|
|
38
|
+
spillMaxTokens: number;
|
|
39
|
+
/** Advisory footer when the same tool call repeats with identical arguments. */
|
|
40
|
+
repeatReminder: boolean;
|
|
41
|
+
/** Inject a model-visible clock (pi injects no date/time anywhere). */
|
|
42
|
+
clock: boolean;
|
|
43
|
+
/** Minimum milliseconds between clock injections in one session. */
|
|
44
|
+
clockRefreshMs: number;
|
|
37
45
|
}
|
|
38
46
|
|
|
39
47
|
export const DEFAULT_REPAIR_SETTINGS: RepairSettings = {
|
|
@@ -44,6 +52,11 @@ export const DEFAULT_REPAIR_SETTINGS: RepairSettings = {
|
|
|
44
52
|
autoBg: false,
|
|
45
53
|
autoBgSecs: 120,
|
|
46
54
|
persistentBash: false,
|
|
55
|
+
// DSH base-preset value (packages/bundle/base/cordis.patch.yml maxInlineTokens).
|
|
56
|
+
spillMaxTokens: 12_500,
|
|
57
|
+
repeatReminder: true,
|
|
58
|
+
clock: false,
|
|
59
|
+
clockRefreshMs: 600_000,
|
|
47
60
|
};
|
|
48
61
|
|
|
49
62
|
function agentDir(): string {
|
|
@@ -67,7 +80,7 @@ function section(json: Record<string, unknown> | null, key: string): Record<stri
|
|
|
67
80
|
/** Merge one settings layer's `repair` keys over out (field-wise override). */
|
|
68
81
|
function mergeLayer(out: RepairSettings, json: Record<string, unknown> | null): void {
|
|
69
82
|
const s = section(json, "repair");
|
|
70
|
-
for (const key of ["arguments", "editRetry", "guards", "autoGenGuard", "autoBg", "persistentBash"] as const) {
|
|
83
|
+
for (const key of ["arguments", "editRetry", "guards", "autoGenGuard", "autoBg", "persistentBash", "repeatReminder", "clock"] as const) {
|
|
71
84
|
if (typeof s[key] === "boolean") out[key] = s[key];
|
|
72
85
|
}
|
|
73
86
|
if (typeof s.autoBgSecs === "number" && Number.isFinite(s.autoBgSecs)) {
|
|
@@ -75,6 +88,14 @@ function mergeLayer(out: RepairSettings, json: Record<string, unknown> | null):
|
|
|
75
88
|
// everything (upstream's env reader clamped for the same reason).
|
|
76
89
|
out.autoBgSecs = Math.max(1, Math.floor(s.autoBgSecs));
|
|
77
90
|
}
|
|
91
|
+
if (typeof s.spillMaxTokens === "number" && Number.isFinite(s.spillMaxTokens)) {
|
|
92
|
+
// Clamp at 0 (= disabled). A negative budget would otherwise mean "spill
|
|
93
|
+
// everything to nothing", the opposite of what a typo intended.
|
|
94
|
+
out.spillMaxTokens = Math.max(0, Math.floor(s.spillMaxTokens));
|
|
95
|
+
}
|
|
96
|
+
if (typeof s.clockRefreshMs === "number" && Number.isFinite(s.clockRefreshMs)) {
|
|
97
|
+
out.clockRefreshMs = Math.max(0, Math.floor(s.clockRefreshMs));
|
|
98
|
+
}
|
|
78
99
|
}
|
|
79
100
|
|
|
80
101
|
/** The agent-dir settings.json (the file /config saves into). */
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// Spill store — where an oversized tool result's full text is written.
|
|
2
|
+
//
|
|
3
|
+
// Adapted from DeepSeek Harness `packages/spill/spill-local/src/store.ts`.
|
|
4
|
+
// One private temp root per process (DSH's `privateRoot`), one file per spill.
|
|
5
|
+
// `encodeSegment` is DSH's injective escaping: tool names and call ids are not
|
|
6
|
+
// trusted (`../../etc/passwd`, NUL, separators), so each is encoded to a single
|
|
7
|
+
// safe path segment rather than sanitised by deletion (which could collide).
|
|
8
|
+
|
|
9
|
+
import { mkdtempSync } from "node:fs";
|
|
10
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
11
|
+
import { tmpdir } from "node:os";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
|
|
14
|
+
/** Prefix of the private per-process root. */
|
|
15
|
+
export const DEFAULT_ROOT_PREFIX = "ceulen-spill-";
|
|
16
|
+
|
|
17
|
+
let defaultRoot: string | undefined;
|
|
18
|
+
/** Monotonic counter making every spill file unique (see saveSpill). */
|
|
19
|
+
let spillSeq = 0;
|
|
20
|
+
|
|
21
|
+
/** The lazily-created private per-process spill root. */
|
|
22
|
+
export function privateRoot(): string {
|
|
23
|
+
defaultRoot ??= mkdtempSync(join(tmpdir(), DEFAULT_ROOT_PREFIX));
|
|
24
|
+
return defaultRoot;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Test seam: override the root (a path that cannot be created exercises the
|
|
28
|
+
* fail-open path). Passing undefined returns to the lazy temp root. */
|
|
29
|
+
export function setSpillRootForTests(root: string | undefined): void {
|
|
30
|
+
defaultRoot = root;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const SAFE = /[A-Za-z0-9._-]/;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Encode arbitrary text as ONE filesystem-safe path segment, injectively.
|
|
37
|
+
* Each code unit is kept literal when safe (except `~`) or escaped as `~XXXX`;
|
|
38
|
+
* `~` is itself escaped, so distinct inputs never collide. The whole-segment
|
|
39
|
+
* tokens `.` and `..` are escaped so they can never traverse.
|
|
40
|
+
*/
|
|
41
|
+
export function encodeSegment(raw: string): string {
|
|
42
|
+
if (raw.length === 0) return "~";
|
|
43
|
+
if (raw === ".") return "~002E";
|
|
44
|
+
if (raw === "..") return "~002E~002E";
|
|
45
|
+
let out = "";
|
|
46
|
+
for (const unit of raw) {
|
|
47
|
+
const code = unit.codePointAt(0) ?? 0;
|
|
48
|
+
if (code > 0xffff) {
|
|
49
|
+
// Non-BMP: encode both surrogate halves so the mapping stays injective.
|
|
50
|
+
for (let i = 0; i < unit.length; i++) out += `~${unit.charCodeAt(i).toString(16).toUpperCase().padStart(4, "0")}`;
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
out += unit !== "~" && SAFE.test(unit) ? unit : `~${code.toString(16).toUpperCase().padStart(4, "0")}`;
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Write the full text of one tool result and return its absolute path.
|
|
60
|
+
* Creates the root on first use (a missing parent would otherwise make the
|
|
61
|
+
* write fail and spill would skip silently every time).
|
|
62
|
+
*/
|
|
63
|
+
export async function saveSpill(toolName: string, callId: string, text: string): Promise<string> {
|
|
64
|
+
const root = privateRoot();
|
|
65
|
+
await mkdir(root, { recursive: true });
|
|
66
|
+
// Monotonic suffix: a retried call reusing a toolCallId must never overwrite
|
|
67
|
+
// a spill an older transcript entry still points at — each spill is
|
|
68
|
+
// immutable once the model has been told its path.
|
|
69
|
+
const file = join(root, `${encodeSegment(toolName)}-${encodeSegment(callId)}-${++spillSeq}.txt`);
|
|
70
|
+
await writeFile(file, text, { encoding: "utf8", mode: 0o600 });
|
|
71
|
+
return file;
|
|
72
|
+
}
|