minicode-ai 0.14.2 → 0.14.4
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/README.md +34 -178
- package/cli/args.ts +10 -18
- package/cli/commands/acp.ts +20 -27
- package/cli/commands/daemon.ts +6 -7
- package/cli/commands/exec.ts +12 -10
- package/cli/commands.ts +6 -9
- package/cli/index.ts +30 -15
- package/cli/provider-manager.ts +1 -3
- package/cli/setup.ts +167 -143
- package/cli/tui.ts +15 -23
- package/docs/CONTROL-PLANE-MAP.md +145 -0
- package/docs/OUTPUT_EVENT_MODEL.md +1 -1
- package/docs/OUTPUT_PROTOCOL_SPEC.md +2 -2
- package/docs/OUTPUT_RENDERING_SPEC.md +7 -2
- package/docs/OUTPUT_UX_RULES.md +1 -1
- package/docs/README.md +14 -102
- package/docs/SUMMARY.md +53 -0
- package/docs/TERMINAL_CONTRACT.md +84 -51
- package/docs/UI_RENDER_PIPELINE.md +204 -0
- package/docs/agents.md +5 -5
- package/docs/architecture.md +23 -12
- package/docs/choosing-mode.md +7 -7
- package/docs/cli.md +22 -29
- package/docs/concepts.md +1 -1
- package/docs/config.md +10 -5
- package/docs/contributing.md +6 -6
- package/docs/environment.md +3 -1
- package/docs/exec.md +5 -5
- package/docs/glossary.md +8 -6
- package/docs/memory-sessions.md +7 -5
- package/docs/policy-sandbox.md +16 -14
- package/docs/quickstart.md +2 -2
- package/docs/repl.md +4 -3
- package/docs/security-model.md +14 -15
- package/docs/security.md +8 -29
- package/docs/skills.md +1 -1
- package/docs/tools.md +2 -2
- package/package.json +5 -3
- package/scripts/vendor-overlays/minicode-context.patch +109 -0
- package/src/app/provider-layer.ts +13 -1
- package/src/app/session.ts +216 -13
- package/src/config.ts +30 -3
- package/src/constants.ts +2 -0
- package/src/daemon/control.ts +1 -1
- package/src/mcp/server.ts +2 -3
- package/src/policy/compaction.ts +272 -16
- package/src/policy/context-window.ts +73 -0
- package/src/policy/context.ts +55 -3
- package/src/policy/ratelimit.ts +47 -18
- package/src/policy/usage.ts +15 -8
- package/src/policy/work-mode.ts +1 -1
- package/src/providers/guards.ts +61 -4
- package/src/providers/provision.ts +12 -3
- package/src/providers/router.ts +56 -23
- package/src/session/context-projection.ts +14 -0
- package/src/session/context-selector.ts +58 -20
- package/src/session/persistence.ts +1 -1
- package/src/task/model.ts +21 -70
- package/src/tools/task.ts +7 -0
- package/src/ui/footer.ts +131 -66
- package/src/ui/i18n/en.ts +0 -11
- package/src/ui/i18n/id.ts +0 -11
- package/src/ui/input/input.ts +2 -3
- package/src/ui/input/prompt-engine.ts +2 -5
- package/src/ui/screens/model-manager.ts +3 -10
- package/src/ui/screens/picker.ts +23 -40
- package/src/ui/screens/provider-manager.ts +12 -33
- package/src/ui/screens/wizard.ts +0 -1
- package/src/ui/tui/app.ts +10 -6
- package/src/ui/tui/transcript.ts +48 -8
- package/vendor/minicore/VENDOR.md +9 -5
- package/vendor/minicore/src/core/loop.ts +47 -12
- package/vendor/minicore/src/core/provider.ts +4 -0
- package/vendor/minicore/src/core/session.ts +14 -1
- package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +0 -489
- package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +0 -391
|
@@ -11,7 +11,7 @@ import {
|
|
|
11
11
|
} from "../input/prompt-engine.ts"
|
|
12
12
|
import { sanitizeAnsiLine } from "../render/sanitize.ts"
|
|
13
13
|
import { c, glyphs, stripAnsi } from "../render/theme.ts"
|
|
14
|
-
import {
|
|
14
|
+
import { truncateToWidth } from "../render/width.ts"
|
|
15
15
|
import { type AltScreen, openAltScreen } from "../runtime/screen.ts"
|
|
16
16
|
import { boxLeftPad, dialogBox } from "./dialog.ts"
|
|
17
17
|
import { runForm, validateRequired, validateUrl } from "./form.ts"
|
|
@@ -19,8 +19,8 @@ import { runPicker } from "./picker.ts"
|
|
|
19
19
|
|
|
20
20
|
const dim = (s: string): string => c.dim(s)
|
|
21
21
|
|
|
22
|
-
/** Lebar
|
|
23
|
-
const PROVIDER_BOX_W =
|
|
22
|
+
/** Lebar tetap popup provider setelah daftar diringkas ke nama provider. */
|
|
23
|
+
const PROVIDER_BOX_W = 52
|
|
24
24
|
|
|
25
25
|
export interface ProviderRow {
|
|
26
26
|
id: string
|
|
@@ -86,19 +86,18 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
|
|
|
86
86
|
}
|
|
87
87
|
|
|
88
88
|
return new Promise<void>((resolve) => {
|
|
89
|
-
// Ukuran mengikuti terminal
|
|
90
|
-
//
|
|
91
|
-
// item dibatasi rows−5 (lihat picker.ts).
|
|
89
|
+
// Ukuran mengikuti terminal sungguhan; satu baris border atas/bawah dan
|
|
90
|
+
// kemungkinan notice tetap masuk ke perhitungan tinggi.
|
|
92
91
|
const visibleRows = () => {
|
|
93
92
|
const rows = process.stdout.rows || 24
|
|
94
|
-
return Math.max(1, Math.min(rows -
|
|
93
|
+
return Math.max(1, Math.min(rows - 3, 14))
|
|
95
94
|
}
|
|
96
95
|
// Lebar konten = lebar kotak TETAP (min=max, paritas picker/model) —
|
|
97
96
|
// dikurangi chrome dialog (lihat picker.ts).
|
|
98
97
|
const width = () =>
|
|
99
98
|
Math.max(8, Math.min((process.stdout.columns || 80) - 2 - 4, PROVIDER_BOX_W - 4))
|
|
100
99
|
|
|
101
|
-
// Isi popup
|
|
100
|
+
// Isi popup ringkas: nama provider dan hasil aksi sementara.
|
|
102
101
|
const bodyLines = (): string[] => {
|
|
103
102
|
const v = visibleRows()
|
|
104
103
|
if (sel < scroll) scroll = sel
|
|
@@ -113,47 +112,28 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
|
|
|
113
112
|
for (let i = 0; i < rows.length; i++) {
|
|
114
113
|
const it = rows[i]!
|
|
115
114
|
const picked = i === sel - scroll
|
|
116
|
-
//
|
|
117
|
-
//
|
|
118
|
-
// disanitasi seperti label picker.
|
|
115
|
+
// Nama provider dan status aktif cukup untuk memilih tanpa memenuhi
|
|
116
|
+
// daftar dengan URL dan jumlah model.
|
|
119
117
|
const aktif = opts.currentModel?.startsWith(`${it.id}::`)
|
|
120
118
|
? ` (${t("common.active")})`
|
|
121
119
|
: ""
|
|
122
|
-
|
|
123
|
-
// sisa SETELAH head+aktif (dulu truncate menelan "(aktif)" dulu
|
|
124
|
-
// saat URL panjang — user tak tahu mana yang aktif).
|
|
125
|
-
const head = `${padToWidth(sanitizeAnsiLine(it.id), 18)} ${t("prov.models", { n: it.models })} `
|
|
126
|
-
const urlBudget = Math.max(8, w - 4 - displayWidth(head) - displayWidth(aktif))
|
|
127
|
-
const label = `${head}${truncateToWidth(sanitizeAnsiLine(it.baseUrl), urlBudget, "…")}${aktif}`
|
|
120
|
+
const label = `${truncateToWidth(sanitizeAnsiLine(it.id), Math.max(8, w - 4 - aktif.length), "…")}${aktif}`
|
|
128
121
|
if (picked) lines.push(` ${c.accent("›")} ${c.accent(c.bold(label))}`)
|
|
129
122
|
else lines.push(` ${dim(label)}`)
|
|
130
123
|
}
|
|
131
|
-
if (providers.length > scroll + v) {
|
|
132
|
-
lines.push(cut(dim(t("dlg.more", { n: providers.length - scroll - v }))))
|
|
133
|
-
}
|
|
134
124
|
}
|
|
135
125
|
// Struk transient (jalur legacy maupun modal).
|
|
136
126
|
if (notice) lines.push(cut(dim(sanitizeAnsiLine(notice))))
|
|
137
127
|
return lines
|
|
138
128
|
}
|
|
139
129
|
|
|
140
|
-
const hintText = (): string =>
|
|
141
|
-
t("prov.hint", {
|
|
142
|
-
select: c.accent(t("verb.select")),
|
|
143
|
-
add: c.accent(t("verb.add")),
|
|
144
|
-
delete: c.accent(t("verb.delete")),
|
|
145
|
-
edit: c.accent(t("verb.edit")),
|
|
146
|
-
close: c.accent(t("verb.close")),
|
|
147
|
-
})
|
|
148
|
-
|
|
149
130
|
const render = () => {
|
|
150
131
|
// Popup komposit: HANYA region kotak (tanpa clear) di atas konten
|
|
151
|
-
// pemilik layar. Lebar
|
|
132
|
+
// pemilik layar. Lebar tetap 52 agar daftar tidak kosong terlalu lebar.
|
|
152
133
|
const box = dialogBox(
|
|
153
134
|
{
|
|
154
|
-
title:
|
|
135
|
+
title: "",
|
|
155
136
|
body: bodyLines(),
|
|
156
|
-
footer: hintText(),
|
|
157
137
|
minWidth: PROVIDER_BOX_W,
|
|
158
138
|
maxWidth: PROVIDER_BOX_W,
|
|
159
139
|
},
|
|
@@ -350,7 +330,6 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
|
|
|
350
330
|
{ name: t("prov.customUrl"), provider: "", value: CUSTOM },
|
|
351
331
|
],
|
|
352
332
|
filterable: true,
|
|
353
|
-
placeholder: t("pick.placeholder"),
|
|
354
333
|
onPick: (v) => resolvePick(v),
|
|
355
334
|
onCancel: () => resolvePick(null),
|
|
356
335
|
}).catch(() => resolvePick(null))
|
package/src/ui/screens/wizard.ts
CHANGED
package/src/ui/tui/app.ts
CHANGED
|
@@ -219,6 +219,7 @@ export class TuiApp {
|
|
|
219
219
|
private onSignalTerm: (() => void) | null = null
|
|
220
220
|
private onSignalHup: (() => void) | null = null
|
|
221
221
|
private onSignalInt: (() => void) | null = null
|
|
222
|
+
private signalExitHandled = false
|
|
222
223
|
|
|
223
224
|
private wasRaw = false
|
|
224
225
|
/**
|
|
@@ -328,6 +329,8 @@ export class TuiApp {
|
|
|
328
329
|
// loop, jadi tak ada jendela nyata; sisipkan await di antara keduanya =
|
|
329
330
|
// membuka race SIGTERM sebelum handler terpasang.
|
|
330
331
|
const restoreAndExit = (code: number) => {
|
|
332
|
+
if (this.signalExitHandled) return
|
|
333
|
+
this.signalExitHandled = true
|
|
331
334
|
// Selesaikan loop lebih dulu: cleanup melepas referensi resolver.
|
|
332
335
|
// Ini juga penting saat process.exit di-stub oleh test atau host.
|
|
333
336
|
this.quitRequested = true
|
|
@@ -737,7 +740,10 @@ export class TuiApp {
|
|
|
737
740
|
return
|
|
738
741
|
}
|
|
739
742
|
this.rememberHistory(line)
|
|
740
|
-
|
|
743
|
+
// Built-in commands and shortcuts belong to the composer history, not the
|
|
744
|
+
// conversation transcript. The command result remains independently
|
|
745
|
+
// visible when it carries useful user-facing information.
|
|
746
|
+
if (!line.startsWith("/")) this.transcript.pushUser(rawLine)
|
|
741
747
|
this.busy = true
|
|
742
748
|
this.thinkingActive = false
|
|
743
749
|
this.turnStartedAt = Date.now()
|
|
@@ -1143,14 +1149,12 @@ export class TuiApp {
|
|
|
1143
1149
|
const room = Math.max(0, rows - 2 - this.composerHeight(cols, busy) - 3)
|
|
1144
1150
|
const shown = hints.slice(0, Math.min(MAX_DROPDOWN_ROWS, room))
|
|
1145
1151
|
const w = Math.max(10, cols)
|
|
1146
|
-
const out: string[] = [
|
|
1152
|
+
const out: string[] = []
|
|
1147
1153
|
shown.forEach((h, i) => {
|
|
1148
1154
|
const picked = i === this.state.sel
|
|
1149
|
-
const text = sanitizeAnsiLine(h)
|
|
1150
|
-
out.push(picked ? c.accent(
|
|
1155
|
+
const text = sanitizeAnsiLine(h).replace(/^\/+/, "")
|
|
1156
|
+
out.push(picked ? c.accent(c.bold(text)) : text)
|
|
1151
1157
|
})
|
|
1152
|
-
if (hints.length > shown.length)
|
|
1153
|
-
out.push(c.muted(t("app.moreLines", { n: hints.length - shown.length })))
|
|
1154
1158
|
return out.map((l) => chunkByWidth(l, w)[0] ?? "")
|
|
1155
1159
|
}
|
|
1156
1160
|
|
package/src/ui/tui/transcript.ts
CHANGED
|
@@ -132,6 +132,39 @@ function renderAssistantLine(line: string, fenceState: FenceState): string | nul
|
|
|
132
132
|
return renderInline(line)
|
|
133
133
|
}
|
|
134
134
|
|
|
135
|
+
/**
|
|
136
|
+
* Rapikan hanya whitespace presentasi jawaban model: hapus baris kosong di
|
|
137
|
+
* tepi dan batasi jeda berulang di luar fenced code. Isi code fence tetap
|
|
138
|
+
* literal karena spasi dan baris kosong di dalamnya adalah bagian contoh.
|
|
139
|
+
*/
|
|
140
|
+
function normalizeAssistantOutput(text: string): string {
|
|
141
|
+
const lines = text.replace(/\r\n?/g, "\n").split("\n")
|
|
142
|
+
const out: string[] = []
|
|
143
|
+
let openFence: { char: string; len: number } | null = null
|
|
144
|
+
for (const line of lines) {
|
|
145
|
+
const fence = parseFence(line)
|
|
146
|
+
if (openFence) {
|
|
147
|
+
out.push(line)
|
|
148
|
+
if (fence && fence.char === openFence.char && fence.len >= openFence.len) openFence = null
|
|
149
|
+
continue
|
|
150
|
+
}
|
|
151
|
+
if (fence) {
|
|
152
|
+
openFence = fence
|
|
153
|
+
out.push(line)
|
|
154
|
+
continue
|
|
155
|
+
}
|
|
156
|
+
if (!line.trim()) {
|
|
157
|
+
if (out.length && out[out.length - 1] !== "") out.push("")
|
|
158
|
+
continue
|
|
159
|
+
}
|
|
160
|
+
out.push(line)
|
|
161
|
+
}
|
|
162
|
+
// Jika fence belum ditutup, baris kosong di ekor masih bagian dari contoh
|
|
163
|
+
// kode dan harus tetap literal. Hanya whitespace di luar fence yang dirapatkan.
|
|
164
|
+
if (!openFence) while (out.length && out[out.length - 1] === "") out.pop()
|
|
165
|
+
return out.join("\n")
|
|
166
|
+
}
|
|
167
|
+
|
|
135
168
|
let selectionSegmenter: Intl.Segmenter | undefined
|
|
136
169
|
|
|
137
170
|
function offsetAtColumn(text: string, start: number, end: number, column: number): number {
|
|
@@ -556,13 +589,18 @@ export class Transcript {
|
|
|
556
589
|
}
|
|
557
590
|
if (this.pending) {
|
|
558
591
|
const pendingFence = this.fenceTracker()
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
592
|
+
const pending = normalizeAssistantOutput(sanitizeAnsi(this.pending))
|
|
593
|
+
if (pending) {
|
|
594
|
+
for (const block of parseMarkdownBlocks(pending)) {
|
|
595
|
+
if (block.type === "table") rows.push(...this.projectTable(block.table, -1, w))
|
|
596
|
+
else
|
|
597
|
+
for (const line of block.text.split("\n")) {
|
|
598
|
+
const clean = stripSgr(sanitizeAnsi(line))
|
|
599
|
+
rows.push(
|
|
600
|
+
...this.projectText(line, clean, -1, w, false, "", true, pendingFence(line)),
|
|
601
|
+
)
|
|
602
|
+
}
|
|
603
|
+
}
|
|
566
604
|
}
|
|
567
605
|
}
|
|
568
606
|
if (this.pendingTruncated) {
|
|
@@ -707,11 +745,13 @@ export class Transcript {
|
|
|
707
745
|
|
|
708
746
|
private commit(): void {
|
|
709
747
|
if (!this.pending) return
|
|
710
|
-
const
|
|
748
|
+
const rawText = this.pendingTruncated
|
|
711
749
|
? `${this.pending}\n${TRANSCRIPT_TRUNCATION_MARKER}`
|
|
712
750
|
: this.pending
|
|
713
751
|
this.pending = ""
|
|
714
752
|
this.pendingTruncated = false
|
|
753
|
+
const text = normalizeAssistantOutput(rawText)
|
|
754
|
+
if (!text) return
|
|
715
755
|
for (const block of parseMarkdownBlocks(sanitizeAnsi(text))) {
|
|
716
756
|
if (block.type === "table") this.appendTable(block.table, { kind: "assistant" })
|
|
717
757
|
else {
|
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
# vendor/minicore — JANGAN EDIT MANUAL
|
|
2
2
|
|
|
3
|
-
Salinan
|
|
4
|
-
|
|
3
|
+
Salinan MiniCore dari source commit yang dipin, ditambah overlay host yang
|
|
4
|
+
diperiksa dari patch di `scripts/vendor-overlays/minicode-context.patch`.
|
|
5
|
+
Overlay memberi admission context per model dan system prompt dinamis;
|
|
6
|
+
simpan seam ini saat menyinkronkan source upstream.
|
|
5
7
|
|
|
6
8
|
- source commit: `0d33571047c0ed3778986108fd42e4bde6828bb0`
|
|
9
|
+
- source hash: `c8d214bb8d5eea86`
|
|
10
|
+
- overlay sha256: `7545ff914e4f83745634ee106c9a2e774dfea3bf4541e58ea98eba216902d432`
|
|
7
11
|
- files: 20
|
|
8
|
-
- hash: `
|
|
9
|
-
- shipped hash: `
|
|
12
|
+
- hash: `b5e27f72d08afb98`
|
|
13
|
+
- shipped hash: `4998979304b3c6e2` (18 file) — fingerprint file vendor yang ikut paket npm
|
|
10
14
|
(hash di atas mencakup test/fakes.ts yang sengaja tidak ikut paket;
|
|
11
15
|
verifikasi dari paket terbit: hitung hash vendor/minicore di dalam tarball)
|
|
12
16
|
|
|
13
17
|
Perbarui dengan `bun run vendor:minicore` (butuh `../minicore`).
|
|
14
|
-
|
|
18
|
+
`bun run vendor:check` memverifikasi source, overlay, dan fingerprint final.
|
|
@@ -45,11 +45,27 @@ export async function executeTurn(
|
|
|
45
45
|
// compaction burned the one recovery retry (though recovery was never
|
|
46
46
|
// tried), and vice versa. The recovery flag is ALWAYS set (a guard
|
|
47
47
|
// against an infinite loop: force_compact_and_retry is exempt from
|
|
48
|
-
// maxProviderRetries);
|
|
49
|
-
//
|
|
50
|
-
|
|
48
|
+
// maxProviderRetries); policy compaction has a small per-turn hard cap,
|
|
49
|
+
// guarding against repeated no-progress work after tool output grows.
|
|
50
|
+
// Permit one follow-up policy compaction after tool results grow the current
|
|
51
|
+
// turn. The hard cap prevents a no-progress compactor from looping forever.
|
|
52
|
+
let budgetCompactions = 0;
|
|
53
|
+
const maxBudgetCompactions = 2;
|
|
51
54
|
let compactedForRecovery = false;
|
|
52
55
|
|
|
56
|
+
// Resolve once for the turn: model switching is a between-turn operation,
|
|
57
|
+
// so budget admission and output accounting must use the same model window.
|
|
58
|
+
let contextWindowTokens = s.contextWindowTokens;
|
|
59
|
+
try {
|
|
60
|
+
const resolved = s.contextWindowTokensForModel?.(s.state.model);
|
|
61
|
+
if (typeof resolved === "number" && Number.isSafeInteger(resolved) && resolved > 0) {
|
|
62
|
+
contextWindowTokens = resolved;
|
|
63
|
+
}
|
|
64
|
+
} catch {
|
|
65
|
+
// Keep the validated numeric fallback; a metadata lookup must not bypass
|
|
66
|
+
// the kernel's context guard.
|
|
67
|
+
}
|
|
68
|
+
|
|
53
69
|
while (true) {
|
|
54
70
|
if (signal.aborted) throw abortError(signal);
|
|
55
71
|
if (stepIndex >= s.maxSteps) throw new AgentError("max_steps_exceeded", `exceeded ${s.maxSteps} steps`);
|
|
@@ -59,28 +75,36 @@ export async function executeTurn(
|
|
|
59
75
|
// prompt and tool schemas, which are sent on every request.
|
|
60
76
|
let pressure = s.budget.evaluate({
|
|
61
77
|
usedTokens: contextTokens(s),
|
|
62
|
-
limitTokens:
|
|
78
|
+
limitTokens: contextWindowTokens,
|
|
63
79
|
});
|
|
64
|
-
|
|
80
|
+
let reduced = false;
|
|
81
|
+
if (s.budget.shouldCompact(pressure) && budgetCompactions < maxBudgetCompactions) {
|
|
65
82
|
const before = s.store.messages.length;
|
|
66
83
|
await compactStore(s, signal);
|
|
67
|
-
|
|
84
|
+
budgetCompactions++;
|
|
68
85
|
// The reason distinguishes the trigger and whether compaction
|
|
69
86
|
// actually shrank the store (no-op = nothing evictable in messages;
|
|
70
87
|
// reporters must tell that apart from fixed system+schema overhead,
|
|
71
88
|
// which compaction never touches).
|
|
72
|
-
|
|
89
|
+
reduced = s.store.messages.length < before;
|
|
73
90
|
s.events.emit({
|
|
74
91
|
type: "context:compacted",
|
|
75
92
|
reason: reduced ? `pressure:${pressure}` : `pressure:${pressure}:no-op`,
|
|
76
93
|
});
|
|
77
94
|
pressure = s.budget.evaluate({
|
|
78
95
|
usedTokens: contextTokens(s),
|
|
79
|
-
limitTokens:
|
|
96
|
+
limitTokens: contextWindowTokens,
|
|
80
97
|
});
|
|
81
98
|
}
|
|
82
|
-
if (pressure
|
|
83
|
-
|
|
99
|
+
if (s.budget.shouldCompact(pressure) && reduced && budgetCompactions < maxBudgetCompactions) {
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (pressure === "critical") {
|
|
103
|
+
const used = contextTokens(s);
|
|
104
|
+
throw new AgentError(
|
|
105
|
+
"budget_exceeded",
|
|
106
|
+
`context window exceeded after compaction (${used} > ${contextWindowTokens}); reduce the prompt, tool output, or fixed instructions, or select a model with a larger context window`,
|
|
107
|
+
);
|
|
84
108
|
}
|
|
85
109
|
|
|
86
110
|
// Sample from the provider with deterministic recovery.
|
|
@@ -176,7 +200,11 @@ export async function executeTurn(
|
|
|
176
200
|
throw new AgentError("provider", errorMessage ?? "provider error", { cause: providerError ?? action });
|
|
177
201
|
case "force_compact_and_retry": {
|
|
178
202
|
if (compactedForRecovery)
|
|
179
|
-
throw new AgentError(
|
|
203
|
+
throw new AgentError(
|
|
204
|
+
"budget_exceeded",
|
|
205
|
+
`context window exceeded after recovery compaction: ${errorMessage ?? "context too large"}`,
|
|
206
|
+
{ cause: providerError ?? action },
|
|
207
|
+
);
|
|
180
208
|
await compactStore(s, signal);
|
|
181
209
|
// The recovery flag is ALWAYS set (even on no-op):
|
|
182
210
|
// force_compact_and_retry is exempt from maxProviderRetries, so a
|
|
@@ -301,6 +329,9 @@ function toolErrorResult(call: ToolCall, message: string): ToolResult {
|
|
|
301
329
|
|
|
302
330
|
function toProviderError(error: unknown, signal: AbortSignal): ProviderError {
|
|
303
331
|
if (signal.aborted) throw abortError(signal);
|
|
332
|
+
// Host-side admission guards (context budget, shutdown, etc.) preserve their
|
|
333
|
+
// deterministic AgentError identity instead of entering provider retry.
|
|
334
|
+
if (error instanceof AgentError) throw error;
|
|
304
335
|
if (error instanceof ProviderError) return error;
|
|
305
336
|
if (error instanceof Error && error.name === "AbortError") {
|
|
306
337
|
throw abortError(signal);
|
|
@@ -333,7 +364,11 @@ function delay(ms: number, signal: AbortSignal): Promise<void> {
|
|
|
333
364
|
function contextTokens(s: SessionInternal): number {
|
|
334
365
|
// Single source in tokens.ts `estimateSessionContext` — shared by the
|
|
335
366
|
// loop and the Session getter so no duplicate estimator can drift.
|
|
336
|
-
|
|
367
|
+
let system = s.system;
|
|
368
|
+
try {
|
|
369
|
+
system = s.systemForContext?.() ?? system;
|
|
370
|
+
} catch {}
|
|
371
|
+
return estimateSessionContext(s.store, system, s.registry.list(), s.estimator);
|
|
337
372
|
}
|
|
338
373
|
|
|
339
374
|
// The single compaction seam. Prefers the strategy's optional async method
|
|
@@ -35,5 +35,9 @@ export interface StreamRequest {
|
|
|
35
35
|
export interface ModelProvider {
|
|
36
36
|
readonly id: string;
|
|
37
37
|
readonly models: readonly string[];
|
|
38
|
+
/** Optional host metadata for per-model admission budgets. */
|
|
39
|
+
contextWindowTokensForModel?(model?: string): number;
|
|
40
|
+
/** Canonical provider/model key for per-model estimator state. */
|
|
41
|
+
contextModelIdentity?(model?: string): string | undefined;
|
|
38
42
|
stream(request: StreamRequest, signal: AbortSignal): AsyncIterable<ProviderEvent>;
|
|
39
43
|
}
|
|
@@ -35,6 +35,8 @@ export interface SessionConfig {
|
|
|
35
35
|
permissions: PermissionHandler;
|
|
36
36
|
tools?: readonly Tool[];
|
|
37
37
|
system?: string;
|
|
38
|
+
/** Dynamic system prompt for host-controlled per-turn mode hints. */
|
|
39
|
+
systemForContext?: () => string;
|
|
38
40
|
model?: string;
|
|
39
41
|
cwd?: string;
|
|
40
42
|
/**
|
|
@@ -59,6 +61,9 @@ export interface SessionConfig {
|
|
|
59
61
|
recovery?: RecoveryPolicy;
|
|
60
62
|
maxSteps?: number;
|
|
61
63
|
contextWindowTokens?: number;
|
|
64
|
+
/** Resolve a model-specific context limit for each run. Additive app seam;
|
|
65
|
+
* the numeric option remains the fallback for existing library callers. */
|
|
66
|
+
contextWindowTokensForModel?: (model?: string) => number;
|
|
62
67
|
toolResultMaxTokens?: number;
|
|
63
68
|
keepRecentTurns?: number;
|
|
64
69
|
/**
|
|
@@ -138,6 +143,7 @@ export interface SessionInternal {
|
|
|
138
143
|
readonly registry: ToolRegistry;
|
|
139
144
|
readonly executor: ToolExecutor;
|
|
140
145
|
readonly system?: string;
|
|
146
|
+
readonly systemForContext?: () => string;
|
|
141
147
|
readonly model?: string;
|
|
142
148
|
readonly cwd?: string;
|
|
143
149
|
readonly permissionMode?: string | (() => string);
|
|
@@ -147,6 +153,7 @@ export interface SessionInternal {
|
|
|
147
153
|
readonly recovery: RecoveryPolicy;
|
|
148
154
|
readonly maxSteps: number;
|
|
149
155
|
readonly contextWindowTokens: number;
|
|
156
|
+
readonly contextWindowTokensForModel?: (model?: string) => number;
|
|
150
157
|
readonly toolResultMaxTokens: number;
|
|
151
158
|
readonly keepRecentTurns: number;
|
|
152
159
|
readonly timeoutMs: number;
|
|
@@ -178,6 +185,7 @@ export function createSession(config: SessionConfig): Session {
|
|
|
178
185
|
registry: createToolRegistry(config.tools ?? []),
|
|
179
186
|
executor: config.executor ?? sequentialExecutor(),
|
|
180
187
|
system: config.system,
|
|
188
|
+
systemForContext: config.systemForContext,
|
|
181
189
|
model: config.model,
|
|
182
190
|
cwd: config.cwd,
|
|
183
191
|
permissionMode: config.permissionMode,
|
|
@@ -187,6 +195,7 @@ export function createSession(config: SessionConfig): Session {
|
|
|
187
195
|
recovery: config.recovery ?? defaultRecoveryPolicy,
|
|
188
196
|
maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS,
|
|
189
197
|
contextWindowTokens: config.contextWindowTokens ?? DEFAULT_CONTEXT_WINDOW_TOKENS,
|
|
198
|
+
contextWindowTokensForModel: config.contextWindowTokensForModel,
|
|
190
199
|
toolResultMaxTokens: config.toolResultMaxTokens ?? DEFAULT_TOOL_RESULT_MAX_TOKENS,
|
|
191
200
|
keepRecentTurns: config.keepRecentTurns ?? DEFAULT_KEEP_RECENT_TURNS,
|
|
192
201
|
timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
@@ -210,7 +219,11 @@ export function createSession(config: SessionConfig): Session {
|
|
|
210
219
|
// Same source of truth as the loop — estimateSessionContext in
|
|
211
220
|
// tokens.ts — never a duplicate estimator.
|
|
212
221
|
get contextTokens() {
|
|
213
|
-
|
|
222
|
+
let system = config.system
|
|
223
|
+
try {
|
|
224
|
+
system = config.systemForContext?.() ?? system
|
|
225
|
+
} catch {}
|
|
226
|
+
return estimateSessionContext(store, system, impl.registry.list(), impl.estimator);
|
|
214
227
|
},
|
|
215
228
|
async run(input, opts) {
|
|
216
229
|
if (impl.running) throw new AgentError("busy", "session is already running");
|