minicode-ai 0.22.0 → 0.25.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.
Files changed (100) hide show
  1. package/README.md +2 -2
  2. package/cli/commands.ts +10 -0
  3. package/cli/index.ts +11 -0
  4. package/cli/setup.ts +64 -33
  5. package/cli/tui.ts +29 -3
  6. package/docs/README.md +2 -2
  7. package/docs/SUMMARY.md +10 -19
  8. package/docs/TERMINAL_CONTRACT.md +119 -32
  9. package/docs/architecture.md +1 -1
  10. package/docs/autonomous-scheduler.md +283 -2
  11. package/docs/choosing-mode.md +4 -4
  12. package/docs/concepts.md +39 -3
  13. package/docs/config.md +90 -4
  14. package/docs/environment.md +6 -0
  15. package/docs/getting-started.md +58 -2
  16. package/docs/repl.md +1 -1
  17. package/docs/security.md +49 -2
  18. package/docs/tools.md +2 -1
  19. package/package.json +2 -36
  20. package/src/app/provider-layer.ts +1 -1
  21. package/src/app/session.ts +129 -20
  22. package/src/config.ts +102 -2
  23. package/src/constants.ts +32 -4
  24. package/src/lib/safe-open.ts +21 -12
  25. package/src/memory/vector.ts +0 -31
  26. package/src/policy/compaction.ts +27 -0
  27. package/src/policy/context-budget.ts +132 -0
  28. package/src/policy/context-escalation.ts +140 -0
  29. package/src/policy/context-window.ts +14 -9
  30. package/src/policy/context.ts +10 -1
  31. package/src/policy/microcompact.ts +162 -0
  32. package/src/policy/no-progress.ts +1 -1
  33. package/src/policy/permission.ts +5 -0
  34. package/src/policy/scrub.ts +15 -2
  35. package/src/policy/tool-contract.ts +11 -9
  36. package/src/presentation/reducer.ts +1 -0
  37. package/src/providers/anthropic.ts +17 -3
  38. package/src/providers/detect.ts +155 -13
  39. package/src/providers/provision.ts +92 -1
  40. package/src/providers/responses.ts +13 -1
  41. package/src/session/persistence.ts +56 -0
  42. package/src/task/autonomous-policy.ts +7 -0
  43. package/src/task/graph-validate.ts +1 -1
  44. package/src/task/session-authority.ts +0 -5
  45. package/src/task/store.ts +0 -4
  46. package/src/tools/ask_user.ts +14 -1
  47. package/src/tools/bash.ts +57 -9
  48. package/src/tools/context.ts +10 -0
  49. package/src/tools/delete_file.ts +3 -2
  50. package/src/tools/edit.ts +5 -4
  51. package/src/tools/git.ts +70 -12
  52. package/src/tools/glob.ts +13 -5
  53. package/src/tools/grep.ts +26 -10
  54. package/src/tools/index.ts +3 -2
  55. package/src/tools/lsp.ts +15 -9
  56. package/src/tools/move_file.ts +4 -3
  57. package/src/tools/patch.ts +5 -4
  58. package/src/tools/read_file.ts +3 -2
  59. package/src/tools/read_image.ts +3 -2
  60. package/src/tools/task.ts +1 -0
  61. package/src/tools/todo.ts +4 -8
  62. package/src/tools/write_file.ts +4 -3
  63. package/src/ui/approval/prompt.ts +226 -77
  64. package/src/ui/assistant/simple.ts +1 -1
  65. package/src/ui/footer.ts +41 -29
  66. package/src/ui/i18n/en.ts +23 -4
  67. package/src/ui/i18n/id.ts +25 -4
  68. package/src/ui/input/input.ts +2 -2
  69. package/src/ui/render/activity-group.ts +1 -0
  70. package/src/ui/render/activity-panel.ts +21 -3
  71. package/src/ui/render/hint.ts +28 -0
  72. package/src/ui/render/ledger.ts +1 -9
  73. package/src/ui/render/logo.ts +86 -0
  74. package/src/ui/render/markdown-table.ts +0 -3
  75. package/src/ui/render/session-summary.ts +22 -1
  76. package/src/ui/render/table-grid.ts +0 -3
  77. package/src/ui/render/theme.ts +36 -5
  78. package/src/ui/runtime/screen.ts +11 -3
  79. package/src/ui/screens/dialog.ts +45 -81
  80. package/src/ui/screens/form.ts +29 -33
  81. package/src/ui/screens/lifecycle.ts +80 -0
  82. package/src/ui/screens/model-manager.ts +84 -91
  83. package/src/ui/screens/picker.ts +36 -33
  84. package/src/ui/screens/provider-manager.ts +50 -59
  85. package/src/ui/screens/watchdog.ts +27 -0
  86. package/src/ui/screens/wizard.ts +3 -20
  87. package/src/ui/tui/app.ts +97 -11
  88. package/src/ui/tui/transcript.ts +55 -16
  89. package/vendor/minicore/src/core/compact.ts +10 -0
  90. package/vendor/minicore/src/core/errors.ts +11 -1
  91. package/vendor/minicore/src/core/executor.ts +6 -1
  92. package/vendor/minicore/src/core/loop.ts +92 -2
  93. package/vendor/minicore/src/core/session.ts +8 -0
  94. package/vendor/minicore/src/providers/openai-compat.ts +15 -2
  95. package/docs/P14_OPEN_WORK.md +0 -290
  96. package/docs/config-providers.md +0 -87
  97. package/docs/glossary.md +0 -39
  98. package/docs/quickstart.md +0 -60
  99. package/docs/security-model.md +0 -96
  100. package/docs/terminal.md +0 -91
