minicode-ai 0.14.2 → 0.14.5

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 (78) hide show
  1. package/README.md +34 -178
  2. package/cli/args.ts +10 -18
  3. package/cli/commands/acp.ts +20 -27
  4. package/cli/commands/daemon.ts +6 -7
  5. package/cli/commands/exec.ts +12 -10
  6. package/cli/commands.ts +6 -9
  7. package/cli/index.ts +30 -15
  8. package/cli/provider-manager.ts +1 -3
  9. package/cli/setup.ts +188 -143
  10. package/cli/tui.ts +15 -23
  11. package/docs/CONTROL-PLANE-MAP.md +145 -0
  12. package/docs/OUTPUT_EVENT_MODEL.md +1 -1
  13. package/docs/OUTPUT_PROTOCOL_SPEC.md +2 -2
  14. package/docs/OUTPUT_RENDERING_SPEC.md +7 -2
  15. package/docs/OUTPUT_UX_RULES.md +1 -1
  16. package/docs/README.md +14 -102
  17. package/docs/SUMMARY.md +53 -0
  18. package/docs/TERMINAL_CONTRACT.md +84 -51
  19. package/docs/UI_RENDER_PIPELINE.md +204 -0
  20. package/docs/agents.md +5 -5
  21. package/docs/architecture.md +23 -12
  22. package/docs/choosing-mode.md +7 -7
  23. package/docs/cli.md +22 -29
  24. package/docs/concepts.md +1 -1
  25. package/docs/config.md +10 -5
  26. package/docs/contributing.md +6 -6
  27. package/docs/environment.md +3 -1
  28. package/docs/exec.md +5 -5
  29. package/docs/glossary.md +8 -6
  30. package/docs/memory-sessions.md +7 -5
  31. package/docs/policy-sandbox.md +16 -14
  32. package/docs/quickstart.md +2 -2
  33. package/docs/repl.md +4 -3
  34. package/docs/security-model.md +14 -15
  35. package/docs/security.md +8 -29
  36. package/docs/skills.md +1 -1
  37. package/docs/tools.md +2 -2
  38. package/package.json +5 -3
  39. package/scripts/vendor-overlays/minicode-context.patch +109 -0
  40. package/src/app/provider-layer.ts +13 -1
  41. package/src/app/session.ts +231 -13
  42. package/src/config.ts +30 -3
  43. package/src/constants.ts +2 -0
  44. package/src/daemon/control.ts +1 -1
  45. package/src/mcp/server.ts +2 -3
  46. package/src/policy/compaction.ts +272 -16
  47. package/src/policy/context-window-catalog.ts +64 -0
  48. package/src/policy/context-window.ts +173 -0
  49. package/src/policy/context.ts +55 -3
  50. package/src/policy/pricing.ts +52 -0
  51. package/src/policy/ratelimit.ts +47 -18
  52. package/src/policy/usage.ts +15 -8
  53. package/src/policy/work-mode.ts +1 -1
  54. package/src/providers/guards.ts +61 -4
  55. package/src/providers/provision.ts +12 -3
  56. package/src/providers/router.ts +56 -23
  57. package/src/session/context-projection.ts +14 -0
  58. package/src/session/context-selector.ts +58 -20
  59. package/src/session/persistence.ts +1 -1
  60. package/src/task/model.ts +21 -70
  61. package/src/tools/task.ts +7 -0
  62. package/src/ui/footer.ts +131 -66
  63. package/src/ui/i18n/en.ts +0 -11
  64. package/src/ui/i18n/id.ts +0 -11
  65. package/src/ui/input/input.ts +2 -3
  66. package/src/ui/input/prompt-engine.ts +2 -5
  67. package/src/ui/screens/model-manager.ts +3 -10
  68. package/src/ui/screens/picker.ts +23 -40
  69. package/src/ui/screens/provider-manager.ts +12 -33
  70. package/src/ui/screens/wizard.ts +0 -1
  71. package/src/ui/tui/app.ts +10 -6
  72. package/src/ui/tui/transcript.ts +48 -8
  73. package/vendor/minicore/VENDOR.md +9 -5
  74. package/vendor/minicore/src/core/loop.ts +47 -12
  75. package/vendor/minicore/src/core/provider.ts +4 -0
  76. package/vendor/minicore/src/core/session.ts +14 -1
  77. package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +0 -489
  78. package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +0 -391
