minicode-ai 0.28.0 → 0.30.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/README.md +1 -1
- package/cli/args.ts +93 -70
- package/cli/bootstrap/presentation-bridge.ts +383 -0
- package/cli/commands/acp.ts +7 -1
- package/cli/commands/doctor.ts +7 -3
- package/cli/commands/exec.ts +6 -16
- package/cli/index.ts +3 -2
- package/cli/setup.ts +13 -380
- package/cli/tui.ts +3 -4
- package/docs/TERMINAL_CONTRACT.md +28 -21
- package/docs/UI_RENDER_PIPELINE.md +3 -3
- package/docs/architecture.md +14 -29
- package/docs/environment.md +1 -1
- package/package.json +1 -1
- package/src/app/session.ts +201 -53
- package/src/app/tool-layer.ts +27 -0
- package/src/lib/atomic-write.ts +31 -59
- package/src/policy/jail.ts +6 -8
- package/src/providers/anthropic.ts +16 -5
- package/src/providers/responses.ts +37 -7
- package/src/providers/sse-bounds.ts +6 -4
- package/src/session/db/runs.ts +397 -0
- package/src/session/db/schema.ts +358 -0
- package/src/session/persistence.ts +64 -955
- package/src/task/db/schema.ts +325 -0
- package/src/task/db/types.ts +269 -0
- package/src/task/store.ts +74 -986
- package/src/ui/assistant/simple.ts +25 -19
- package/src/ui/i18n/en.ts +0 -3
- package/src/ui/i18n/id.ts +0 -3
- package/src/ui/render/logo.ts +15 -18
- package/src/ui/render/markdown-layout.ts +293 -0
- package/src/ui/render/markdown.ts +36 -44
- package/src/ui/render/session-summary.ts +1 -1
- package/src/ui/render/table-grid.ts +16 -7
- package/src/ui/render/width.ts +71 -18
- package/src/ui/render/wrap.ts +39 -22
- package/src/ui/session-state.ts +4 -4
- package/src/ui/tui/app.ts +15 -36
- package/src/ui/tui/transcript.ts +111 -50
- package/vendor/minicore/src/providers/openai-compat.ts +7 -0
|
@@ -102,7 +102,7 @@ tanpa IO) digerakkan `cli/` (`tui.ts`, `commands.ts`, `wizard.ts`,
|
|
|
102
102
|
resize, counter judul, scroll wheel/`j`/`k`/`Space`, dan salin `c` opsional); jendela
|
|
103
103
|
interaktif command (`/model`, `/provider`, `/sessions`, picker) berbagi
|
|
104
104
|
`dialogBox`/`hintLine` (dan `listRow` untuk daftar) yang sama serta mendukung scroll mouse
|
|
105
|
-
wheel. TUI fullscreen menampilkan
|
|
105
|
+
wheel. TUI fullscreen menampilkan logo kecil minicode di pojok kiri atas saat transkrip kosong/idle (tanpa identitas/hint di atas prompt),
|
|
106
106
|
`Tab` pada dropdown `/` untuk autocomplete, jeda antar-turn dan label bahasa fence redup,
|
|
107
107
|
serta fallback glyph `MINICODE_ASCII=1` konsisten hingga garis tabel dan ellipsis.
|
|
108
108
|
|
|
@@ -113,10 +113,10 @@ I = bisa diinterupsi, L = bisa tiba setelah completion.
|
|
|
113
113
|
|
|
114
114
|
| Event | Producer | Representasi UI | S | D | O | I | L |
|
|
115
115
|
|---|---|---|---|---|---|---|---|
|
|
116
|
-
| assistant text | provider stream | stdout wrap + fence
|
|
116
|
+
| assistant text | provider stream | stdout/TUI wrap ber-indentasi gantung (margin kiri 3 kolom adaptif, jeda antar-poin/heading/blok) + code fence 3-spasi; pipe-table-aligned di TTY, source sanitized di non-TTY | ya | tidak (E1) | tidak | ya (abort) | tidak (detach flush 1x, E6) |
|
|
117
117
|
| tool call | model → kernel | `› nama target` muted (compact: diam) | tidak | tidak | tidak | ya | tidak |
|
|
118
118
|
| tool result | tool → executor | ledger hijau/merah; minimize → `+ label` + buffer; panel aktivitas ON → baris grup per keluarga tool (`+ explore · N tools · N ok`) | tidak | tidak | tidak | ya | tidak |
|
|
119
|
-
| reasoning | provider extension | TUI composer
|
|
119
|
+
| reasoning | provider extension | default tersembunyi (TUI composer tetap dots clock, isi disimpan ke `/expand`); bila dibuka (`/thinking` / `Ctrl+T` / `MINICODE_SHOW_THINKING=1` / `--verbose`), panel aktivitas ON → AREA thinking live maks 10 baris (`+ thinking`, ringkas 1 baris saat turn selesai); panel OFF → alir per baris | ya | tidak | tidak | ya | tidak |
|
|
120
120
|
| thinking effort | picker `/model` | badge + level per model | tidak | tidak | tidak | tidak | tidak |
|
|
121
121
|
| usage | provider extension | verbose saja; masuk budget watcher | ya | tidak | ya (tail pasca-finish) | ya | ya (diabaikan aman) |
|
|
122
122
|
| compaction | kernel loop | `── compacted: <reason>` kuning, reason verbatim | tidak | tidak | tidak | tidak | tidak |
|
package/docs/architecture.md
CHANGED
|
@@ -68,43 +68,28 @@ prefix-compare 10 ms.
|
|
|
68
68
|
|
|
69
69
|
## Task system (state kerja durable)
|
|
70
70
|
|
|
71
|
-
Task state **bukan** chat history dan **bukan** tool trace.
|
|
72
|
-
`src/tools/todo.ts`; `.minicode/todos/<id>.json` adalah satu-satunya sumber
|
|
73
|
-
kebenaran, dan `plan.updated` (event durable untuk ACP/`exec --json`) hanyalah
|
|
74
|
-
**proyeksi** dari file itu.
|
|
71
|
+
Task state **bukan** chat history dan **bukan** tool trace. Sumber kebenaran durable adalah `TaskStore` di SQLite lokal workspace (`.minicode/tasks.db`, `src/task/store.ts` + `src/task/db/{types,schema}.ts`), sedangkan `src/tools/todo.ts` menjadi adapter model/tool (memperbarui `.minicode/todos/<id>.json` + menyinkronkan ke `TaskStore` via `synchronizeCanonicalTasks` di `src/task/sync.ts`), dan `plan.updated` (event durable untuk ACP/`exec --json`) adalah proyeksi downstream (`syncTodoViewsFromTaskStore`).
|
|
75
72
|
|
|
76
73
|
```text
|
|
77
|
-
todo_write (model) ─► normalizeTodos ─► .minicode/todos/<id>.json
|
|
78
|
-
│
|
|
79
|
-
│
|
|
80
|
-
│
|
|
81
|
-
|
|
82
|
-
|
|
74
|
+
todo_write (model) ─► normalizeTodos ─► .minicode/todos/<id>.json (snapshot proyeksi)
|
|
75
|
+
│ │
|
|
76
|
+
│ ▼
|
|
77
|
+
│ synchronizeCanonicalTasks ─► .minicode/tasks.db (TaskStore: authority)
|
|
78
|
+
│ ▲
|
|
79
|
+
▼ │ setCompletionEvidence
|
|
80
|
+
plan.updated (proyeksi downstream SETELAH sukses) ─┘
|
|
83
81
|
```
|
|
84
82
|
|
|
85
83
|
Tiga aturan yang menjaga domain ini:
|
|
86
84
|
|
|
87
|
-
1. **Identitas sesi kanonik (P2.1).** Todo terikat ke `sid` kanonik dari
|
|
85
|
+
1. **Identitas sesi kanonik (P2.1) & ID kanonik TaskStore (P4A).** Todo terikat ke `sid` kanonik dari
|
|
88
86
|
`resolveSessionIdentity` (`src/session/identity.ts`), bukan id volatil
|
|
89
87
|
proses (`bootId`). `--resume` tanpa `--session` tidak lagi menempa id
|
|
90
|
-
acak; `--resume` tak dikenal gagal eksplisit (`SESSION_NOT_FOUND`).
|
|
91
|
-
2. **Completion butuh bukti.** `setCompletionEvidence()` menyuntikkan verdict
|
|
88
|
+
acak; `--resume` tak dikenal gagal eksplisit (`SESSION_NOT_FOUND`). Alokasi `taskId` kanonik sepenuhnya milik `TaskStore`.
|
|
89
|
+
2. **Completion butuh bukti.** `setCompletionEvidence()` menyuntikkan verdict (`unverified` | `passed` | `failed` | `stale`) dari composition root. `failed` menolak
|
|
92
90
|
`completed` → task jadi `blocked` + alasannya, dan hasilnya dilaporkan ke
|
|
93
|
-
model. Default `unverified` menjaga pemakaian tanpa `--verify` tetap
|
|
94
|
-
|
|
95
|
-
3. **Satu normalizer, dua store.** `planFromTodos` ( adaptor) memanggil
|
|
96
|
-
`normalizeTodos` yang sama dengan file, sehingga status/cap/`blocked` tidak
|
|
97
|
-
bisa berbeda arah — dan plan event terbit di `execution:completed`, bukan
|
|
98
|
-
dari argumen sebelum tool jalan.
|
|
99
|
-
|
|
100
|
-
Batas subsystem **todo**: file todo tetap datar — tanpa field dependency di
|
|
101
|
-
`TodoItem`, tanpa surface user (`/tasks`), `/undo` hanya revert file (todo
|
|
102
|
-
tetap `completed`), dan tanpa TTL/GC untuk file todo di luar SQLite.
|
|
103
|
-
Dependency/graph dan scheduler **sudah ada**, tetapi pada subsystem terpisah:
|
|
104
|
-
TaskGraph + Scheduler di `src/task/` beroperasi di atas TaskStore
|
|
105
|
-
(`.minicode/tasks.db`), bukan di atas file todo; `todo_write` hanya boleh
|
|
106
|
-
menyentuhnya lewat `taskId` kanonik (`src/tools/todo.ts`), dan control
|
|
107
|
-
surface-nya `/scheduler` (off by default).
|
|
91
|
+
model; `requireVerified && unverified` menahan klaim di `VERIFYING` / menurunkannya sesuai gerbang verifikasi. Default `unverified` menjaga pemakaian tanpa `--verify` tetap berjalan; yang dilarang adalah completion diam-diam tanpa jejak.
|
|
92
|
+
3. **Satu otoritas status, satu jalur proyeksi.** `TaskStore` adalah satu-satunya otoritas mutasi/reconcile/claim (`TaskAuthority`: `LEGACY` vs `SCHEDULER`), sementara `TaskGraph` dan `ProductionScheduler` di `src/task/` beroperasi di atas `.minicode/tasks.db`; `todo_write` dan `/openwork` membaca serta menyinkronkan melalui adapter `src/task/sync.ts` dan `syncTodoViewsFromTaskStore` — dan `plan.updated` hanya terbit di `execution:completed`, bukan dari argumen sebelum tool jalan. (`/undo` tetap hanya me-revert berkas workspace, tidak membalik status task durable).
|
|
108
93
|
|
|
109
94
|
## Bukti verifikasi (P2.10)
|
|
110
95
|
|
|
@@ -133,7 +118,7 @@ Enam primitif tampilan (semuanya di dalam TUI fullscreen saat interaktif): trans
|
|
|
133
118
|
- `src/session/verification.ts` + `src/tools/evidence.ts`: identitas invokasi milik aplikasi, intent/receipt yang di-await, observasi eksplisit, idempotency, dan korelasi efek anak — semuanya di jurnal mutasi yang sama.
|
|
134
119
|
|
|
135
120
|
- `src/ui/render/`: `theme.ts` (getter `c`/`glyphs`, palet level-aware 16/256/truecolor), `width.ts` (kolom), `sanitize.ts` (hanya SGR lewat), `ledger.ts` (status word/glyph/paint + run-marker bersama untuk TUI & linear), `hint.ts` (grammar hint `kunci label` spasi-only), `list.ts` (`listRow` marker `›` + kolom tetap), `notice.ts` (notice sukses/error/info), `markdown.ts`, `markdown-table.ts` (parser pipe-table streaming), `table-grid.ts` (grid budget terminal), `cells.ts` (framebuffer sel grapheme+SGR + diff "tulis-ulang ekor" untuk penulisan inkremental), `composer-wrap.ts` (wrap composer inkremental), `highlight.ts diff.ts table.ts wrap.ts money.ts errors.ts`.
|
|
136
|
-
- `src/presentation/`: `events.ts` mendefinisikan event presentasi dan registry durability; `adapter.ts` memetakan runtime ke `DomainEvent`; `reducer.ts`/`model.ts` membangun state replayable dan ringkasan turunan; `store.ts` menyimpan referensi konten; `projection.ts` membentuk envelope `minicode.output.v1` dan kategori error machine. `src/session/persistence.ts` menyimpan log `presentation_events` dan `messages` dengan fidelity `reasoning`/`is_error`. `cli/setup.ts` memiliki bridge exhaustive `toPresentationEvent()`; renderer TUI/linear/machine memakai keputusan policy via injeksi `PresentationPolicy`.
|
|
121
|
+
- `src/presentation/`: `events.ts` mendefinisikan event presentasi dan registry durability; `adapter.ts` memetakan runtime ke `DomainEvent`; `reducer.ts`/`model.ts` membangun state replayable dan ringkasan turunan; `store.ts` menyimpan referensi konten; `projection.ts` membentuk envelope `minicode.output.v1` dan kategori error machine. `src/session/persistence.ts` dibantu `src/session/db/{schema,runs}.ts` menyimpan log `presentation_events`, `runs`, dan `messages` dengan fidelity `reasoning`/`is_error`. `src/task/store.ts` dibantu `src/task/db/{types,schema}.ts` mengelola `.minicode/tasks.db`. `cli/setup.ts` (delegating bridge presentasi via `cli/bootstrap/presentation-bridge.ts`) memiliki bridge exhaustive `toPresentationEvent()`; renderer TUI/linear/machine memakai keputusan policy via injeksi `PresentationPolicy`.
|
|
137
122
|
- `src/policy/`: `context.ts` (estimator sadar-densitas kode/JSON + kalibrasi usage), `context-window.ts` + `context-window-catalog.ts` (resolve window: config → katalog → models.dev → default 128K alias → 32K), `bpe.ts` + `tokenizer-registry.ts` (tokenizer BPE presisi on-demand dari HuggingFace, cache lokal, fallback densitas), `compaction.ts` (kompaksi LLM + mekanikal, anti-drift/anti-thrash, prefer provider sesi), `usage.ts`/`pricing.ts` (estimas biaya + models.dev).
|
|
138
123
|
- `src/ui/input/`: `askLine`, `prompt-engine` (grapheme `Intl.Segmenter`, streaming decoder, bracket-paste, mouse X10/SGR press/drag/release + wheel dinormalisasi; selection app-level di TUI).
|
|
139
124
|
- `src/ui/screens/`: view murni `picker/wizard/model-manager/provider-manager/form/dialog/output-window`; `output-window.ts` = jendela readout command ber-scroll di atas chat (v7.18).
|
package/docs/environment.md
CHANGED
|
@@ -90,7 +90,7 @@ Variabel yang paling menentukan perilaku (sisanya referensi di bawah):
|
|
|
90
90
|
| `MINICODE_BELL` | `0` → matikan bell `\x07` saat approval (aksesibilitas) |
|
|
91
91
|
| `MINICODE_STATUSLINE` | `rich` → statusline turn menampilkan token kumulatif + biaya sesi (default hemat) |
|
|
92
92
|
| `MINICODE_A11Y` | `1` → live-region approval untuk screen reader (baris polos tanpa ANSI) |
|
|
93
|
-
| `MINICODE_SHOW_THINKING` | reasoning model
|
|
93
|
+
| `MINICODE_SHOW_THINKING` | reasoning model tersembunyi SECARA DEFAULT (`false`); `1` → paksa terlihat (atau `/thinking` / `Ctrl+T` / `--verbose`), `0` → paksa tersembunyi |
|
|
94
94
|
| `MINICODE_MINIMIZE_ACTIVITY` | ON secara default di TUI; `0` → transparan (baris per-tool). Lipat aktivitas tool per turn jadi satu ringkasan (detail via `/expand`) |
|
|
95
95
|
| `MINICODE_ACTIVITY_PANEL` | `0` → matikan panel aktivitas (default AKTIF di TUI; `/fold` toggle); `1` → paksa aktif juga di jalur linear/one-shot |
|
|
96
96
|
| `MINICODE_AUTORESUME_BG` | `0` → nonaktifkan auto-resume turn TUI saat job background selesai (default aktif; sekali per job, hanya bila tidak ada turn berjalan) |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "minicode-ai",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.30.1",
|
|
4
4
|
"description": "Open-source terminal coding agent on a vendored zero-dependency MiniCore kernel — layered permissions, path jail, sandboxing, MCP/LSP, and durable shadow-git checkpoints",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"private": false,
|
package/src/app/session.ts
CHANGED
|
@@ -17,6 +17,7 @@ import {
|
|
|
17
17
|
estimateTools,
|
|
18
18
|
safeStringify,
|
|
19
19
|
} from "#minicore/core/tokens.ts"
|
|
20
|
+
import type { Message, UserMessage } from "#minicore/core/types.ts"
|
|
20
21
|
import { LIMITS } from "../constants.ts"
|
|
21
22
|
// [Area B · PROMPT 06] Binding persetujuan ↔ operasi yang dieksekusi.
|
|
22
23
|
import { ApprovalBindingStore, verifyApprovalBinding } from "../policy/approval-binding.ts"
|
|
@@ -180,6 +181,14 @@ export function createRecoveryLedger(now: () => number = Date.now): RecoveryLedg
|
|
|
180
181
|
export const cappedRecovery = {
|
|
181
182
|
onError(error: ProviderError, attempt: number): RecoveryAction {
|
|
182
183
|
const category = error.category
|
|
184
|
+
// 402 / kuota habis tidak akan sembuh dengan retry — fail-fast.
|
|
185
|
+
if (
|
|
186
|
+
category === "unknown" &&
|
|
187
|
+
(/\b402\b/.test(error.message) ||
|
|
188
|
+
/quota_exceeded|insufficient_quota|exceeded its quota/i.test(error.message))
|
|
189
|
+
) {
|
|
190
|
+
return { type: "throw" }
|
|
191
|
+
}
|
|
183
192
|
const ra = error.retryAfterMs
|
|
184
193
|
const saneRetryAfter =
|
|
185
194
|
ra != null && Number.isFinite(ra) && ra >= 0
|
|
@@ -249,10 +258,9 @@ export type WorkModeControl = {
|
|
|
249
258
|
*
|
|
250
259
|
* DISCUSS = investigasi baca-saja yang berorientasi diskusi: model membaca,
|
|
251
260
|
* mencari, dan bernalar, lalu MENYAJIKAN temuan/opsi/trade-off untuk didiskusikan
|
|
252
|
-
* dengan user — bukan menulis atau mengeksekusi apa pun.
|
|
253
|
-
*
|
|
254
|
-
*
|
|
255
|
-
* menambah apa pun (identitas).
|
|
261
|
+
* dengan user — bukan menulis atau mengeksekusi apa pun.
|
|
262
|
+
* BUILD (EXECUTE) = direktif aktif positif bahwa implementasi diizinkan dan
|
|
263
|
+
* mengabaikan pembatasan DISCUSS pada histori percakapan sebelumnya.
|
|
256
264
|
*
|
|
257
265
|
* Ini *guidance* (behavior), bukan enforcement — enforcement tetap milik ceiling
|
|
258
266
|
* handler `work-mode.ts`. Diekspor agar teruji langsung (pola repo pure/export).
|
|
@@ -260,13 +268,109 @@ export type WorkModeControl = {
|
|
|
260
268
|
export function workModeHint(workMode: WorkMode): string {
|
|
261
269
|
if (workMode === "DISCUSS") {
|
|
262
270
|
return (
|
|
263
|
-
"\n\nDISCUSS MODE: You are in read-only investigation, discussion, and planning mode. " +
|
|
271
|
+
"\n\nDISCUSS MODE (active): You are in read-only investigation, discussion, and planning mode. " +
|
|
264
272
|
"Do NOT modify files, run bash, or use write/edit tools. " +
|
|
265
273
|
"Read, search, and reason — investigate the question thoroughly, discuss findings, options, and trade-offs with the user, and produce a concrete implementation plan. " +
|
|
266
274
|
"Do not implement or execute any change."
|
|
267
275
|
)
|
|
268
276
|
}
|
|
269
|
-
return
|
|
277
|
+
return (
|
|
278
|
+
"\n\nBUILD MODE (active): Full implementation and execution tools are active. " +
|
|
279
|
+
"If earlier turns in the conversation occurred under read-only DISCUSS mode, ignore prior self-statements or plans about waiting/refusing edits — proceed directly to implement requested changes using write/edit/bash tools without asking for written confirmation unless genuine ambiguity remains."
|
|
280
|
+
)
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const PLAN_PM_HINT =
|
|
284
|
+
"\n\nPLAN MODE: You are in read-only planning mode. Do NOT modify files, run bash, or use write/edit tools. Only read, search, and reason — then output a concrete implementation plan."
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* Penanda live `PermissionMode` (`Auto`, `Ask`, `Unrestricted`, dsb.) pada
|
|
288
|
+
* system prompt supaya model memahami perilaku gerbang izin & tidak meminta
|
|
289
|
+
* konfirmasi tertulis yang tidak perlu saat berganti mode.
|
|
290
|
+
*/
|
|
291
|
+
export function permissionModeHint(
|
|
292
|
+
permissionMode: PermissionMode | undefined,
|
|
293
|
+
workMode: WorkMode,
|
|
294
|
+
): string {
|
|
295
|
+
if (!permissionMode) return ""
|
|
296
|
+
switch (permissionMode) {
|
|
297
|
+
case "plan":
|
|
298
|
+
return PLAN_PM_HINT
|
|
299
|
+
case "unrestricted":
|
|
300
|
+
return workMode === "EXECUTE"
|
|
301
|
+
? "\n\nPERMISSION MODE: UNRESTRICTED (active this session). Interactive approval prompts, workspace path jail, bash-guard, and allowlist restrictions are lifted; execute tools directly without asking confirmation."
|
|
302
|
+
: "\n\nPERMISSION MODE: UNRESTRICTED (suspended in DISCUSS mode — read-only ceiling and workspace path jail stay enforced until switching to BUILD)."
|
|
303
|
+
case "ask":
|
|
304
|
+
return "\n\nPERMISSION MODE: ASK (supervised). Non-read-only mutating/execution tools require interactive approval in the UI; invoke tools directly when ready — do NOT ask the user for written confirmation in chat before calling them."
|
|
305
|
+
case "auto":
|
|
306
|
+
return "\n\nPERMISSION MODE: AUTO (autonomous within workspace safety guards). Authorized workspace tools execute without confirmation prompts (`ask_user` is unavailable); act directly."
|
|
307
|
+
case "allow-all":
|
|
308
|
+
return "\n\nPERMISSION MODE: ALLOW-ALL. Workspace tools run autonomously subject to path jail and hard security guards."
|
|
309
|
+
case "allowlist":
|
|
310
|
+
return "\n\nPERMISSION MODE: ALLOWLIST. Shell commands are restricted to the configured bash allowlist; workspace path jail and hard security guards stay active."
|
|
311
|
+
case "readonly":
|
|
312
|
+
return "\n\nPERMISSION MODE: READONLY. Only read-only workspace tools are permitted."
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
export interface ModeSnapshot {
|
|
317
|
+
workMode: WorkMode
|
|
318
|
+
permissionMode?: PermissionMode
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const workModeLabel = (wm: WorkMode): "BUILD" | "DISCUSS" =>
|
|
322
|
+
wm === "EXECUTE" ? "BUILD" : "DISCUSS"
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Catatan transisi singkat ketika `WorkMode` atau `PermissionMode` berubah antar
|
|
326
|
+
* turn dalam sesi yang sama — disisipkan hanya di salinan wire request turn itu
|
|
327
|
+
* supaya model tidak terkecoh oleh histori turn sebelumnya saat bolak-balik mode.
|
|
328
|
+
*/
|
|
329
|
+
export function buildModeTransitionNote(prev: ModeSnapshot, curr: ModeSnapshot): string {
|
|
330
|
+
const parts: string[] = []
|
|
331
|
+
if (prev.workMode !== curr.workMode) {
|
|
332
|
+
parts.push(
|
|
333
|
+
curr.workMode === "EXECUTE"
|
|
334
|
+
? `WorkMode ${workModeLabel(prev.workMode)} -> BUILD (write/edit/bash tools NOW ENABLED; ignore prior read-only/planning statements in history and implement directly without asking written confirmation)`
|
|
335
|
+
: `WorkMode ${workModeLabel(prev.workMode)} -> DISCUSS (read-only mode NOW ACTIVE; do NOT modify files or run mutating commands)`,
|
|
336
|
+
)
|
|
337
|
+
}
|
|
338
|
+
if (prev.permissionMode !== curr.permissionMode && curr.permissionMode) {
|
|
339
|
+
const fromLabel = (prev.permissionMode ?? "auto").toUpperCase()
|
|
340
|
+
const toLabel = curr.permissionMode.toUpperCase()
|
|
341
|
+
if (curr.permissionMode === "unrestricted") {
|
|
342
|
+
parts.push(
|
|
343
|
+
curr.workMode === "EXECUTE"
|
|
344
|
+
? `PermissionMode ${fromLabel} -> UNRESTRICTED (full access active; approval prompts, jail, and bash-guard bypassed)`
|
|
345
|
+
: `PermissionMode ${fromLabel} -> UNRESTRICTED (read-only DISCUSS ceiling stays active until switching to BUILD)`,
|
|
346
|
+
)
|
|
347
|
+
} else if (curr.permissionMode === "ask") {
|
|
348
|
+
parts.push(
|
|
349
|
+
`PermissionMode ${fromLabel} -> ASK (supervised; call tools directly — approval prompt is automatic in UI)`,
|
|
350
|
+
)
|
|
351
|
+
} else {
|
|
352
|
+
parts.push(
|
|
353
|
+
`PermissionMode ${fromLabel} -> ${toLabel} (autonomous workspace execution active)`,
|
|
354
|
+
)
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
return parts.length > 0 ? `[Runtime mode update: ${parts.join("; ")}]` : ""
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function annotateLastUserMessage(messages: readonly Message[], note: string): readonly Message[] {
|
|
361
|
+
if (!note) return messages
|
|
362
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
363
|
+
const msg = messages[i]
|
|
364
|
+
if (msg?.role !== "user") continue
|
|
365
|
+
const content: UserMessage["content"] =
|
|
366
|
+
typeof msg.content === "string"
|
|
367
|
+
? `${note}\n\n${msg.content}`
|
|
368
|
+
: [{ type: "text", text: `${note}\n` }, ...msg.content]
|
|
369
|
+
const next = messages.slice()
|
|
370
|
+
next[i] = { ...msg, content }
|
|
371
|
+
return next
|
|
372
|
+
}
|
|
373
|
+
return messages
|
|
270
374
|
}
|
|
271
375
|
|
|
272
376
|
export async function createMinicodeSession(
|
|
@@ -401,6 +505,9 @@ export async function createMinicodeSession(
|
|
|
401
505
|
* ini perilaku identik seperti sebelumnya.
|
|
402
506
|
*/
|
|
403
507
|
beforeToolEffect?: (call: { id: string; name: string; args: unknown }) => Promise<void>
|
|
508
|
+
/** Tool tak-tersedia yang skemanya disembunyikan pada request wire LLM
|
|
509
|
+
* (tidak mengubah registry `tools`/permission kanonik). */
|
|
510
|
+
hiddenWireTools?: ReadonlySet<string>
|
|
404
511
|
},
|
|
405
512
|
): Promise<Session> {
|
|
406
513
|
// Normalisasi root sekali di composition agar ToolContext selalu memiliki path tepercaya.
|
|
@@ -414,12 +521,10 @@ export async function createMinicodeSession(
|
|
|
414
521
|
`createMinicodeSession: workMode ${resolvedWorkMode} dengan permissionHandler terinjeksi belum didukung (fail-closed S2.1)`,
|
|
415
522
|
)
|
|
416
523
|
}
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
//
|
|
420
|
-
//
|
|
421
|
-
// pembungkus provider supaya transisi runtime `/work-mode` maupun `/mode`
|
|
422
|
-
// tercermin langsung di StreamRequest.system tanpa mengedit vendor/minicore.
|
|
524
|
+
// P0.2 (G-PROMPT-RT): rakit bagian dasar sekali, lalu tambahkan `workModeHint`
|
|
525
|
+
// + `permissionModeHint` secara LIVE per-turn lewat pembungkus provider supaya
|
|
526
|
+
// transisi runtime `/work-mode` maupun `/mode` & `/unrestric` tercermin
|
|
527
|
+
// langsung di StreamRequest.system tanpa mengedit vendor/minicore.
|
|
423
528
|
const baseSystem = await buildSystemPrompt({
|
|
424
529
|
cwd: defaultCwd,
|
|
425
530
|
extra: opts.systemExtra ?? "",
|
|
@@ -450,6 +555,7 @@ export async function createMinicodeSession(
|
|
|
450
555
|
noProgress,
|
|
451
556
|
onNoProgress,
|
|
452
557
|
approvalBindings: _approvalBindings,
|
|
558
|
+
hiddenWireTools,
|
|
453
559
|
...rest
|
|
454
560
|
} = opts
|
|
455
561
|
if (!provider) throw new Error("createMinicodeSession: provider is required")
|
|
@@ -674,13 +780,19 @@ export async function createMinicodeSession(
|
|
|
674
780
|
// Teruskan mode live ke kernel agar ToolContext.permissionMode selalu
|
|
675
781
|
// mencerminkan Shift+Tab saat itu (bukan snapshot saat sesi dibuat).
|
|
676
782
|
const livePermissionMode = (): PermissionMode => (injected ? "readonly" : withMode.__getMode())
|
|
783
|
+
const liveWorkModeForSystem = (): WorkMode =>
|
|
784
|
+
injected ? resolvedWorkMode : (wmCtl.__getWorkMode?.() ?? resolvedWorkMode)
|
|
785
|
+
const livePermissionModeForSystem = (): PermissionMode | undefined =>
|
|
786
|
+
injected ? opts.permissionMode : withMode.__getMode()
|
|
787
|
+
let lastTurnMode: ModeSnapshot | null = null
|
|
788
|
+
let activeTurnTransitionNote = ""
|
|
789
|
+
let turnSentStream = false
|
|
677
790
|
const computeLiveSystem = (): string => {
|
|
678
|
-
const pm =
|
|
679
|
-
const wm =
|
|
680
|
-
const planHint = pm === "plan" ? PLAN_PM_HINT : ""
|
|
791
|
+
const pm = livePermissionModeForSystem()
|
|
792
|
+
const wm = liveWorkModeForSystem()
|
|
681
793
|
const contextWindow = contextWindowForModel(currentContextModel())
|
|
682
794
|
const capacityHint = `\n\n# Harness context capacity\nThe harness currently budgets ${contextWindow} tokens for the selected model. This is the configured/resolved session limit, not a guarantee from the provider. It is independent of the Windows operating system and shell. System instructions, tool schemas, history, and output share this budget; compaction starts before the full window is exhausted. Preserve durable task progress before compaction.`
|
|
683
|
-
return baseSystem +
|
|
795
|
+
return baseSystem + workModeHint(wm) + permissionModeHint(pm, wm) + capacityHint
|
|
684
796
|
}
|
|
685
797
|
// [CTX] Kalibrasi dipisahkan per identitas model agar berpindah ke model
|
|
686
798
|
// lain tidak membawa rasio tokenizer/provider dari sesi sebelumnya.
|
|
@@ -840,7 +952,11 @@ export async function createMinicodeSession(
|
|
|
840
952
|
return provider.models
|
|
841
953
|
},
|
|
842
954
|
async *stream(req, signal) {
|
|
955
|
+
turnSentStream = true
|
|
843
956
|
const system = computeLiveSystem()
|
|
957
|
+
const messages = activeTurnTransitionNote
|
|
958
|
+
? annotateLastUserMessage(req.messages, activeTurnTransitionNote)
|
|
959
|
+
: req.messages
|
|
844
960
|
const model = req.model ?? currentContextModel()
|
|
845
961
|
let limit = contextWindowForModel(model)
|
|
846
962
|
let maxOutputTokens = maxOutputTokensForModel(model)
|
|
@@ -848,23 +964,27 @@ export async function createMinicodeSession(
|
|
|
848
964
|
let calibration = calibrationFor(estimatorModel)
|
|
849
965
|
let estimator = (text: string) => preciseEstimator(estimatorModel, text)
|
|
850
966
|
let admittedFactor = calibration.snapshot().factor
|
|
851
|
-
const
|
|
967
|
+
const rawTools = req.tools ?? []
|
|
968
|
+
const tools =
|
|
969
|
+
hiddenWireTools && hiddenWireTools.size > 0
|
|
970
|
+
? rawTools.filter((t) => !hiddenWireTools.has(t.name))
|
|
971
|
+
: rawTools
|
|
852
972
|
const localInputTokens =
|
|
853
|
-
estimateMessages(
|
|
973
|
+
estimateMessages(messages, minicodeEstimator) +
|
|
854
974
|
estimateSystem(system, minicodeEstimator) +
|
|
855
975
|
estimateTools(tools, minicodeEstimator)
|
|
856
976
|
let inputTokens =
|
|
857
|
-
estimateMessages(
|
|
977
|
+
estimateMessages(messages, estimator) +
|
|
858
978
|
estimateSystem(system, estimator) +
|
|
859
979
|
estimateTools(tools, estimator)
|
|
860
980
|
// Anchor ukuran nyata: jangan biarkan estimasi (chars/4, bisa under-count
|
|
861
981
|
// 2–5× pada kode/JSON) jatuh di bawah input asli terakhir provider. Input
|
|
862
982
|
// hanya tumbuh antar-turn normal; bila jumlah pesan menyusut (kompaksi,
|
|
863
983
|
// rewind/checkpoint, atau clear), reset anchor agar tidak memicu overflow palsu.
|
|
864
|
-
if (
|
|
984
|
+
if (messages.length < lastRequestMessageCount) {
|
|
865
985
|
lastProviderInputTokens = undefined
|
|
866
986
|
}
|
|
867
|
-
lastRequestMessageCount =
|
|
987
|
+
lastRequestMessageCount = messages.length
|
|
868
988
|
if (lastProviderInputTokens !== undefined && lastProviderInputTokens > inputTokens) {
|
|
869
989
|
inputTokens = lastProviderInputTokens
|
|
870
990
|
}
|
|
@@ -895,7 +1015,7 @@ export async function createMinicodeSession(
|
|
|
895
1015
|
// cutoff ini palsu (inflasi kalibrasi) — bukan konteks benar-benar penuh.
|
|
896
1016
|
factor: calibration.snapshot().factor,
|
|
897
1017
|
localInputTokens: localInputTokens,
|
|
898
|
-
storeMessages:
|
|
1018
|
+
storeMessages: messages.length,
|
|
899
1019
|
},
|
|
900
1020
|
})
|
|
901
1021
|
let clientOverflowErr: ProviderError | undefined
|
|
@@ -926,7 +1046,15 @@ export async function createMinicodeSession(
|
|
|
926
1046
|
throw error
|
|
927
1047
|
}
|
|
928
1048
|
|
|
929
|
-
for await (const event of provider.stream(
|
|
1049
|
+
for await (const event of provider.stream(
|
|
1050
|
+
{
|
|
1051
|
+
...req,
|
|
1052
|
+
messages,
|
|
1053
|
+
system,
|
|
1054
|
+
...(hiddenWireTools && hiddenWireTools.size > 0 ? { tools } : {}),
|
|
1055
|
+
},
|
|
1056
|
+
requestController.signal,
|
|
1057
|
+
)) {
|
|
930
1058
|
if (event.type === "extension" && event.kind === "effective-model") {
|
|
931
1059
|
const effective = event.data as { effective?: unknown; provider?: unknown } | undefined
|
|
932
1060
|
if (
|
|
@@ -945,7 +1073,7 @@ export async function createMinicodeSession(
|
|
|
945
1073
|
admittedFactor = calibration.snapshot().factor
|
|
946
1074
|
inputTokens = Math.max(
|
|
947
1075
|
inputTokens,
|
|
948
|
-
estimateMessages(
|
|
1076
|
+
estimateMessages(messages, estimator) +
|
|
949
1077
|
estimateSystem(system, estimator) +
|
|
950
1078
|
estimateTools(tools, estimator),
|
|
951
1079
|
)
|
|
@@ -957,7 +1085,7 @@ export async function createMinicodeSession(
|
|
|
957
1085
|
if (currentFactor > admittedFactor) {
|
|
958
1086
|
inputTokens = Math.max(
|
|
959
1087
|
inputTokens,
|
|
960
|
-
estimateMessages(
|
|
1088
|
+
estimateMessages(messages, estimator) +
|
|
961
1089
|
estimateSystem(system, estimator) +
|
|
962
1090
|
estimateTools(tools, estimator),
|
|
963
1091
|
)
|
|
@@ -1177,35 +1305,55 @@ export async function createMinicodeSession(
|
|
|
1177
1305
|
run(input: string, runOpts?: { signal?: AbortSignal; model?: string }) {
|
|
1178
1306
|
activeContextModel = runOpts?.model ?? opts.model
|
|
1179
1307
|
const modelForRun = activeContextModel
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
escalateContextWindow(modelForRun, used, true)
|
|
1308
|
+
const startMode: ModeSnapshot = {
|
|
1309
|
+
workMode: liveWorkModeForSystem(),
|
|
1310
|
+
permissionMode: livePermissionModeForSystem(),
|
|
1311
|
+
}
|
|
1312
|
+
activeTurnTransitionNote = lastTurnMode
|
|
1313
|
+
? buildModeTransitionNote(lastTurnMode, startMode)
|
|
1314
|
+
: ""
|
|
1315
|
+
turnSentStream = false
|
|
1316
|
+
return core
|
|
1317
|
+
.run(input, runOpts)
|
|
1318
|
+
.finally(() => {
|
|
1319
|
+
if (turnSentStream) {
|
|
1320
|
+
lastTurnMode = {
|
|
1321
|
+
workMode: liveWorkModeForSystem(),
|
|
1322
|
+
permissionMode: livePermissionModeForSystem(),
|
|
1323
|
+
}
|
|
1197
1324
|
}
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1325
|
+
activeTurnTransitionNote = ""
|
|
1326
|
+
turnSentStream = false
|
|
1327
|
+
})
|
|
1328
|
+
.catch((error: unknown) => {
|
|
1329
|
+
// Kernel melaporkan kehabisan konteks sebagai `budget_exceeded` dengan
|
|
1330
|
+
// `details.reason` = `fixpoint` atau `critical`. Keduanya BUKTI
|
|
1331
|
+
// terverifikasi bahwa jendela yang dipakai terlalu kecil untuk sesi ini
|
|
1332
|
+
// — sama sahnya dengan penolakan provider. Tanpa eskalasi di sini,
|
|
1333
|
+
// sesi yang sudah di titik tetap langsung mati padahal endpoint mungkin
|
|
1334
|
+
// punya kapasitas jauh lebih besar.
|
|
1335
|
+
//
|
|
1336
|
+
// Bukan pemicu: `max_steps_exceeded`, `max_turns`, `aborted`, timeout,
|
|
1337
|
+
// dan error provider non-konteks — menaikkan jendela tak akan menolong.
|
|
1338
|
+
// (`max_steps_exceeded` punya jalurnya sendiri: eskalasi batas langkah.)
|
|
1339
|
+
if (error instanceof AgentError && error.kind === "budget_exceeded") {
|
|
1340
|
+
const reason = error.details?.reason
|
|
1341
|
+
if (reason === "fixpoint" || reason === "critical") {
|
|
1342
|
+
const used =
|
|
1343
|
+
typeof error.details?.fixedTokens === "number" ? error.details.fixedTokens : 0
|
|
1344
|
+
escalateContextWindow(modelForRun, used, true)
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
// [T-008] Turn mentok batas langkah: naik satu tangga untuk turn
|
|
1348
|
+
// berikutnya. Kerja turn ini tetap hilang (kernel sudah berhenti), tapi
|
|
1349
|
+
// turn lanjutan tidak akan menabrak dinding yang sama. Bounded: satu
|
|
1350
|
+
// langkah per kejadian, dibatasi STEP_LIMIT_CEILING.
|
|
1351
|
+
if (error instanceof AgentError && error.kind === "max_steps_exceeded") {
|
|
1352
|
+
const used = typeof error.details?.steps === "number" ? error.details.steps : 0
|
|
1353
|
+
escalateMaxSteps(used)
|
|
1354
|
+
}
|
|
1355
|
+
throw error
|
|
1356
|
+
})
|
|
1209
1357
|
},
|
|
1210
1358
|
abort() {
|
|
1211
1359
|
core.abort()
|
package/src/app/tool-layer.ts
CHANGED
|
@@ -18,6 +18,33 @@ const errMsg = (e: unknown) => (e instanceof Error ? e.message : String(e))
|
|
|
18
18
|
|
|
19
19
|
export type ToolScope = "full" | "explore"
|
|
20
20
|
|
|
21
|
+
const MCP_WIRE_TOOLS = ["mcp_list", "mcp_call", "mcp_read", "mcp_prompt"] as const
|
|
22
|
+
const LSP_WIRE_TOOLS = [
|
|
23
|
+
"lsp_diagnostics",
|
|
24
|
+
"lsp_definition",
|
|
25
|
+
"lsp_references",
|
|
26
|
+
"lsp_hover",
|
|
27
|
+
"lsp_symbols",
|
|
28
|
+
"lsp_workspace_symbols",
|
|
29
|
+
] as const
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Daftar tool yang skemanya aman disembunyikan dari wire API ketika kapabilitas
|
|
33
|
+
* runtime-nya tidak aktif (MCP/LSP kosong, sandbox none, atau non-interaktif),
|
|
34
|
+
* agar token prompt awal hemat tanpa mengubah registry izin/WorkMode kanonik.
|
|
35
|
+
*/
|
|
36
|
+
export function computeUnavailableWireTools(
|
|
37
|
+
cfg: Pick<MinicodeConfig, "mcpServers" | "lspServers">,
|
|
38
|
+
opts: { sandboxMode?: string; interactiveAsk?: boolean } = {},
|
|
39
|
+
): Set<string> {
|
|
40
|
+
const hidden = new Set<string>()
|
|
41
|
+
if (!cfg.mcpServers?.length) for (const n of MCP_WIRE_TOOLS) hidden.add(n)
|
|
42
|
+
if (!cfg.lspServers?.length) for (const n of LSP_WIRE_TOOLS) hidden.add(n)
|
|
43
|
+
if (!opts.sandboxMode || opts.sandboxMode === "none") hidden.add("code_run")
|
|
44
|
+
if (opts.interactiveAsk === false) hidden.add("ask_user")
|
|
45
|
+
return hidden
|
|
46
|
+
}
|
|
47
|
+
|
|
21
48
|
// WorkMode ceiling (DISCUSS menyatukan diskusi + perencanaan; EXECUTE = BUILD).
|
|
22
49
|
// Invariant INV-WM1 & #7: WorkMode TIDAK PERNAH memperluas akses; `visible`
|
|
23
50
|
// diselaraskan penuh dengan `callable` di handler:
|