@@ -2,10 +2,26 @@ import { LIMITS } from "../constants.ts"
2
2
 
3
3
  export interface DetectedModel {
4
4
  id: string
5
+ /**
6
+ * Jendela konteks yang DILAPORKAN endpoint `/models`, bila ada.
7
+ *
8
+ * KENAPA dibaca: kapasitas endpoint yang benar-benar dipanggil adalah sumber
9
+ * otoritatif — katalog publik bisa basi atau tidak mengenali alias gateway.
10
+ * Nilai ini tidak dikarang: hanya diisi bila endpoint menyertakannya.
11
+ */
12
+ contextLength?: number
13
+ /** Batas output model (`max_output_tokens`) bila dilaporkan. Dipakai sebagai
14
+ * reserve output proporsional, bukan angka tetap. */
15
+ maxOutputTokens?: number
16
+ /** Dukungan cache yang dilaporkan endpoint (Fase 7.1); `undefined` = tak disebut. */
17
+ promptCaching?: boolean
5
18
  }
6
19
 
7
20
  export interface DetectResult {
8
21
  models: string[]
22
+ /** Metadata per model, hanya untuk model yang endpoint-nya melaporkan
23
+ * kapasitas. Model tanpa metadata tidak muncul di sini (tidak dikarang). */
24
+ modelMetadata?: Record<string, DetectedModel>
9
25
  providerHint: "openai" | "anthropic" | "responses" | "unknown"
10
26
  /**
11
27
  * True bila server menjawab 401/403 di salah satu attempt: key salah/
@@ -40,11 +56,136 @@ function hybridHeaders(apiKey: string): Record<string, string>[] {
40
56
  ]
41
57
  }
42
58
 
59
+ /**
60
+ * Nama field yang dipakai berbagai gateway/agregator untuk melaporkan
61
+ * kapasitas konteks. Tidak ada standar tunggal: OpenAI-compat memakai
62
+ * `context_length`, Anthropic-style memakai `max_input_tokens`, agregator
63
+ * memakai `context_window` atau menyarangkan di `top_provider`.
64
+ *
65
+ * KENAPA daftar eksplisit, bukan tebakan berbasis substring: field bernama
66
+ * `max_tokens` pada sebagian endpoint berarti batas OUTPUT, bukan konteks —
67
+ * memetakannya sebagai konteks akan mengecilkan jendela secara diam-diam,
68
+ * persis kelas bug yang ingin dihilangkan.
69
+ */
70
+ const CONTEXT_FIELD_ALIASES = [
71
+ "context_length",
72
+ "context_window",
73
+ "max_context_length",
74
+ "max_context_tokens",
75
+ "max_input_tokens",
76
+ "input_token_limit",
77
+ ] as const
78
+
79
+ const OUTPUT_FIELD_ALIASES = [
80
+ "max_output_tokens",
81
+ "max_completion_tokens",
82
+ "max_output",
83
+ "output_token_limit",
84
+ ] as const
85
+
86
+ /** Field penanda dukungan cache (boolean, atau objek = ya). */
87
+ const CACHE_FIELD_ALIASES = [
88
+ "prompt_caching",
89
+ "prompt_cache",
90
+ "supports_prompt_caching",
91
+ "supports_cache",
92
+ "cache_control",
93
+ ] as const
94
+
95
+ /** `undefined` (tak disebut) harus beda dari `false` (menolak) — tri-state. */
96
+ function extractCacheSupport(obj: Record<string, unknown>): boolean | undefined {
97
+ for (const key of CACHE_FIELD_ALIASES) {
98
+ if (!(key in obj)) continue
99
+ const v = obj[key]
100
+ if (typeof v === "boolean") return v
101
+ return v !== null && v !== undefined && v !== "" && v !== 0
102
+ }
103
+ return undefined
104
+ }
105
+
106
+ function positiveInt(value: unknown): number | undefined {
107
+ if (typeof value !== "number" || !Number.isFinite(value)) return undefined
108
+ const n = Math.floor(value)
109
+ // Batas atas jauh di atas kapasitas model publik mana pun (2M) — menolak
110
+ // nilai rusak/absurd tanpa menolak model nyata.
111
+ return n > 0 && n <= 20_000_000 ? n : undefined
112
+ }
113
+
114
+ function pickField(obj: Record<string, unknown>, aliases: readonly string[]): number | undefined {
115
+ for (const key of aliases) {
116
+ const v = positiveInt(obj[key])
117
+ if (v !== undefined) return v
118
+ }
119
+ return undefined
120
+ }
121
+
122
+ /**
123
+ * Ekstrak metadata kapasitas dari satu entri `/models`.
124
+ *
125
+ * Diekspor untuk test: perilaku yang paling penting diuji di sini — payload
126
+ * tanpa field kapasitas harus menghasilkan `undefined` (bukan angka karangan).
127
+ */
128
+ export function extractModelCapacity(entry: unknown): {
129
+ contextLength?: number
130
+ maxOutputTokens?: number
131
+ promptCaching?: boolean
132
+ } {
133
+ if (!entry || typeof entry !== "object") return {}
134
+ const obj = entry as Record<string, unknown>
135
+ // Agregator menyarangkan kapasitas di `top_provider`, tapi sebagian juga
136
+ // menduplikasinya di level atas — cek keduanya, level atas menang karena
137
+ // itu yang paling spesifik untuk model ini.
138
+ const nested =
139
+ obj.top_provider && typeof obj.top_provider === "object"
140
+ ? (obj.top_provider as Record<string, unknown>)
141
+ : undefined
142
+ const contextLength =
143
+ pickField(obj, CONTEXT_FIELD_ALIASES) ??
144
+ (nested ? pickField(nested, CONTEXT_FIELD_ALIASES) : undefined)
145
+ const maxOutputTokens =
146
+ pickField(obj, OUTPUT_FIELD_ALIASES) ??
147
+ (nested ? pickField(nested, OUTPUT_FIELD_ALIASES) : undefined)
148
+ // Level atas menang; `top_provider` hanya fallback.
149
+ const promptCaching =
150
+ extractCacheSupport(obj) ?? (nested ? extractCacheSupport(nested) : undefined)
151
+ return {
152
+ ...(contextLength !== undefined ? { contextLength } : {}),
153
+ ...(maxOutputTokens !== undefined ? { maxOutputTokens } : {}),
154
+ ...(promptCaching !== undefined ? { promptCaching } : {}),
155
+ }
156
+ }
157
+
158
+ /** Petakan entri mentah `/models` → id + metadata (hanya yang dilaporkan). */
159
+ function mapEntries(raw: unknown[]): {
160
+ models: string[]
161
+ modelMetadata?: Record<string, DetectedModel>
162
+ } {
163
+ const models: string[] = []
164
+ let metadata: Record<string, DetectedModel> | undefined
165
+ for (const entry of raw) {
166
+ if (!entry || typeof entry !== "object") continue
167
+ const id = (entry as { id?: unknown }).id
168
+ if (typeof id !== "string" || !id) continue
169
+ models.push(id)
170
+ const capacity = extractModelCapacity(entry)
171
+ if (capacity.contextLength !== undefined || capacity.maxOutputTokens !== undefined) {
172
+ metadata ??= {}
173
+ metadata[id] = { id, ...capacity }
174
+ }
175
+ }
176
+ return { models, ...(metadata ? { modelMetadata: metadata } : {}) }
177
+ }
178
+
43
179
  async function tryFetchModels(
44
180
  baseUrl: string,
45
181
  headers: Record<string, string>,
46
182
  signal: AbortSignal,
47
- ): Promise<{ models: string[] | null; contacted: boolean; sawAuth: boolean }> {
183
+ ): Promise<{
184
+ models: string[] | null
185
+ modelMetadata?: Record<string, DetectedModel>
186
+ contacted: boolean
187
+ sawAuth: boolean
188
+ }> {
48
189
  const urls = [`${baseUrl.replace(/\/+$/, "")}/models`, `${baseUrl.replace(/\/+$/, "")}/v1/models`]
49
190
  let contacted = false
50
191
  let sawAuth = false
@@ -61,17 +202,17 @@ async function tryFetchModels(
61
202
  // terlihat sukses tersimpan).
62
203
  if (res.status === 401 || res.status === 403) sawAuth = true
63
204
  if (!res.ok) continue
64
- const json = (await res.json()) as { data?: { id: string }[]; models?: { id: string }[] }
205
+ const json = (await res.json()) as { data?: unknown[]; models?: unknown[] }
65
206
  const data = json.data ?? json.models ?? []
66
- if (Array.isArray(data) && data.length)
67
- return { models: data.map((m) => m.id).filter(Boolean), contacted, sawAuth }
68
- // anthropic format: {data: [{id, display_name}]}
69
- if (Array.isArray((json as unknown as { models: unknown }).models)) {
70
- return {
71
- models: (json as unknown as { models: { id: string }[] }).models.map((m) => m.id),
72
- contacted,
73
- sawAuth,
74
- }
207
+ if (Array.isArray(data) && data.length) {
208
+ const mapped = mapEntries(data)
209
+ if (mapped.models.length)
210
+ return {
211
+ models: mapped.models,
212
+ ...(mapped.modelMetadata ? { modelMetadata: mapped.modelMetadata } : {}),
213
+ contacted,
214
+ sawAuth,
215
+ }
75
216
  }
76
217
  } catch {}
77
218
  }
@@ -94,7 +235,7 @@ export async function detectModels(
94
235
  let everAuthFailed = false
95
236
  for (const h of hybridHeaders(apiKey)) {
96
237
  if (sig.aborted) break
97
- const { models, contacted, sawAuth } = await tryFetchModels(baseUrl, h, sig)
238
+ const { models, modelMetadata, contacted, sawAuth } = await tryFetchModels(baseUrl, h, sig)
98
239
  everContacted = everContacted || contacted
99
240
  everAuthFailed = everAuthFailed || sawAuth
100
241
  if (models?.length) {
@@ -110,8 +251,9 @@ export async function detectModels(
110
251
  ? "anthropic"
111
252
  : "openai"
112
253
  const uniqueModels = Array.from(new Set(models))
113
- const result = {
254
+ const result: DetectResult = {
114
255
  models: uniqueModels,
256
+ ...(modelMetadata ? { modelMetadata } : {}),
115
257
  providerHint: hint as DetectResult["providerHint"],
116
258
  authFailed: everAuthFailed,
117
259
  }
@@ -5,6 +5,7 @@
5
5
  import { readFile } from "node:fs/promises"
6
6
  import { resolve } from "node:path"
7
7
  import {
8
+ type ContextWindowSource,
8
9
  globalConfigPath,
9
10
  LOCAL,
10
11
  loadConfig,
@@ -106,6 +107,80 @@ export function deriveProviderId(baseUrl: string, existingIds: string[], id?: st
106
107
  return uniqId
107
108
  }
108
109
 
110
+ /**
111
+ * Gabungkan metadata kapasitas yang DITEMUKAN endpoint ke entri provider.
112
+ *
113
+ * Aturan presedensi (alasannya sama dengan `resolveContextWindow`):
114
+ * - Nilai ber-`source: "user"` milik operator TIDAK PERNAH ditimpa. Config lama
115
+ * tanpa catatan asal diperlakukan `user` supaya perilaku tidak berubah diam-diam.
116
+ * - Nilai `endpoint`/`probe` boleh diperbarui oleh deteksi berikutnya — endpoint
117
+ * yang dipanggil hari ini lebih tahu daripada hasil deteksi kemarin.
118
+ * - Model yang hilang dari `/models` (sudah tak ada) dibuang agar config tidak
119
+ * mengumpulkan nilai basi untuk model yang tak bisa dipakai lagi.
120
+ *
121
+ * Diekspor untuk test: ini satu-satunya tempat yang menentukan "siapa menang".
122
+ */
123
+ export function mergeDiscoveredCapacity(
124
+ previous: ProviderEntry | undefined,
125
+ detected: DetectResult,
126
+ ): Pick<
127
+ ProviderEntry,
128
+ "contextWindows" | "contextWindowSources" | "maxOutputTokens" | "enablePromptCaching"
129
+ > {
130
+ const metadata = detected.modelMetadata
131
+ if (!metadata || Object.keys(metadata).length === 0) return {}
132
+ const prevWindows = previous?.contextWindows ?? {}
133
+ const prevSources = previous?.contextWindowSources ?? {}
134
+ const prevMaxOut = previous?.maxOutputTokens ?? {}
135
+ const windows: Record<string, number> = {}
136
+ const sources: Record<string, ContextWindowSource> = {}
137
+ const maxOut: Record<string, number> = {}
138
+ for (const [model, meta] of Object.entries(metadata)) {
139
+ // Buang entri untuk model yang tak lagi ditawarkan endpoint (basi).
140
+ // Model di luar metadata tetap dipertahankan dari config lama di bawah.
141
+ const prevSource = prevSources[model]
142
+ const userOwned =
143
+ prevSource === undefined ? prevWindows[model] !== undefined : prevSource === "user"
144
+ if (meta.contextLength !== undefined && !userOwned) {
145
+ windows[model] = meta.contextLength
146
+ sources[model] = "endpoint"
147
+ }
148
+ if (meta.maxOutputTokens !== undefined) maxOut[model] = meta.maxOutputTokens
149
+ }
150
+ // Pertahankan yang tak dilaporkan endpoint kali ini (endpoint bisa parsial:
151
+ // sebagian gateway hanya menyertakan kapasitas untuk model yang baru
152
+ // ditambahkan). `live` hanya dipakai untuk membuang model yang endpoint
153
+ // TIDAK menawarkan lagi — bukan untuk membuang nilai yang belum dilaporkan.
154
+ const live = new Set(detected.models)
155
+ for (const [model, tokens] of Object.entries(prevWindows)) {
156
+ if (live.size > 0 && !live.has(model)) continue
157
+ if (windows[model] === undefined) {
158
+ windows[model] = tokens
159
+ sources[model] = prevSources[model] ?? "user"
160
+ }
161
+ }
162
+ for (const [model, tokens] of Object.entries(prevMaxOut)) {
163
+ if (live.size > 0 && !live.has(model)) continue
164
+ if (maxOut[model] === undefined) maxOut[model] = tokens
165
+ }
166
+ // Fase 7.1: satu model mendukung = provider mendukung; false bila semua menolak.
167
+ let caching: boolean | undefined
168
+ for (const meta of Object.values(metadata)) {
169
+ if (meta.promptCaching === true) {
170
+ caching = true
171
+ break
172
+ }
173
+ if (meta.promptCaching === false) caching ??= false
174
+ }
175
+
176
+ return {
177
+ ...(Object.keys(windows).length > 0 ? { contextWindows: windows } : {}),
178
+ ...(Object.keys(sources).length > 0 ? { contextWindowSources: sources } : {}),
179
+ ...(Object.keys(maxOut).length > 0 ? { maxOutputTokens: maxOut } : {}),
180
+ ...(caching !== undefined ? { enablePromptCaching: caching } : {}),
181
+ }
182
+ }
183
+
109
184
  export async function detectAndSave(
110
185
  baseUrl: string,
111
186
  apiKey: string,
@@ -158,6 +233,9 @@ export async function detectAndSave(
158
233
  // ini tiap add/edit me-reset effort ke default diam-diam ("hilang").
159
234
  const previous = prevCfg.providers.find((p) => p.id === uniqId)
160
235
  const prevEffort = previous?.reasoningEffort
236
+ // Kapasitas dari metadata endpoint (bila dilaporkan) diutamakan atas tebakan
237
+ // statis, tapi tak pernah menimpa nilai `user` — lihat mergeDiscoveredCapacity.
238
+ const capacity = mergeDiscoveredCapacity(previous, detected)
161
239
  const entry: ProviderEntry = {
162
240
  id: uniqId,
163
241
  baseUrl,
@@ -165,6 +243,7 @@ export async function detectAndSave(
165
243
  models: detected.models,
166
244
  providerHint: detected.providerHint,
167
245
  ...(previous?.contextWindows ? { contextWindows: previous.contextWindows } : {}),
246
+ ...capacity,
168
247
  ...(prevEffort ? { reasoningEffort: prevEffort } : {}),
169
248
  }
170
249
  await saveProvider(entry, opts)
@@ -250,7 +329,14 @@ export async function refreshProviderModels(
250
329
  try {
251
330
  const detected = await detectModels(p.baseUrl, apiKey)
252
331
  if (detected.models.length) {
253
- updated.set(p.id, { ...p, models: detected.models, providerHint: detected.providerHint })
332
+ // Metadata kapasitas ikut disegarkan: gateway yang menambah/mengubah
333
+ // model akan memperbarui jendela konteksnya tanpa user menyentuh apa pun.
334
+ updated.set(p.id, {
335
+ ...p,
336
+ models: detected.models,
337
+ providerHint: detected.providerHint,
338
+ ...mergeDiscoveredCapacity(p, detected),
339
+ })
254
340
  } else if (detected.authFailed) {
255
341
  // Key ditolak (401/403): bedakan dari provider tanpa endpoint
256
342
  // (Anthropic-style, tetap diam) — operator harus periksa key-nya.
@@ -290,6 +376,11 @@ export async function refreshProviderModels(
290
376
  if (nu) {
291
377
  p.models = nu.models
292
378
  p.providerHint = nu.providerHint
379
+ // Kapasitas hanya ditulis bila hasil merge memang punya isi — tanpa
380
+ // guard ini provider tanpa metadata akan menghapus nilai lama.
381
+ if (nu.contextWindows) p.contextWindows = nu.contextWindows
382
+ if (nu.contextWindowSources) p.contextWindowSources = nu.contextWindowSources
383
+ if (nu.maxOutputTokens) p.maxOutputTokens = nu.maxOutputTokens
293
384
  changed = true
294
385
  }
295
386
  }
@@ -262,12 +262,23 @@ export function createResponsesProvider(config: ResponsesConfig): ModelProvider
262
262
  // budget/cost (buta spend). Bentuk shape sama dengan adapter
263
263
  // openai-compat agar kolektor tak perlu tahu provider.
264
264
  const u = resp?.usage as
265
- | { input_tokens?: unknown; output_tokens?: unknown; total_tokens?: unknown }
265
+ | {
266
+ input_tokens?: unknown
267
+ output_tokens?: unknown
268
+ total_tokens?: unknown
269
+ cached_tokens?: unknown
270
+ input_tokens_details?: { cached_tokens?: unknown }
271
+ }
266
272
  | undefined
267
273
  if (
268
274
  u &&
269
275
  (u.input_tokens != null || u.output_tokens != null || u.total_tokens != null)
270
276
  ) {
277
+ // Fase 7: cache-hit alias (input_tokens_details.cached_tokens / cached_tokens).
278
+ const cached =
279
+ (u.input_tokens_details?.cached_tokens !== undefined
280
+ ? u.input_tokens_details.cached_tokens
281
+ : u.cached_tokens) ?? undefined
271
282
  yield {
272
283
  type: "extension",
273
284
  kind: "usage",
@@ -276,6 +287,7 @@ export function createResponsesProvider(config: ResponsesConfig): ModelProvider
276
287
  outputTokens:
277
288
  typeof u.output_tokens === "number" ? u.output_tokens : undefined,
278
289
  totalTokens: typeof u.total_tokens === "number" ? u.total_tokens : undefined,
290
+ ...(typeof cached === "number" ? { cacheReadTokens: cached } : {}),
279
291
  },
280
292
  }
281
293
  }
@@ -891,6 +891,22 @@ export function loadPresentationEvents(id: string, cwd?: string): DomainEvent[]
891
891
  return loadPresentationEventsWithStats(id, cwd).events
892
892
  }
893
893
 
894
+ /** Hitung kompaksi durable via kolom `type` (jangan muat+decode seluruh
895
+ * presentation_events — resume dulu tarik semua baris hanya untuk hitung revisi). */
896
+ export function countDurableCompactionEvents(sessionId: string, cwd?: string): number {
897
+ const db = open(cwd)
898
+ try {
899
+ const row = db
900
+ .prepare(
901
+ "SELECT COUNT(*) AS n FROM presentation_events WHERE session_id = ? AND type = 'context.compacted'",
902
+ )
903
+ .get(sessionId) as { n: number } | null
904
+ return row?.n ?? 0
905
+ } finally {
906
+ db.close()
907
+ }
908
+ }
909
+
894
910
  // P2.12 — baca rentang untuk replay konsumen. WAJIB ada: `loadPresentationEvents`
895
911
  // memuat SELURUH riwayat ke memori, dan konsumen yang attach dengan offset lama
896
912
  // akan menarik seluruh sesi (ratusan ribu baris) hanya untuk 200 event terakhir
@@ -1557,6 +1573,46 @@ export function loadSession(
1557
1573
  }
1558
1574
  }
1559
1575
 
1576
+ /**
1577
+ * Meta sesi TANPA decode histori pesan. Jalur resume hanya butuh turnCount/
1578
+ * workMode/system/cwd; histori penuh dibaca SEKALI lewat `loadThreadHistoryWithSeq`.
1579
+ * Memisahkan meta dari decode menutup bug perf: dulu resume memanggil `loadSession`
1580
+ * (decode SEMUA messages) + `loadThreadHistoryWithSeq` (decode lagi) — dua kali
1581
+ * JSON.parse seluruh histori.
1582
+ */
1583
+ export function loadSessionMeta(
1584
+ id: string,
1585
+ cwd?: string,
1586
+ ): {
1587
+ system?: string
1588
+ cwd?: string
1589
+ turnCount: number
1590
+ workMode?: "DISCUSS" | "PLAN" | "EXECUTE"
1591
+ } | null {
1592
+ const db = open(cwd)
1593
+ try {
1594
+ const sess = db.prepare("SELECT system, cwd, work_mode FROM sessions WHERE id = ?").get(id) as {
1595
+ system: string
1596
+ cwd: string
1597
+ work_mode: string | null
1598
+ } | null
1599
+ if (!sess) return null
1600
+ const turnRow = db
1601
+ .prepare("SELECT MAX(turn_idx) AS m FROM turns WHERE session_id = ?")
1602
+ .get(id) as { m: number | null } | null
1603
+ const turnCount = turnRow?.m != null ? turnRow.m + 1 : 0
1604
+ const workMode = parseStoredWorkMode(sess.work_mode)
1605
+ return {
1606
+ system: sess.system,
1607
+ cwd: sess.cwd,
1608
+ turnCount,
1609
+ ...(workMode ? { workMode } : {}),
1610
+ }
1611
+ } finally {
1612
+ db.close()
1613
+ }
1614
+ }
1615
+
1560
1616
  // P2.4: baca histori SATU thread (ketat: tanpa NULL transisional).
1561
1617
  // Beda dari loadSession (kompatibel): di sini thread scope eksplisit.
1562
1618
  export function loadThreadHistory(sessionId: string, threadId: string, cwd?: string): unknown[] {
@@ -189,6 +189,13 @@ export const TOOL_CAPABILITIES: readonly ToolClassification[] = [
189
189
  evidence:
190
190
  "VERIFIED: writes history and identity. The existing sub-agent layer strips it for the same reason (src/tools/task.ts:309-321).",
191
191
  },
192
+ {
193
+ name: "git_push",
194
+ capability: "PRIVILEGED",
195
+ autonomous: false,
196
+ evidence:
197
+ "VERIFIED: publishes local history to a remote - irreversible outside this machine and visible to others. Same class as git_commit; the sub-agent layer strips it too.",
198
+ },
192
199
 
193
200
  // ── memory (session state) ──
194
201
  {
@@ -212,7 +212,7 @@ export function analyseRelations(nodes: readonly GraphNode[]): RelationAnalysis
212
212
  * what distinguishes "seen in this walk" (a cycle) from "seen in an earlier
213
213
  * walk" (already settled).
214
214
  *
215
- * Fan-out is intentionally unbounded: `MAX_PARENT` is declared in TaskStore but
215
+ * Fan-out is intentionally unbounded: `MAX_PARENT` used to be declared in TaskStore but
216
216
  * enforced nowhere, so the width of a containment forest is not bounded here
217
217
  * either (design lock S5).
218
218
  */
@@ -91,11 +91,6 @@ export function newOwnerToken(): string {
91
91
  return `own-${Date.now().toString(36)}-${counter.toString(36)}-${rand}`
92
92
  }
93
93
 
94
- /** Test-only: make token generation reproducible. */
95
- export function resetOwnerTokenCounterForTests(): void {
96
- counter = 0
97
- }
98
-
99
94
  /** The durable row. One per (session, incarnation). */
100
95
  export interface SessionAuthority {
101
96
  readonly sessionId: string
package/src/task/store.ts CHANGED
@@ -88,8 +88,6 @@ function emitTaskTransition(
88
88
  /** Bounds so the JSON columns cannot grow without limit. */
89
89
  const MAX_DEPENDS_ON = 32
90
90
  const MAX_EVIDENCE = 32
91
- const MAX_ACCEPTANCE = 32
92
- const MAX_PARENT = 64
93
91
 
94
92
  /** Shape of the data, not of the table: this rises when column SEMANTICS
95
93
  * change, not merely when a column is added. */
@@ -2923,5 +2921,3 @@ export function legacyDigest(raw: string): string {
2923
2921
  const { createHash } = require("node:crypto") as typeof import("node:crypto")
2924
2922
  return createHash("sha256").update(scrubSecrets(raw)).digest("hex").slice(0, 32)
2925
2923
  }
2926
-
2927
- export const __testing = { MAX_DEPENDS_ON, MAX_EVIDENCE, MAX_ACCEPTANCE, MAX_PARENT }
@@ -11,6 +11,19 @@ import type { ApprovalEventHook, ApprovalHookEvent } from "../presentation/event
11
11
 
12
12
  export type AskTextFn = (question: string, options?: string[]) => Promise<string | null>
13
13
 
14
+ /**
15
+ * Potong tanpa membelah pasangan surrogate: `slice` mentah menyisakan surrogate
16
+ * tinggi yatim → U+FFFD (AUD-010). Lapisan tool tak boleh impor src/ui.
17
+ */
18
+ function sliceSafeChars(s: string, max: number): string {
19
+ if (s.length <= max) return s
20
+ let end = max
21
+ const code = s.charCodeAt(end - 1)
22
+ // Surrogate tinggi di posisi terakhir = pasangannya ikut terpotong; mundur 1.
23
+ if (code >= 0xd800 && code <= 0xdbff) end -= 1
24
+ return s.slice(0, Math.max(0, end))
25
+ }
26
+
14
27
  let askTextFn: AskTextFn | undefined
15
28
 
16
29
  export function setAskTextFn(fn: AskTextFn | undefined): void {
@@ -61,7 +74,7 @@ export const askUserTool: Tool = {
61
74
  .slice(0, 2000)
62
75
  if (!q) throw new Error("question empty")
63
76
  const opts = Array.isArray(options)
64
- ? (options as unknown[]).map((o) => String(o).slice(0, 200)).slice(0, 8)
77
+ ? (options as unknown[]).map((o) => sliceSafeChars(String(o), 200)).slice(0, 8)
65
78
  : undefined
66
79
  // Tanpa view ter-inject atau di luar TTY: tolak, jangan gantung.
67
80
  // Model harus melanjutkan dengan asumsi paling aman, bukan menunggu.
package/src/tools/bash.ts CHANGED
@@ -4,7 +4,7 @@ import { resolve as resolvePath } from "node:path"
4
4
  import type { Tool, ToolContext } from "#minicore"
5
5
  import { LIMITS } from "../constants.ts"
6
6
  import { isCwdOutsideRoot, isPathOutsideRoot } from "../policy/jail.ts"
7
- import { requireToolCwd } from "./context.ts"
7
+ import { contextUnrestricted, requireToolCwd } from "./context.ts"
8
8
 
9
9
  // re-export untuk backward compat (helper kini terpusat di policy/scrub)
10
10
  export { SECRET_ENV_RE, sanitizeSpawnEnv, stripSecretsEnv } from "../policy/scrub.ts"
@@ -88,6 +88,34 @@ interface BackgroundJob {
88
88
 
89
89
  const jobs = new Map<string, BackgroundJob>()
90
90
 
91
+ /**
92
+ * Pendengar selesainya job background: lapisan cli memakainya untuk repaint
93
+ * badge footer + satu auto-resume terbatas. Tool hanya mengumumkan fakta
94
+ * "job X selesai dengan exit N" — tak tahu apa pun soal UI/prompt. Set agar
95
+ * unsubscribe idempoten dan aman saat listener menghapus dirinya saat emit.
96
+ */
97
+ const finishListeners = new Set<(id: string, code: number | null) => void>()
98
+
99
+ /** Daftarkan pendengar selesai job. Return = fungsi unsubscribe (idempoten). */
100
+ export function onBackgroundJobFinished(
101
+ listener: (id: string, code: number | null) => void,
102
+ ): () => void {
103
+ finishListeners.add(listener)
104
+ return () => {
105
+ finishListeners.delete(listener)
106
+ }
107
+ }
108
+
109
+ function emitBackgroundJobFinished(id: string, code: number | null): void {
110
+ // Satu listener yang melempar tak boleh menahan listener lain ATAU
111
+ // menggagalkan handler `close` proses anak.
112
+ for (const listener of [...finishListeners]) {
113
+ try {
114
+ listener(id, code)
115
+ } catch {}
116
+ }
117
+ }
118
+
91
119
  // F-03 (P5 §C2): gerbang akses job. Hanya pemilik (sid sama, null==null untuk
92
120
  // jalur legacy) yang boleh inspect/cancel. Kegagalan karena kepemilikan
93
121
  // menghasilkan TIDAK ADA — pemanggil tak bisa membedakan "job milik sesi lain"
@@ -221,7 +249,12 @@ export function listBackgroundJobs(): { id: string; cmd: string; done: boolean }
221
249
  return [...jobs.values()].map((j) => ({ id: j.id, cmd: j.cmd, done: j.done }))
222
250
  }
223
251
 
224
- function startBackground(cmd: string, cwd: string | undefined, ownerSid: string | null): string {
252
+ function startBackground(
253
+ cmd: string,
254
+ cwd: string | undefined,
255
+ ownerSid: string | null,
256
+ relaxed = false,
257
+ ): string {
225
258
  reapFinishedJobs()
226
259
  const live = [...jobs.values()].filter((j) => !j.done).length
227
260
  if (live >= LIMITS.BASH_BACKGROUND_MAX_JOBS) {
@@ -233,7 +266,7 @@ function startBackground(cmd: string, cwd: string | undefined, ownerSid: string
233
266
  const proc = spawn(cmd, {
234
267
  shell: true,
235
268
  cwd,
236
- env: sanitizeSpawnEnv(process.env),
269
+ env: sanitizeSpawnEnv(process.env, undefined, relaxed),
237
270
  stdio: ["ignore", "pipe", "pipe"],
238
271
  // detached agar shell jadi group leader → killTree bisa menutup SELURUH
239
272
  // grup (POSIX kill(-pid)). Tanpa ini yang bisa dibunuh cuma wrapper shell
@@ -260,13 +293,23 @@ function startBackground(cmd: string, cwd: string | undefined, ownerSid: string
260
293
  const piece = job.buffer.append("err", d)
261
294
  if (piece) job.chunks.push(scrubSecrets(piece))
262
295
  })
296
+ // Emit sekali per job: `error` biasanya disusul `close` (emit ganda =
297
+ // dua auto-resume). Guard lokal cukup — kedua handler berbagi closure.
298
+ let emitted = false
299
+ const emitOnce = (code: number | null): void => {
300
+ if (emitted) return
301
+ emitted = true
302
+ emitBackgroundJobFinished(id, code)
303
+ }
263
304
  proc.on("error", (e) => {
264
305
  job.chunks.push(`[error] ${e.message}`)
265
306
  job.done = true
307
+ emitOnce(null)
266
308
  })
267
309
  proc.on("close", (code) => {
268
310
  job.exitCode = code
269
311
  job.done = true
312
+ emitOnce(code)
270
313
  })
271
314
  jobs.set(id, job)
272
315
  return id
@@ -300,8 +343,9 @@ function makeBashTool(ownerSid: string | null): Tool {
300
343
  },
301
344
  async execute({ cmd, cwd, timeoutMs, background }, ctx) {
302
345
  const sessionRoot = requireToolCwd(ctx)
346
+ const relaxed = contextUnrestricted(ctx)
303
347
  const c = cwd as string | undefined
304
- if (c && (isCwdOutsideRoot(c, sessionRoot) || isPathOutsideRoot(c, sessionRoot)))
348
+ if (!relaxed && c && (isCwdOutsideRoot(c, sessionRoot) || isPathOutsideRoot(c, sessionRoot)))
305
349
  throw new Error(`cwd outside workspace: ${c}`)
306
350
  const resolvedCwd = c ? resolvePath(sessionRoot, c) : undefined
307
351
  const effectiveCwd = resolvedCwd ?? sessionRoot
@@ -313,7 +357,11 @@ function makeBashTool(ownerSid: string | null): Tool {
313
357
  // symlink — tak bisa ditutup murah dari sini (shell mengikuti symlink by
314
358
  // design; safe-open O_NOFOLLOW hanya untuk tool file). Mitigasi: --sandbox
315
359
  // untuk isolasi penuh; lihat permission.ts jail + safe-open.ts.
316
- const timeout = timeoutMs ?? LIMITS.BASH_DEFAULT_TIMEOUT_MS
360
+ // Unrestricted: default timeout jauh lebih lega; timeoutMs eksplisit
361
+ // tetap menang.
362
+ const timeout =
363
+ timeoutMs ??
364
+ (relaxed ? LIMITS.UNRESTRICTED_BASH_TIMEOUT_MS : LIMITS.BASH_DEFAULT_TIMEOUT_MS)
317
365
 
318
366
  if (background === true) {
319
367
  // Sandbox tidak diterapkan di jalur background: container/namespace
@@ -324,7 +372,7 @@ function makeBashTool(ownerSid: string | null): Tool {
324
372
  "background:true is not supported while --sandbox is active (the process must outlive the turn)",
325
373
  )
326
374
  }
327
- const id = startBackground(cmd as string, resolvedCwd, ownerSid)
375
+ const id = startBackground(cmd as string, resolvedCwd, ownerSid, relaxed)
328
376
  // F-07: echo perintah di-scrub seperti output foreground — command line
329
377
  // bisa membawa secret (`curl -H "Authorization: Bearer …"`), dan versi
330
378
  // lama menaruhnya mentah ke konteks model.
@@ -336,7 +384,7 @@ function makeBashTool(ownerSid: string | null): Tool {
336
384
  if (dockerAvailable()) {
337
385
  const res = await runInDocker(cmd as string, effectiveCwd, {
338
386
  timeoutMs: timeout,
339
- env: sanitizeSpawnEnv(process.env) as Record<string, string>,
387
+ env: sanitizeSpawnEnv(process.env, undefined, relaxed) as Record<string, string>,
340
388
  signal: ctx.signal,
341
389
  })
342
390
  ctx.signal.throwIfAborted()
@@ -363,7 +411,7 @@ function makeBashTool(ownerSid: string | null): Tool {
363
411
  if (osSandboxAvailable()) {
364
412
  const res = await runInOsSandbox(cmd as string, effectiveCwd, {
365
413
  timeoutMs: timeout,
366
- env: sanitizeSpawnEnv(process.env) as Record<string, string>,
414
+ env: sanitizeSpawnEnv(process.env, undefined, relaxed) as Record<string, string>,
367
415
  })
368
416
  const text = scrubSecrets(res.output)
369
417
  if (res.code !== 0 && res.code !== null)
@@ -394,7 +442,7 @@ function makeBashTool(ownerSid: string | null): Tool {
394
442
  // undefined (= inherit process.cwd()). Jail/permission dievaluasi
395
443
  // terhadap sessionRoot — eksekusi harus di direktori yang sama.
396
444
  cwd: effectiveCwd,
397
- env: sanitizeSpawnEnv(process.env),
445
+ env: sanitizeSpawnEnv(process.env, undefined, relaxed),
398
446
  signal: ctx.signal,
399
447
  // detached agar shell jadi group leader → killTree bisa bunuh
400
448
  // seluruh grup (POSIX kill(-pid)). Tanpa ini cucu yatim menahan pipe.