@@ -315,7 +315,7 @@ function selectionFreshness(
315
315
  *
316
316
  * Urutan strategi (audit §7):
317
317
  * 1. summary-plus-tail — ringkasan durable [0,B) + ekor [B, head] (bila aman)
318
- * 2. fallback-unknown — view kanonik penuh + label jujur (DIVERGED/UNKNOWN)
318
+ * 2. fallback-unknown — histori kanonik berlabel jujur bila muat
319
319
  * 3. full-history — histori kanonik penuh bila muat budget
320
320
  * 4. budget-tail — ekor kanonik terbaru yang muat budget
321
321
  */
@@ -359,36 +359,75 @@ export function selectContext(input: SelectContextInput): ContextSelection {
359
359
  const summaryText = input.projection.summaryText
360
360
  if (b > 0 && typeof summaryText === "string" && summaryText.length > 0) {
361
361
  const { frontier, messages: tail } = coverageOf(input, rows, b)
362
- const synthetic = syntheticSummaryMessage(summaryText, b)
363
- const msgs: Message[] = [synthetic, ...tail]
364
- const artifact: ContextOnlyArtifact = { role: "user", content: synthetic.content as string }
365
- return Object.freeze({
366
- sessionId: input.sessionId,
367
- threadId: input.threadId,
368
- frontier,
369
- messages: msgs,
370
- source: "projection" as ContextSource,
371
- coveredSeq: b,
372
- selectionBasis: "summary-plus-tail" as SelectionBasis,
373
- freshness: selectionFreshness(frontier, input.canonicalFrontier),
374
- budget: report(msgs),
375
- detail: `durable summary covers [0,${b}) + canonical tail [${b},${headSeq}]`,
376
- contextOnly: artifact,
377
- })
362
+ const makeProjectionSelection = (text: string, truncated: boolean): ContextSelection => {
363
+ const synthetic = syntheticSummaryMessage(text, b)
364
+ const msgs: Message[] = [synthetic, ...tail]
365
+ const artifact: ContextOnlyArtifact = { role: "user", content: synthetic.content as string }
366
+ return Object.freeze({
367
+ sessionId: input.sessionId,
368
+ threadId: input.threadId,
369
+ frontier,
370
+ messages: msgs,
371
+ source: "projection" as ContextSource,
372
+ coveredSeq: b,
373
+ selectionBasis: "summary-plus-tail" as SelectionBasis,
374
+ freshness: selectionFreshness(frontier, input.canonicalFrontier),
375
+ budget: report(msgs),
376
+ detail: truncated
377
+ ? `durable summary covers [0,${b}) + canonical tail [${b},${headSeq}]; summary tail truncated to fit budget`
378
+ : `durable summary covers [0,${b}) + canonical tail [${b},${headSeq}]`,
379
+ contextOnly: artifact,
380
+ })
381
+ }
382
+ const complete = makeProjectionSelection(summaryText, false)
383
+ if (complete.budget.fits) return complete
384
+
385
+ // Projection texts can grow independently of the model window. Keep the
386
+ // most recent portion of the old summary and preserve the canonical tail
387
+ // only when the resulting pair fits; otherwise continue to budget-tail.
388
+ const marker = "[older projection prefix omitted for context budget]\n"
389
+ const tailTokens = sumTokens(tail, est)
390
+ if (tailTokens < limit) {
391
+ let low = 0
392
+ let high = summaryText.length
393
+ let best: ContextSelection | undefined
394
+ while (low <= high) {
395
+ const keep = Math.floor((low + high) / 2)
396
+ let suffix = summaryText.slice(summaryText.length - keep)
397
+ if (suffix.length > 0) {
398
+ const code = suffix.charCodeAt(0)
399
+ if (code >= 0xdc00 && code <= 0xdfff) suffix = suffix.slice(1)
400
+ }
401
+ const text = `${marker}${suffix}`
402
+ const candidate = makeProjectionSelection(text, true)
403
+ if (candidate.budget.fits) {
404
+ best = candidate
405
+ low = keep + 1
406
+ } else {
407
+ high = keep - 1
408
+ }
409
+ }
410
+ if (best) return best
411
+ }
378
412
  }
379
413
  // batas tak aman / ringkasan kosong → lanjut sebagai histori kanonik penuh.
380
414
  }
381
415
 
382
416
  const full = coverageOf(input, rows, 0)
383
417
  const fullFreshness = selectionFreshness(full.frontier, input.canonicalFrontier)
418
+ const fullTokens = sumTokens(full.messages, est)
384
419
 
385
420
  // ── Strategi 2: fallback-unknown (STALE/DIVERGED/UNKNOWN) ──────────────────
386
421
  // N3: baris BASI (view di belakang kanonis) TIDAK boleh dilabeli
387
422
  // "full-history" — label itu menyiratkan representasi kanonik yang trusted,
388
423
  // padahal view ini tak memutakhirkan diri ke head kanonis. Pakai
389
- // `fallback-unknown` (state yang sudah ada; bukan basis kelima yang baru).
424
+ // `fallback-unknown` bila histori penuh muat; bila tidak, teruskan ke
425
+ // budget-tail dengan status freshness tetap dihitung dari frontier terpilih.
390
426
  // Coverage completeness (semua baris tersedia diikutkan) ≠ freshness/trust.
391
- if (fullFreshness === "unknown" || fullFreshness === "diverged" || fullFreshness === "stale") {
427
+ if (
428
+ (fullFreshness === "unknown" || fullFreshness === "diverged" || fullFreshness === "stale") &&
429
+ fullTokens <= limit
430
+ ) {
392
431
  return Object.freeze({
393
432
  sessionId: input.sessionId,
394
433
  threadId: input.threadId,
@@ -404,7 +443,6 @@ export function selectContext(input: SelectContextInput): ContextSelection {
404
443
  }
405
444
 
406
445
  // ── Strategi 3: full-history (muat budget) ─────────────────────────────────
407
- const fullTokens = sumTokens(full.messages, est)
408
446
  if (fullTokens <= limit) {
409
447
  return Object.freeze({
410
448
  sessionId: input.sessionId,
@@ -217,7 +217,7 @@ function open(cwd?: string, local = false): Database {
217
217
  db.exec("ALTER TABLE sessions ADD COLUMN parent_run_id TEXT NULL")
218
218
  }
219
219
  // P0.2 (Q5): persistensi WorkMode di metadata sesi lintas `--resume`.
220
- // NULL = sesi legacy pra-P0.2 (resume fallback ke default EXECUTE).
220
+ // NULL = sesi legacy tanpa WorkMode tersimpan (resume fallback DISCUSS).
221
221
  if (!cols.some((c) => c.name === "work_mode")) {
222
222
  db.exec("ALTER TABLE sessions ADD COLUMN work_mode TEXT NULL")
223
223
  }
package/src/task/model.ts CHANGED
@@ -1,46 +1,14 @@
1
- // Task model types — the *domain* half of Phase 1.
2
- //
3
- // EVIDENCE NOTE. This file did NOT survive the wipe: there is no
4
- // `model.orig.ts` artifact and no `src/task/` in the recovered baseline. It is
5
- // reconstructed from the only two surviving sources of truth about it:
6
- //
7
- // 1. `store.orig.ts` — the actual pre-wipe implementation. Every field below
8
- // is pinned by `TaskRow` + `rowToTask()` + the construction sites in
9
- // `synchronizeTasks()`. Where the artifact *uses* a field, that field is
10
- // PROVEN, not guessed.
11
- // 2. `docs/TASK_IDENTITY_SPEC.md` + `docs/TASK_STATE_MACHINE_SPEC.md` —
12
- // in-repo design docs committed at baseline HEAD (`aa76dfb`).
13
- //
14
- // The two sources DISAGREE, and the disagreement is recorded rather than
15
- // smoothed over:
16
- //
17
- // | aspect | design doc | store.orig.ts (ACTUAL) |
18
- // |---------------|-------------------------------|------------------------|
19
- // | status casing | lowercase ("pending") | UPPERCASE ("PENDING") |
20
- // | blocker | `blocker: TaskBlocker` object | `blockedReason: string`|
21
- // | timestamps | `createdAt: number` | `createdAt: string` ISO|
22
- // | verification | `at: number` | `checkedAt: string` |
23
- // | provenance | `{source, actor, at}` | `{origin, source}` |
24
- // | titleKey | present | ABSENT |
25
- // | revision | ABSENT | present |
26
- //
27
- // The artifact wins. It is later evidence and it is the code that actually
28
- // ran. The doc is DESIGN-mode and predates the implementation.
29
- //
30
- // Every inference below is tagged `[INFERRED]`. Everything untagged is proven
31
- // by `store.orig.ts`.
1
+ // Domain types shared by TaskStore, TaskGraph, and scheduler code. Runtime
2
+ // invariants live in the current validators and persistence implementation.
32
3
 
33
4
  /**
34
5
  * Task lifecycle states.
35
6
  *
36
- * PROVEN by artifact usage: `PENDING` (the `rowToTask` fallback), `BLOCKED`
37
- * (the only status compared in `validate()`), `CANCELLED` (named in the
38
- * `deleteTask` comment as the sanctioned alternative to deletion).
7
+ * These values are persisted and validated by the task store. Producers may
8
+ * support only a subset of the declared lifecycle.
39
9
  *
40
- * [INFERRED] the remaining five, from `docs/TASK_STATE_MACHINE_SPEC.md` which
41
- * states the enum is "diperluas dari 5 ke 8" and lists them lowercase. Uppercased
42
- * to match the artifact's casing convention. None is ever written by the store
43
- * itself; they only widen what `isTaskStatus` accepts.
10
+ * The union includes lifecycle states accepted by the task domain. A type
11
+ * member alone does not imply that each producer currently emits that state.
44
12
  */
45
13
  export type TaskStatus =
46
14
  | "PENDING"
@@ -63,7 +31,7 @@ const TASK_STATUSES: readonly TaskStatus[] = [
63
31
  "CANCELLED",
64
32
  ]
65
33
 
66
- /** PROVEN: `rowToTask` calls this to decide whether a stored status is valid. */
34
+ /** Check whether a persisted status belongs to the task domain. */
67
35
  export function isTaskStatus(value: unknown): value is TaskStatus {
68
36
  return typeof value === "string" && TASK_STATUSES.includes(value as TaskStatus)
69
37
  }
@@ -180,33 +148,25 @@ export function isLegalTaskTransition(from: TaskStatus, to: TaskStatus): boolean
180
148
  * its running max at `0` and returns `taskIdFromIndex(max)`, so for an EMPTY
181
149
  * session (max = 0) the very first id must be `t1` — therefore the index is
182
150
  * 1-based and the mapping is `n -> t(n+1)`. This also reproduces the
183
- * artifact's own worked example: `t1,t2,t5` -> max 5 -> `t6`, not `t3`.
151
+ * store example: `t1,t2,t5` -> max 5 -> `t6`, not `t3`.
184
152
  */
185
153
  export function taskIdFromIndex(index: number): string {
186
154
  return `t${index + 1}`
187
155
  }
188
156
 
189
157
  /**
190
- * [INFERRED] Strict guard for a canonical id. `docs/TASK_IDENTITY_SPEC.md` fixes
191
- * the form as `t<n>` starting at 1, so `t0`, `t01` and `t-1` are all rejected.
192
- * `store.orig.ts` relies on this to reject model-supplied ids before they can
193
- * reach SQL, and `nextId()` re-parses with `Number(id.slice(1))`, which only
194
- * round-trips cleanly for `^t[1-9][0-9]*$`.
158
+ * Canonical task IDs use a positive, unpadded session-local integer. Reject
159
+ * values that cannot round-trip through the store's next-ID calculation.
195
160
  */
196
161
  const TASK_ID_RE = /^t[1-9][0-9]*$/
197
162
 
198
- /** PROVEN: guard used by `getTask`, `patchTask`, `deleteTask`. */
163
+ /** Guard canonical IDs at task-store entry points. */
199
164
  export function isTaskId(value: unknown): value is string {
200
165
  return typeof value === "string" && TASK_ID_RE.test(value)
201
166
  }
202
167
 
203
168
  /**
204
- * Verification record attached to a task.
205
- *
206
- * PROVEN from the artifact's only construction site
207
- * (`synchronizeTasks`): `{ verdict, detail?, checkedAt }` where `checkedAt` is
208
- * an ISO string from `nowIso()`. Note the field is `checkedAt`, NOT the
209
- * `at: number` the design doc proposed — artifact wins.
169
+ * Verification record persisted with a task. `checkedAt` is an ISO timestamp.
210
170
  */
211
171
  export interface TaskVerification {
212
172
  verdict: "passed" | "failed" | "unverified"
@@ -219,12 +179,8 @@ export type TaskEvidenceKind = "completion" | "receipt" | "test" | "verify" | "c
219
179
  /**
220
180
  * Evidence record appended on every synchronization.
221
181
  *
222
- * PROVEN from the artifact's construction site: `{ kind: "completion", detail,
223
- * at }` with `at` an ISO string.
224
- *
225
- * [INFERRED] the wider kind union, from `docs/TASK_STATE_MACHINE_SPEC.md`
226
- * (`EvidenceKind`). The store only ever writes `"completion"`; the rest exist so
227
- * a later phase can name evidence without another migration.
182
+ * Evidence kinds describe the source of a task completion claim or related
183
+ * verification record.
228
184
  */
229
185
  export interface TaskEvidence {
230
186
  kind: TaskEvidenceKind
@@ -235,18 +191,15 @@ export interface TaskEvidence {
235
191
  /**
236
192
  * [INFERRED] Acceptance criteria.
237
193
  *
238
- * UNRECOVERABLE SHAPE: the artifact stores and returns this value but never
239
- * reads a field from it and never constructs a non-null one, so its real shape
240
- * is unrecoverable. Modelled as an opaque record — the store round-trips it
241
- * verbatim via JSON and deliberately interprets nothing. Guessing concrete
242
- * fields here would be pure invention with no behavioural consequence.
194
+ * The store round-trips this opaque JSON value and does not interpret its
195
+ * fields. Keep the shape open until a concrete consumer is introduced.
243
196
  */
244
197
  export type TaskAcceptance = Record<string, unknown>
245
198
 
246
199
  /**
247
200
  * Where a task came from.
248
201
  *
249
- * PROVEN from the artifact: the `rowToTask` default is
202
+ * The `rowToTask` default is
250
203
  * `{ origin: "runtime", source: "unknown" }` and `synchronizeTasks` writes
251
204
  * `{ origin: "model", source: "todo_write" }`. So `origin` is a closed
252
205
  * two-value union and `source` is an open string.
@@ -259,11 +212,9 @@ export interface TaskProvenance {
259
212
  /**
260
213
  * One durable task row.
261
214
  *
262
- * PROVEN field-for-field by `rowToTask()`, which is the authoritative
215
+ * Projected field-for-field by `rowToTask()`, which is the authoritative
263
216
  * projection: the DB column set and this object are in 1:1 correspondence.
264
- * `sessionId` and `revision` do not appear in the design doc at all — they
265
- * exist only in the artifact, and `revision` is the stale-write substrate
266
- * Phase 1 must preserve.
217
+ * `revision` is the stale-write substrate and must be preserved.
267
218
  */
268
219
  export interface Task {
269
220
  /** Stable, canonical `t<n>`, allocated by the store. Never reused. */
@@ -288,13 +239,13 @@ export interface Task {
288
239
  revision: number
289
240
  }
290
241
 
291
- /** PROVEN: `getSnapshot()` returns exactly this. */
242
+ /** Snapshot returned by `getSnapshot()`. */
292
243
  export interface TaskSnapshot {
293
244
  sessionId: string
294
245
  tasks: Task[]
295
246
  }
296
247
 
297
- /** Error codes the artifact actually raises, plus nothing invented. */
248
+ /** Error codes emitted by the task store. */
298
249
  export type TaskErrorCode =
299
250
  | "TASK_DB_INIT_FAILURE"
300
251
  | "TASK_INVALID_ID"
package/src/tools/task.ts CHANGED
@@ -7,6 +7,7 @@ import { loadConfig } from "../config.ts"
7
7
  import { LIMITS } from "../constants.ts"
8
8
  import { resolveLocalDbPath } from "../lib/db-path.ts"
9
9
  import { evaluateConsequence, isAceEnabled } from "../policy/consequence-engine.ts"
10
+ import { resolveContextWindow } from "../policy/context-window.ts"
10
11
  import type { NoProgressOptions } from "../policy/no-progress.ts"
11
12
  import type { RateLimiter } from "../policy/ratelimit.ts"
12
13
  import type { WorkMode } from "../policy/work-mode.ts"
@@ -151,6 +152,7 @@ export function clearSubAgentSessionFactory(): void {
151
152
  export interface SubAgentParentRouting {
152
153
  rateLimiter?: RateLimiter
153
154
  defaultProviderId?: string
155
+ contextWindowTokensForModel?: (model?: string) => number
154
156
  }
155
157
 
156
158
  let parentRouting: SubAgentParentRouting = {}
@@ -201,6 +203,9 @@ export function setSubAgentParentRouting(c: SubAgentParentRouting): void {
201
203
  parentRouting = {
202
204
  ...(c.rateLimiter ? { rateLimiter: c.rateLimiter } : {}),
203
205
  ...(c.defaultProviderId ? { defaultProviderId: c.defaultProviderId } : {}),
206
+ ...(c.contextWindowTokensForModel
207
+ ? { contextWindowTokensForModel: c.contextWindowTokensForModel }
208
+ : {}),
204
209
  }
205
210
  }
206
211
 
@@ -224,6 +229,8 @@ async function getProvider(overrides: SubAgentParentRouting = parentRouting) {
224
229
  if (providers.length === 0) throw new Error("no provider for sub-agent")
225
230
  return createRouterProvider({
226
231
  providers,
232
+ contextWindowTokensForModel:
233
+ overrides.contextWindowTokensForModel ?? ((model) => resolveContextWindow(cfg, model).tokens),
227
234
  ...(overrides.rateLimiter ? { limiter: overrides.rateLimiter } : {}),
228
235
  ...(overrides.defaultProviderId ? { defaultProviderId: overrides.defaultProviderId } : {}),
229
236
  })
package/src/ui/footer.ts CHANGED
@@ -5,26 +5,18 @@
5
5
  // jadi render tetap deterministik dan bisa diuji tanpa menunggu waktu.
6
6
  //
7
7
  // Gaya (keputusan produk): footer hampir tak terlihat; field dipisahkan
8
- // dengan spasi dan warna, tanpa bullet separator. Mode memakai mapping warna
9
- // yang sama dengan prompt lama: plan kuning, ask biru, sisanya hijau.
10
- //
11
- // Tata letak: `✦ 00.00.00 mode model cwd ……… 14.2k` — konteks rata kanan.
12
- // Mode di-pad ke lebar tetap agar teks di kanannya TIDAK bergeser saat mode
13
- // berganti (Shift+Tab): tanpa padding, `auto`→`allowlist` menggeser seluruh baris.
8
+ // dengan spasi dan warna, tanpa bullet separator. Work Mode ada di kiri;
9
+ // Permission Mode berwarna cyan di sisi kanan, dekat penggunaan konteks.
14
10
  import { sanitizeAnsiLine } from "./render/sanitize.ts"
15
11
  import { c, glyphs } from "./render/theme.ts"
16
- import { displayWidth, padToWidth, truncateToWidth } from "./render/width.ts"
12
+ import { displayWidth, truncateToWidth } from "./render/width.ts"
17
13
 
18
14
  export type TimerHighlight = "seconds" | "minutes" | "hours"
19
15
 
20
16
  export interface FooterStatus {
17
+ /** Permission mode efektif sesi ini (umumnya AUTO atau ASK). */
21
18
  mode: string
22
- /**
23
- * P12 S2.2 Slice 5 — WorkMode aktif sesi (DISCUSS|PLAN|EXECUTE). Hanya
24
- * ditampilkan bila bukan EXECUTE: label jadi `<WorkMode>·<permission mode>`
25
- * (mis. `PLAN·auto`, `DISCUSS·auto`) agar dua lapis intent/permission bisa
26
- * dibedakan. EXECUTE (default) = perilaku lama, label permission mode saja.
27
- */
19
+ /** WorkMode aktif sesi; identitas internal EXECUTE ditampilkan sebagai Build. */
28
20
  workMode?: string
29
21
  model: string
30
22
  cwd: string
@@ -48,8 +40,10 @@ export interface FooterStatus {
48
40
  timerHighlight?: TimerHighlight
49
41
  }
50
42
 
51
- /** Lebar tetap kolom mode — muat label terpanjang "DISCUSS · AUTO". */
52
- const MODE_WIDTH = 14
43
+ /** Lebar tetap kolom agar perubahan WorkMode tidak menggeser model/CWD. */
44
+ const WORK_MODE_WIDTH = 18
45
+ const WORK_MODE_COMPACT_WIDTH = 13
46
+ const WORK_MODE_VALUE_WIDTH = 7
53
47
 
54
48
  /** Buang prefix provider (`acme::deepseek-v4` → `deepseek-v4`). */
55
49
  export function shortModel(id: string): string {
@@ -57,30 +51,50 @@ export function shortModel(id: string): string {
57
51
  return i >= 0 ? id.slice(i + 2) : id
58
52
  }
59
53
 
60
- /** Label permission (AUTO/ASK) — legacy profile warisan di-uppercase saja. */
61
- function permissionLabel(mode: string): string {
62
- return (mode || "").toUpperCase()
54
+ function titleCaseMode(value: string, fallback: string): string {
55
+ const clean = sanitizeAnsiLine(value).trim()
56
+ if (!clean) return fallback
57
+ return clean
58
+ .toLowerCase()
59
+ .replace(/(^|[\s_-])([a-z])/g, (_match, sep: string, letter: string) => {
60
+ return `${sep}${letter.toUpperCase()}`
61
+ })
63
62
  }
64
63
 
65
- /**
66
- * Warna + PAD token mode. Padding dilakukan sebelum pewarnaan supaya lebar
67
- * kolom mode tetap sama untuk semua mode (anti-geser), sementara warna tetap
68
- * dipilih dari nama mode asli.
69
- *
70
- * [mode-architecture] Selalu tampilkan KEDUA lapis sebagai `<WorkMode> ·
71
- * <PermissionMode>` (mis. `BUILD · AUTO`, `PLAN · ASK`). Identitas internal
72
- * `EXECUTE` ditampilkan sebagai produk `BUILD`. EXECUTE/default tak lagi
73
- * disembunyikan. Warna mengikuti lapis yang lebih ketat: DISCUSS/PLAN warning,
74
- * ASK info, AUTO success.
75
- */
76
- export function paintFooterMode(mode: string, workMode?: string): string {
77
- const wm = !workMode || workMode === "EXECUTE" ? "BUILD" : workMode.toUpperCase()
78
- const pm = permissionLabel(mode)
79
- const restrictive = wm === "DISCUSS" || wm === "PLAN"
80
- const label = `${wm} · ${pm}`
81
- const padded = padToWidth(sanitizeAnsiLine(label), MODE_WIDTH)
82
- if (restrictive) return c.warning(padded)
83
- return pm === "ASK" ? c.info(padded) : c.success(padded)
64
+ function workModeValue(workMode?: string): string {
65
+ const normalized = (workMode || "DISCUSS").toUpperCase()
66
+ if (normalized === "EXECUTE" || normalized === "BUILD") return "Build"
67
+ if (normalized === "DISCUSS") return "Discuss"
68
+ if (normalized === "PLAN") return "Plan"
69
+ return titleCaseMode(workMode ?? "", "Build")
70
+ }
71
+
72
+ type ModeLabelStyle = "full" | "compact" | "value"
73
+
74
+ /** Work Mode memakai warna semantik; label/nilai memakai title case. */
75
+ export function paintWorkMode(workMode?: string, style: ModeLabelStyle = "full"): string {
76
+ const value = workModeValue(workMode)
77
+ const normalized = sanitizeAnsiLine(workMode || "DISCUSS").toUpperCase()
78
+ const prefix = style === "full" ? "Work Mode: " : style === "compact" ? "Work: " : ""
79
+ const width =
80
+ style === "full"
81
+ ? WORK_MODE_WIDTH
82
+ : style === "compact"
83
+ ? WORK_MODE_COMPACT_WIDTH
84
+ : WORK_MODE_VALUE_WIDTH
85
+ const labelWidth = displayWidth(sanitizeAnsiLine(`${prefix}${value}`))
86
+ const colorValue = normalized === "DISCUSS" || normalized === "PLAN" ? c.warning : c.success
87
+ return `${prefix ? c.gray(prefix) : ""}${colorValue(value)}${" ".repeat(
88
+ Math.max(0, width - labelWidth),
89
+ )}`
90
+ }
91
+
92
+ /** Permission Mode selalu cyan agar terpisah secara visual dari Work Mode. */
93
+ export function paintPermissionMode(mode: string, style: ModeLabelStyle = "full"): string {
94
+ const value = titleCaseMode(mode, "Auto")
95
+ if (style === "value") return c.info(value)
96
+ const prefix = style === "full" ? "Permission Mode: " : "Permission: "
97
+ return `${c.gray(prefix)}${c.info(value)}`
84
98
  }
85
99
 
86
100
  /** Spark glyph: redup saat idle, pulse putih↔abu saat busy (frame genap/ganjil). */
@@ -131,7 +145,6 @@ export function renderFooter(s: FooterStatus, columns: number): string[] {
131
145
  ? `${paintTimer(timerText, s.timerActive === true, s.timerHighlight)} `
132
146
  : ""
133
147
  const lead = `${spark} ${timer}`
134
- const mode = paintFooterMode(s.mode, s.workMode)
135
148
  const fieldGap = " "
136
149
  // Satu-baris: cwd/model bisa berisi newline (nama dir) — sanitizeAnsiLine
137
150
  // agar \n tak memecah frame lengket ke scrollback (displayWidth menghitung
@@ -139,38 +152,90 @@ export function renderFooter(s: FooterStatus, columns: number): string[] {
139
152
  const model = c.gray(sanitizeAnsiLine(shortModel(s.model)))
140
153
  const cwdTxt = c.muted(sanitizeAnsiLine(s.cwd))
141
154
  const shortCwdTxt = c.muted(sanitizeAnsiLine(shortenPath(s.cwd)))
142
-
143
- const full = `${lead}${mode}${fieldGap}${model}${fieldGap}${cwdTxt}`
144
- const shortened = `${lead}${mode}${fieldGap}${model}${fieldGap}${shortCwdTxt}`
145
- const mid = `${lead}${mode}${fieldGap}${model}`
146
- const lean = `${lead}${mode}`
147
-
148
155
  const target = Math.max(4, cols - 1)
149
156
  const ctx = s.context ? sanitizeAnsiLine(s.context) : ""
150
157
  const metrics = s.metrics ? sanitizeAnsiLine(s.metrics) : ""
151
- // F-CTX-1: metrik usage menempel di kiri blok konteks (satu blok rata kanan).
152
- const rightTxt = [ctx, metrics].filter(Boolean).join(" ")
153
- const rightW = displayWidth(rightTxt)
154
-
155
- // Rata kanan: konteks didorong ke kolom `target` dengan gap ideal ≥6
156
- // agar rapi dan tidak mepet (keluhan: terlalu rapat → 1→2→4→6).
157
- // Bila tak muat, konteks diprioritaskan — kiri dipotong duluan lewat
158
- // tangga di bawah, bukan konteks yang dilepas.
159
- const align = (left: string): string => {
160
- const lw = displayWidth(left)
161
- if (!rightTxt) return left
162
- if (lw + rightW + 2 > target) return left
163
- const gap = Math.max(6, target - lw - rightW)
164
- return `${left}${" ".repeat(gap)}${c.gray(rightTxt)}`
158
+ const contextParts = [ctx, metrics].filter(Boolean).map((part) => c.gray(part))
159
+ const leftWithCwdFor = (style: ModeLabelStyle): string[] => {
160
+ const work = paintWorkMode(s.workMode, style)
161
+ return [
162
+ `${lead}${work}${fieldGap}${model}${fieldGap}${cwdTxt}`,
163
+ ...(shortCwdTxt !== cwdTxt
164
+ ? [`${lead}${work}${fieldGap}${model}${fieldGap}${shortCwdTxt}`]
165
+ : []),
166
+ ]
167
+ }
168
+ const leftWithoutCwdFor = (style: ModeLabelStyle): string[] => {
169
+ const work = paintWorkMode(s.workMode, style)
170
+ return [`${lead}${work}${fieldGap}${model}`]
171
+ }
172
+ const leftModeOnlyFor = (style: ModeLabelStyle): string => {
173
+ return `${lead}${paintWorkMode(s.workMode, style)}`
174
+ }
175
+ const rightFor = (style: ModeLabelStyle): string =>
176
+ [...contextParts, paintPermissionMode(s.mode, style)].join(fieldGap)
177
+ const align = (left: string, right: string): string | undefined => {
178
+ const leftWidth = displayWidth(left)
179
+ const rightWidth = displayWidth(right)
180
+ const gapWidth = target - leftWidth - rightWidth
181
+ if (gapWidth < 1) return undefined
182
+ return `${left}${" ".repeat(gapWidth)}${right}`
183
+ }
184
+
185
+ // Pertahankan label penuh selama muat; jika tidak, padatkan kedua label
186
+ // bersama-sama sebelum menghilangkan konteks atau memotong salah satu mode.
187
+ const labelPairGroups: ReadonlyArray<ReadonlyArray<readonly [ModeLabelStyle, ModeLabelStyle]>> = [
188
+ [
189
+ ["full", "full"],
190
+ ["compact", "compact"],
191
+ ],
192
+ [["value", "value"]],
193
+ [
194
+ ["full", "compact"],
195
+ ["compact", "full"],
196
+ ],
197
+ [
198
+ ["compact", "value"],
199
+ ["value", "compact"],
200
+ ],
201
+ [
202
+ ["full", "value"],
203
+ ["value", "full"],
204
+ ],
205
+ ]
206
+ for (const pairGroup of labelPairGroups) {
207
+ for (const leftCandidates of [leftWithCwdFor, leftWithoutCwdFor]) {
208
+ for (const [workStyle, permissionStyle] of pairGroup) {
209
+ for (const left of leftCandidates(workStyle)) {
210
+ const line = align(left, rightFor(permissionStyle))
211
+ if (line && displayWidth(line) <= target) return [line]
212
+ }
213
+ }
214
+ }
215
+ }
216
+ for (const pairGroup of labelPairGroups) {
217
+ for (const [workStyle, permissionStyle] of pairGroup) {
218
+ const line = align(leftModeOnlyFor(workStyle), rightFor(permissionStyle))
219
+ if (line && displayWidth(line) <= target) return [line]
220
+ }
165
221
  }
166
222
 
167
- // Tangga prioritas buang saat sempit: cwd penuh → cwd diperpendek → model
168
- // (spark + timer + mode + context tetap punya ruang).
169
- const candidates = shortCwdTxt !== cwdTxt ? [full, shortened, mid, lean] : [full, mid, lean]
170
- for (const left of candidates) {
171
- const line = align(left)
172
- if (displayWidth(line) <= target) return [line]
223
+ // Terminal sangat sempit: pertahankan spark dan dua nilai mode, hilangkan
224
+ // timer/model/CWD/label sebelum konteks; potong konteks lebih dahulu.
225
+ const workValue = paintWorkMode(s.workMode, "value")
226
+ const permissionValue = paintPermissionMode(s.mode, "value")
227
+ const shortWorkValue = workValue.trimEnd()
228
+ const modeOnly = `${spark} ${shortWorkValue} ${permissionValue}`
229
+ if (ctx || metrics) {
230
+ const context = [ctx, metrics].filter(Boolean).join(" ")
231
+ const baseWidth = displayWidth(modeOnly)
232
+ const contextBudget = target - baseWidth - 2
233
+ if (contextBudget > 0) {
234
+ const shortenedContext = truncateToWidth(context, contextBudget, "…")
235
+ const withContext = `${spark} ${shortWorkValue} ${c.gray(shortenedContext)} ${permissionValue}`
236
+ if (displayWidth(withContext) <= target) return [withContext]
237
+ }
173
238
  }
174
- // Bahkan `lean` tak muat (terminal sangat sempit): potong keras.
175
- return [truncateToWidth(align(lean), target, "…")]
239
+ if (displayWidth(modeOnly) <= target) return [modeOnly]
240
+ return [truncateToWidth(modeOnly, target, "…")]
176
241
  }
package/src/ui/i18n/en.ts CHANGED
@@ -3,8 +3,6 @@
3
3
  // Nilai memakai interpolasi `{nama}` sederhana (lihat t()).
4
4
  export const en = {
5
5
  "app.placeholder": "ask anything, / for commands… (Ctrl+D exits)",
6
- "app.menuHeader": "─ commands ─",
7
- "app.moreLines": " … {n} more",
8
6
  "app.newBelow": "↓ {n} new lines below · PgDn to bottom",
9
7
  "app.abortHint": "abort sent — press Esc again to quit",
10
8
  "app.working": "Working",
@@ -63,17 +61,11 @@ export const en = {
63
61
  "verb.delete": "delete",
64
62
  "verb.edit": "edit",
65
63
  "verb.close": "close",
66
- "pick.filter": "Filter:",
67
- "pick.placeholder": "type to filter",
68
64
  "pick.noMatch": 'No matches for "{q}"',
69
- "pick.matches": "{n}/{total} matches",
70
- "pick.hint": "↑↓:{select} · Enter:{confirm} · Esc:{back}",
71
65
  "pick.fail": "picker failed: {msg}",
72
66
  "pick.failOpen": "picker failed to open: {msg}",
73
67
  "model.empty": "No models configured",
74
68
  "model.noMatch": "No models match",
75
- "model.title": "Models",
76
- "model.typeFilter": "type to filter",
77
69
  "model.deleteTitle": "Delete model",
78
70
  "model.deleteFooter": "←/→/y/n select · Enter delete · Esc cancel",
79
71
  "model.delActive": 'Delete ACTIVE model "{id}"?',
@@ -81,9 +73,7 @@ export const en = {
81
73
  "model.failOpen": "model manager failed to open: {msg}",
82
74
  "effort.title": "Thinking effort",
83
75
  "effort.saved": "Thinking: {effort} (next session)",
84
- "prov.title": "Providers",
85
76
  "prov.empty": "No providers",
86
- "prov.hint": "Enter:{select} · a:{add} · d:{delete} · e:{edit} · Esc:{close}",
87
77
  "prov.addTitle": "Add provider",
88
78
  "prov.customUrl": "Custom URL",
89
79
  "prov.editTitle": 'Edit "{id}"',
@@ -98,7 +88,6 @@ export const en = {
98
88
  "prov.deleteAsk": " — delete?",
99
89
  "prov.deleteFooter": "←/→/y/n select · Enter delete · Esc cancel",
100
90
  "prov.failOpen": "provider manager failed to open: {msg}",
101
- "prov.models": "{n} models",
102
91
  "prov.reloadFail": "provider reload failed — restart to apply changes",
103
92
  "prov.detectFail": "Model detection failed: {msg}",
104
93
  "prov.updateFail": "Update failed: {msg}",