minicode-ai 0.14.2 → 0.14.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -178
- package/cli/args.ts +10 -18
- package/cli/commands/acp.ts +20 -27
- package/cli/commands/daemon.ts +6 -7
- package/cli/commands/exec.ts +12 -10
- package/cli/commands.ts +6 -9
- package/cli/index.ts +30 -15
- package/cli/provider-manager.ts +1 -3
- package/cli/setup.ts +167 -143
- package/cli/tui.ts +15 -23
- package/docs/CONTROL-PLANE-MAP.md +145 -0
- package/docs/OUTPUT_EVENT_MODEL.md +1 -1
- package/docs/OUTPUT_PROTOCOL_SPEC.md +2 -2
- package/docs/OUTPUT_RENDERING_SPEC.md +7 -2
- package/docs/OUTPUT_UX_RULES.md +1 -1
- package/docs/README.md +14 -102
- package/docs/SUMMARY.md +53 -0
- package/docs/TERMINAL_CONTRACT.md +84 -51
- package/docs/UI_RENDER_PIPELINE.md +204 -0
- package/docs/agents.md +5 -5
- package/docs/architecture.md +23 -12
- package/docs/choosing-mode.md +7 -7
- package/docs/cli.md +22 -29
- package/docs/concepts.md +1 -1
- package/docs/config.md +10 -5
- package/docs/contributing.md +6 -6
- package/docs/environment.md +3 -1
- package/docs/exec.md +5 -5
- package/docs/glossary.md +8 -6
- package/docs/memory-sessions.md +7 -5
- package/docs/policy-sandbox.md +16 -14
- package/docs/quickstart.md +2 -2
- package/docs/repl.md +4 -3
- package/docs/security-model.md +14 -15
- package/docs/security.md +8 -29
- package/docs/skills.md +1 -1
- package/docs/tools.md +2 -2
- package/package.json +5 -3
- package/scripts/vendor-overlays/minicode-context.patch +109 -0
- package/src/app/provider-layer.ts +13 -1
- package/src/app/session.ts +216 -13
- package/src/config.ts +30 -3
- package/src/constants.ts +2 -0
- package/src/daemon/control.ts +1 -1
- package/src/mcp/server.ts +2 -3
- package/src/policy/compaction.ts +272 -16
- package/src/policy/context-window.ts +73 -0
- package/src/policy/context.ts +55 -3
- package/src/policy/ratelimit.ts +47 -18
- package/src/policy/usage.ts +15 -8
- package/src/policy/work-mode.ts +1 -1
- package/src/providers/guards.ts +61 -4
- package/src/providers/provision.ts +12 -3
- package/src/providers/router.ts +56 -23
- package/src/session/context-projection.ts +14 -0
- package/src/session/context-selector.ts +58 -20
- package/src/session/persistence.ts +1 -1
- package/src/task/model.ts +21 -70
- package/src/tools/task.ts +7 -0
- package/src/ui/footer.ts +131 -66
- package/src/ui/i18n/en.ts +0 -11
- package/src/ui/i18n/id.ts +0 -11
- package/src/ui/input/input.ts +2 -3
- package/src/ui/input/prompt-engine.ts +2 -5
- package/src/ui/screens/model-manager.ts +3 -10
- package/src/ui/screens/picker.ts +23 -40
- package/src/ui/screens/provider-manager.ts +12 -33
- package/src/ui/screens/wizard.ts +0 -1
- package/src/ui/tui/app.ts +10 -6
- package/src/ui/tui/transcript.ts +48 -8
- package/vendor/minicore/VENDOR.md +9 -5
- package/vendor/minicore/src/core/loop.ts +47 -12
- package/vendor/minicore/src/core/provider.ts +4 -0
- package/vendor/minicore/src/core/session.ts +14 -1
- package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +0 -489
- package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +0 -391
package/docs/tools.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Tools
|
|
1
|
+
# Tools
|
|
2
2
|
|
|
3
3
|
Referensi lengkap tool Minicode: filesystem, search, exec, git, web, memory, plan, agents, MCP, LSP.
|
|
4
4
|
|
|
@@ -90,7 +90,7 @@ Batas `BASH_BACKGROUND_MAX_JOBS`; semua job mati saat CLI keluar.
|
|
|
90
90
|
|
|
91
91
|
| Tool | Fungsi | Catatan |
|
|
92
92
|
|---|---|---|
|
|
93
|
-
| `delegate_task` | Sub-agen isolasi `explore`/`plan` | Pool 3,
|
|
93
|
+
| `delegate_task` | Sub-agen isolasi `explore`/`plan` | Pool 3, context/memory/signal/budget terpisah, abort-aware. Di ASK, TTY meminta persetujuan dan non-TTY menolak; AUTO berjalan tanpa prompt bila authorized. Parent PermissionMode `ASK`/`plan`/`readonly` memaksa `explore`; WorkMode `DISCUSS`/`PLAN` membatasi tool anak ke subset eksplorasi. Anak tidak mendapat MCP, commit, memory/todo writes, nesting, atau job background. Satu approval mencakup satu delegasi; turn gagal setelah anak committed → warning `[recovery]` |
|
|
94
94
|
|
|
95
95
|
## MCP
|
|
96
96
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "minicode-ai",
|
|
3
|
-
"version": "0.14.
|
|
3
|
+
"version": "0.14.4",
|
|
4
4
|
"description": "Coding agent CLI built on the frozen MiniCore runtime — tools, MCP, LSP, sandbox, shadow-git checkpoints",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"private": false,
|
|
@@ -48,20 +48,22 @@
|
|
|
48
48
|
"vendor/minicore/src",
|
|
49
49
|
"vendor/minicore/package.json",
|
|
50
50
|
"vendor/minicore/VENDOR.md",
|
|
51
|
+
"scripts/vendor-overlays/minicode-context.patch",
|
|
51
52
|
"README.md",
|
|
52
53
|
"LICENSE",
|
|
53
|
-
"docs/OUTPUT_ARCHITECTURE_AUDIT.md",
|
|
54
54
|
"docs/OUTPUT_EVENT_MODEL.md",
|
|
55
|
-
"docs/OUTPUT_IMPLEMENTATION_PLAN.md",
|
|
56
55
|
"docs/OUTPUT_PROTOCOL_SPEC.md",
|
|
57
56
|
"docs/OUTPUT_RENDERING_SPEC.md",
|
|
58
57
|
"docs/OUTPUT_UX_RULES.md",
|
|
58
|
+
"docs/SUMMARY.md",
|
|
59
59
|
"docs/TERMINAL_CONTRACT.md",
|
|
60
|
+
"docs/UI_RENDER_PIPELINE.md",
|
|
60
61
|
"docs/agents.md",
|
|
61
62
|
"docs/architecture.md",
|
|
62
63
|
"docs/choosing-mode.md",
|
|
63
64
|
"docs/cli.md",
|
|
64
65
|
"docs/concepts.md",
|
|
66
|
+
"docs/CONTROL-PLANE-MAP.md",
|
|
65
67
|
"docs/config-providers.md",
|
|
66
68
|
"docs/config.md",
|
|
67
69
|
"docs/contributing.md",
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
diff --git a/vendor/minicore/src/core/loop.ts b/vendor/minicore/src/core/loop.ts
|
|
2
|
+
index 11ea5eb..56e4f54 100644
|
|
3
|
+
--- a/vendor/minicore/src/core/loop.ts
|
|
4
|
+
+++ b/vendor/minicore/src/core/loop.ts
|
|
5
|
+
@@ -48,3 +48,6 @@ export async function executeTurn(
|
|
6
|
+
- // maxProviderRetries); the policy flag is set when a policy compaction
|
|
7
|
+
- // is attempted (once per turn, guarding against per-step O(n) repeats).
|
|
8
|
+
- let compactedForBudget = false;
|
|
9
|
+
+ // maxProviderRetries); policy compaction has a small per-turn hard cap,
|
|
10
|
+
+ // guarding against repeated no-progress work after tool output grows.
|
|
11
|
+
+ // Permit one follow-up policy compaction after tool results grow the current
|
|
12
|
+
+ // turn. The hard cap prevents a no-progress compactor from looping forever.
|
|
13
|
+
+ let budgetCompactions = 0;
|
|
14
|
+
+ const maxBudgetCompactions = 2;
|
|
15
|
+
@@ -52,0 +56,13 @@ export async function executeTurn(
|
|
16
|
+
+ // Resolve once for the turn: model switching is a between-turn operation,
|
|
17
|
+
+ // so budget admission and output accounting must use the same model window.
|
|
18
|
+
+ let contextWindowTokens = s.contextWindowTokens;
|
|
19
|
+
+ try {
|
|
20
|
+
+ const resolved = s.contextWindowTokensForModel?.(s.state.model);
|
|
21
|
+
+ if (typeof resolved === "number" && Number.isSafeInteger(resolved) && resolved > 0) {
|
|
22
|
+
+ contextWindowTokens = resolved;
|
|
23
|
+
+ }
|
|
24
|
+
+ } catch {
|
|
25
|
+
+ // Keep the validated numeric fallback; a metadata lookup must not bypass
|
|
26
|
+
+ // the kernel's context guard.
|
|
27
|
+
+ }
|
|
28
|
+
+
|
|
29
|
+
@@ -62 +78 @@ export async function executeTurn(
|
|
30
|
+
- limitTokens: s.contextWindowTokens,
|
|
31
|
+
+ limitTokens: contextWindowTokens,
|
|
32
|
+
@@ -64 +80,2 @@ export async function executeTurn(
|
|
33
|
+
- if (s.budget.shouldCompact(pressure) && !compactedForBudget) {
|
|
34
|
+
+ let reduced = false;
|
|
35
|
+
+ if (s.budget.shouldCompact(pressure) && budgetCompactions < maxBudgetCompactions) {
|
|
36
|
+
@@ -67 +84 @@ export async function executeTurn(
|
|
37
|
+
- compactedForBudget = true;
|
|
38
|
+
+ budgetCompactions++;
|
|
39
|
+
@@ -72 +89 @@ export async function executeTurn(
|
|
40
|
+
- const reduced = s.store.messages.length < before;
|
|
41
|
+
+ reduced = s.store.messages.length < before;
|
|
42
|
+
@@ -79 +96 @@ export async function executeTurn(
|
|
43
|
+
- limitTokens: s.contextWindowTokens,
|
|
44
|
+
+ limitTokens: contextWindowTokens,
|
|
45
|
+
@@ -82,2 +99,9 @@ export async function executeTurn(
|
|
46
|
+
- if (pressure === "critical" && compactedForBudget) {
|
|
47
|
+
- throw new AgentError("budget_exceeded", "context window exceeded after compaction");
|
|
48
|
+
+ if (s.budget.shouldCompact(pressure) && reduced && budgetCompactions < maxBudgetCompactions) {
|
|
49
|
+
+ continue;
|
|
50
|
+
+ }
|
|
51
|
+
+ if (pressure === "critical") {
|
|
52
|
+
+ const used = contextTokens(s);
|
|
53
|
+
+ throw new AgentError(
|
|
54
|
+
+ "budget_exceeded",
|
|
55
|
+
+ `context window exceeded after compaction (${used} > ${contextWindowTokens}); reduce the prompt, tool output, or fixed instructions, or select a model with a larger context window`,
|
|
56
|
+
+ );
|
|
57
|
+
@@ -179 +203,5 @@ export async function executeTurn(
|
|
58
|
+
- throw new AgentError("budget_exceeded", errorMessage ?? "context too large", { cause: providerError ?? action });
|
|
59
|
+
+ throw new AgentError(
|
|
60
|
+
+ "budget_exceeded",
|
|
61
|
+
+ `context window exceeded after recovery compaction: ${errorMessage ?? "context too large"}`,
|
|
62
|
+
+ { cause: providerError ?? action },
|
|
63
|
+
+ );
|
|
64
|
+
@@ -303,0 +332,3 @@ function toProviderError(error: unknown, signal: AbortSignal): ProviderError {
|
|
65
|
+
+ // Host-side admission guards (context budget, shutdown, etc.) preserve their
|
|
66
|
+
+ // deterministic AgentError identity instead of entering provider retry.
|
|
67
|
+
+ if (error instanceof AgentError) throw error;
|
|
68
|
+
@@ -336 +367,5 @@ function contextTokens(s: SessionInternal): number {
|
|
69
|
+
- return estimateSessionContext(s.store, s.system, s.registry.list(), s.estimator);
|
|
70
|
+
+ let system = s.system;
|
|
71
|
+
+ try {
|
|
72
|
+
+ system = s.systemForContext?.() ?? system;
|
|
73
|
+
+ } catch {}
|
|
74
|
+
+ return estimateSessionContext(s.store, system, s.registry.list(), s.estimator);
|
|
75
|
+
diff --git a/vendor/minicore/src/core/provider.ts b/vendor/minicore/src/core/provider.ts
|
|
76
|
+
index 489e244..63afbbc 100644
|
|
77
|
+
--- a/vendor/minicore/src/core/provider.ts
|
|
78
|
+
+++ b/vendor/minicore/src/core/provider.ts
|
|
79
|
+
@@ -37,0 +38,4 @@ export interface ModelProvider {
|
|
80
|
+
+ /** Optional host metadata for per-model admission budgets. */
|
|
81
|
+
+ contextWindowTokensForModel?(model?: string): number;
|
|
82
|
+
+ /** Canonical provider/model key for per-model estimator state. */
|
|
83
|
+
+ contextModelIdentity?(model?: string): string | undefined;
|
|
84
|
+
diff --git a/vendor/minicore/src/core/session.ts b/vendor/minicore/src/core/session.ts
|
|
85
|
+
index 6e183d7..df80273 100644
|
|
86
|
+
--- a/vendor/minicore/src/core/session.ts
|
|
87
|
+
+++ b/vendor/minicore/src/core/session.ts
|
|
88
|
+
@@ -37,0 +38,2 @@ export interface SessionConfig {
|
|
89
|
+
+ /** Dynamic system prompt for host-controlled per-turn mode hints. */
|
|
90
|
+
+ systemForContext?: () => string;
|
|
91
|
+
@@ -61,0 +64,3 @@ export interface SessionConfig {
|
|
92
|
+
+ /** Resolve a model-specific context limit for each run. Additive app seam;
|
|
93
|
+
+ * the numeric option remains the fallback for existing library callers. */
|
|
94
|
+
+ contextWindowTokensForModel?: (model?: string) => number;
|
|
95
|
+
@@ -140,0 +146 @@ export interface SessionInternal {
|
|
96
|
+
+ readonly systemForContext?: () => string;
|
|
97
|
+
@@ -149,0 +156 @@ export interface SessionInternal {
|
|
98
|
+
+ readonly contextWindowTokensForModel?: (model?: string) => number;
|
|
99
|
+
@@ -180,0 +188 @@ export function createSession(config: SessionConfig): Session {
|
|
100
|
+
+ systemForContext: config.systemForContext,
|
|
101
|
+
@@ -189,0 +198 @@ export function createSession(config: SessionConfig): Session {
|
|
102
|
+
+ contextWindowTokensForModel: config.contextWindowTokensForModel,
|
|
103
|
+
@@ -213 +222,5 @@ export function createSession(config: SessionConfig): Session {
|
|
104
|
+
- return estimateSessionContext(store, config.system, impl.registry.list(), impl.estimator);
|
|
105
|
+
+ let system = config.system
|
|
106
|
+
+ try {
|
|
107
|
+
+ system = config.systemForContext?.() ?? system
|
|
108
|
+
+ } catch {}
|
|
109
|
+
+ return estimateSessionContext(store, system, impl.registry.list(), impl.estimator);
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createOpenAICompatProvider } from "#minicore/providers/openai-compat.ts"
|
|
2
2
|
import { loadConfig, type MinicodeConfig } from "../config.ts"
|
|
3
|
+
import { resolveContextWindow } from "../policy/context-window.ts"
|
|
3
4
|
import type { RateLimiter } from "../policy/ratelimit.ts"
|
|
4
5
|
import { createAnthropicProvider } from "../providers/anthropic.ts"
|
|
5
6
|
import { buildProviderListAsync } from "../providers/build.ts"
|
|
@@ -7,6 +8,7 @@ import { withStreamGuards } from "../providers/guards.ts"
|
|
|
7
8
|
import { createRouterProvider } from "../providers/router.ts"
|
|
8
9
|
|
|
9
10
|
let currentRouter: ReturnType<typeof createRouterProvider> | null = null
|
|
11
|
+
let currentConfig: MinicodeConfig | null = null
|
|
10
12
|
|
|
11
13
|
/** Setup tanpa provider apa pun. Dilempar (bukan exit di sini) agar
|
|
12
14
|
* composition root bisa memilih presentasi: REPL/one-shot mencetak pesan
|
|
@@ -24,9 +26,17 @@ export async function reloadProviders(
|
|
|
24
26
|
): Promise<void> {
|
|
25
27
|
if (!currentRouter) return
|
|
26
28
|
const cfg = await loadConfig(cwd, { allowLocal: opts.allowLocal })
|
|
29
|
+
if (currentConfig)
|
|
30
|
+
currentConfig.providers.splice(0, currentConfig.providers.length, ...cfg.providers)
|
|
31
|
+
else currentConfig = cfg
|
|
27
32
|
const providers = await buildProviderListAsync(cfg)
|
|
28
|
-
const r = currentRouter as unknown as {
|
|
33
|
+
const r = currentRouter as unknown as {
|
|
34
|
+
updateProviders: (list: unknown[]) => void
|
|
35
|
+
}
|
|
29
36
|
if (typeof r.updateProviders === "function") r.updateProviders(providers)
|
|
37
|
+
// Keep the router's live context resolver. The composition root may have
|
|
38
|
+
// wrapped it with a session override and warning policy; replacing it here
|
|
39
|
+
// would make /sync silently reset child sessions to config-only limits.
|
|
30
40
|
}
|
|
31
41
|
|
|
32
42
|
export async function createProviderLayer(opts: {
|
|
@@ -43,6 +53,7 @@ export async function createProviderLayer(opts: {
|
|
|
43
53
|
setupWhenEmpty?: () => Promise<boolean>
|
|
44
54
|
}): Promise<{ cfg: MinicodeConfig; router: ReturnType<typeof createRouterProvider> }> {
|
|
45
55
|
const cfg = await loadConfig(opts.cwd, { allowLocal: opts.allowLocalConfig })
|
|
56
|
+
currentConfig = cfg
|
|
46
57
|
type Provider = ReturnType<typeof createOpenAICompatProvider>
|
|
47
58
|
let providers = await buildProviderListAsync(cfg)
|
|
48
59
|
|
|
@@ -119,6 +130,7 @@ export async function createProviderLayer(opts: {
|
|
|
119
130
|
}
|
|
120
131
|
const router = createRouterProvider({
|
|
121
132
|
providers,
|
|
133
|
+
contextWindowTokensForModel: (model) => resolveContextWindow(cfg, model).tokens,
|
|
122
134
|
...(opts.rateLimiter ? { limiter: opts.rateLimiter } : {}),
|
|
123
135
|
})
|
|
124
136
|
currentRouter = router
|
package/src/app/session.ts
CHANGED
|
@@ -1,23 +1,31 @@
|
|
|
1
1
|
import { resolve } from "node:path"
|
|
2
2
|
import type { RecoveryAction } from "#minicore/core/errors.ts"
|
|
3
|
-
import { ProviderError } from "#minicore/core/errors.ts"
|
|
3
|
+
import { AgentError, ProviderError } from "#minicore/core/errors.ts"
|
|
4
4
|
import type {
|
|
5
5
|
ModelProvider,
|
|
6
6
|
PermissionHandler,
|
|
7
|
+
ProviderEvent,
|
|
7
8
|
Session,
|
|
8
9
|
SessionConfig,
|
|
9
10
|
} from "#minicore/core/index.ts"
|
|
10
11
|
import { createSession as createCoreSession } from "#minicore/core/index.ts"
|
|
11
12
|
import { defaultRecoveryPolicy } from "#minicore/core/recovery.ts"
|
|
12
|
-
import {
|
|
13
|
+
import {
|
|
14
|
+
estimateMessages,
|
|
15
|
+
estimateSystem,
|
|
16
|
+
estimateTools,
|
|
17
|
+
safeStringify,
|
|
18
|
+
} from "#minicore/core/tokens.ts"
|
|
13
19
|
import { LIMITS } from "../constants.ts"
|
|
14
20
|
// [Area B · PROMPT 06] Binding persetujuan ↔ operasi yang dieksekusi.
|
|
15
21
|
import { ApprovalBindingStore, verifyApprovalBinding } from "../policy/approval-binding.ts"
|
|
16
22
|
import {
|
|
17
23
|
buildSystemPrompt,
|
|
18
24
|
createCalibratedEstimator,
|
|
25
|
+
createIncrementalTokenCounter,
|
|
19
26
|
minicodeEstimator,
|
|
20
27
|
} from "../policy/context.ts"
|
|
28
|
+
import { DEFAULT_FALLBACK_CONTEXT_WINDOW_TOKENS } from "../policy/context-window.ts"
|
|
21
29
|
import { parallelExecutor } from "../policy/executor.ts"
|
|
22
30
|
import {
|
|
23
31
|
canonicalArgsHash,
|
|
@@ -118,6 +126,8 @@ export async function createMinicodeSession(
|
|
|
118
126
|
> & {
|
|
119
127
|
systemExtra?: string
|
|
120
128
|
cwd?: string
|
|
129
|
+
/** Live model identity used for per-model token calibration. */
|
|
130
|
+
getContextModel?: () => string | undefined
|
|
121
131
|
permissionMode?: "auto" | "readonly" | "plan" | "allow-all" | "ask" | "allowlist"
|
|
122
132
|
/** S2.1: WorkMode adalah lapis intent TERPISAH dari PermissionMode.
|
|
123
133
|
* Default EXECUTE = perilaku lama (base handler apa adanya). Nilai selain
|
|
@@ -230,6 +240,7 @@ export async function createMinicodeSession(
|
|
|
230
240
|
workMode: _workMode,
|
|
231
241
|
allowLocalConfig,
|
|
232
242
|
systemExtra: _extra,
|
|
243
|
+
getContextModel: _getContextModel,
|
|
233
244
|
provider,
|
|
234
245
|
onPermissions,
|
|
235
246
|
onWorkMode,
|
|
@@ -261,6 +272,8 @@ export async function createMinicodeSession(
|
|
|
261
272
|
const t = (rest as Record<string, unknown>).timeoutMs
|
|
262
273
|
if (typeof t === "number" && (!Number.isFinite(t) || t < 0))
|
|
263
274
|
delete (rest as Record<string, unknown>).timeoutMs
|
|
275
|
+
else if (typeof t === "number" && t > LIMITS.MAX_TIMER_DELAY_MS)
|
|
276
|
+
(rest as Record<string, unknown>).timeoutMs = LIMITS.MAX_TIMER_DELAY_MS
|
|
264
277
|
const m = (rest as Record<string, unknown>).maxSteps
|
|
265
278
|
if (typeof m !== "number" || !Number.isFinite(m) || m < 1)
|
|
266
279
|
delete (rest as Record<string, unknown>).maxSteps
|
|
@@ -444,17 +457,172 @@ export async function createMinicodeSession(
|
|
|
444
457
|
const planHint = pm === "plan" ? PLAN_PM_HINT : ""
|
|
445
458
|
return baseSystem + planHint + workModeHint(wm)
|
|
446
459
|
}
|
|
460
|
+
// [CTX] Kalibrasi dipisahkan per identitas model agar berpindah ke model
|
|
461
|
+
// lain tidak membawa rasio tokenizer/provider dari sesi sebelumnya.
|
|
462
|
+
const calibrations = new Map<string, ReturnType<typeof createCalibratedEstimator>>()
|
|
463
|
+
const contextModelKey = (model?: string): string => model?.trim() || "__default__"
|
|
464
|
+
const calibrationFor = (model?: string) => {
|
|
465
|
+
const key = contextModelKey(model)
|
|
466
|
+
let calibration = calibrations.get(key)
|
|
467
|
+
if (!calibration) {
|
|
468
|
+
calibration = createCalibratedEstimator()
|
|
469
|
+
calibrations.set(key, calibration)
|
|
470
|
+
}
|
|
471
|
+
return calibration
|
|
472
|
+
}
|
|
473
|
+
let activeContextModel = opts.model
|
|
474
|
+
const currentContextModel = () => {
|
|
475
|
+
const selected = _getContextModel?.() ?? activeContextModel
|
|
476
|
+
try {
|
|
477
|
+
return provider.contextModelIdentity?.(selected) ?? selected
|
|
478
|
+
} catch {
|
|
479
|
+
return selected
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
const calibratedEstimator = (text: string) =>
|
|
483
|
+
calibrationFor(currentContextModel()).estimator(text)
|
|
484
|
+
let lastRequestLocalEstimate: { model: string; tokens: number } | undefined
|
|
485
|
+
const contextWindowForModel = (model?: string): number => {
|
|
486
|
+
const explicit = rest.contextWindowTokens
|
|
487
|
+
if (
|
|
488
|
+
!rest.contextWindowTokensForModel &&
|
|
489
|
+
typeof explicit === "number" &&
|
|
490
|
+
Number.isSafeInteger(explicit) &&
|
|
491
|
+
explicit > 0
|
|
492
|
+
) {
|
|
493
|
+
return explicit
|
|
494
|
+
}
|
|
495
|
+
try {
|
|
496
|
+
const resolved =
|
|
497
|
+
rest.contextWindowTokensForModel?.(model) ?? provider.contextWindowTokensForModel?.(model)
|
|
498
|
+
if (typeof resolved === "number" && Number.isSafeInteger(resolved) && resolved > 0)
|
|
499
|
+
return resolved
|
|
500
|
+
} catch {}
|
|
501
|
+
return typeof explicit === "number" && Number.isSafeInteger(explicit) && explicit > 0
|
|
502
|
+
? explicit
|
|
503
|
+
: DEFAULT_FALLBACK_CONTEXT_WINDOW_TOKENS
|
|
504
|
+
}
|
|
447
505
|
const dynamicProvider: ModelProvider = {
|
|
448
506
|
id: provider.id,
|
|
449
507
|
get models() {
|
|
450
508
|
return provider.models
|
|
451
509
|
},
|
|
452
|
-
stream(req, signal) {
|
|
453
|
-
|
|
510
|
+
async *stream(req, signal) {
|
|
511
|
+
const system = computeLiveSystem()
|
|
512
|
+
const model = req.model ?? currentContextModel()
|
|
513
|
+
let limit = contextWindowForModel(model)
|
|
514
|
+
const estimatorModel = model?.includes("::") ? model : (currentContextModel() ?? model)
|
|
515
|
+
let calibration = calibrationFor(estimatorModel)
|
|
516
|
+
let estimator = calibration.estimator
|
|
517
|
+
let admittedFactor = calibration.snapshot().factor
|
|
518
|
+
const tools = req.tools ?? []
|
|
519
|
+
const localInputTokens =
|
|
520
|
+
estimateMessages(req.messages, minicodeEstimator) +
|
|
521
|
+
estimateSystem(system, minicodeEstimator) +
|
|
522
|
+
estimateTools(tools, minicodeEstimator)
|
|
523
|
+
let inputTokens =
|
|
524
|
+
estimateMessages(req.messages, estimator) +
|
|
525
|
+
estimateSystem(system, estimator) +
|
|
526
|
+
estimateTools(tools, estimator)
|
|
527
|
+
lastRequestLocalEstimate = {
|
|
528
|
+
model: contextModelKey(estimatorModel),
|
|
529
|
+
tokens: localInputTokens,
|
|
530
|
+
}
|
|
531
|
+
// Sisakan ruang framing dan respons minimum. Tanpa reserve, request yang
|
|
532
|
+
// tepat menyentuh batas provider tetap ditolak setelah biaya dibakar.
|
|
533
|
+
let reserve = Math.min(256, Math.floor(limit / 10))
|
|
534
|
+
let outputAllowance = Math.max(0, limit - inputTokens - reserve)
|
|
535
|
+
let outputTokens = 0
|
|
536
|
+
const streamedText = createIncrementalTokenCounter()
|
|
537
|
+
const streamedReasoning = createIncrementalTokenCounter()
|
|
538
|
+
const contextLimitEvent = (input: number, output: number): ProviderEvent => ({
|
|
539
|
+
type: "extension",
|
|
540
|
+
kind: "context-window-limit",
|
|
541
|
+
data: { inputTokens: input, outputTokens: output, windowTokens: limit },
|
|
542
|
+
})
|
|
543
|
+
const overflow = (actualInput = inputTokens, actualOutput = outputTokens) =>
|
|
544
|
+
new AgentError(
|
|
545
|
+
"budget_exceeded",
|
|
546
|
+
`context window budget reached for the selected model: input ${actualInput} + output ${actualOutput} exceeds ${limit} tokens; reduce the prompt/tools or select a larger context window`,
|
|
547
|
+
)
|
|
548
|
+
const requestController = new AbortController()
|
|
549
|
+
const forwardAbort = () => requestController.abort(signal.reason)
|
|
550
|
+
if (signal.aborted) forwardAbort()
|
|
551
|
+
else signal.addEventListener("abort", forwardAbort, { once: true })
|
|
552
|
+
try {
|
|
553
|
+
if (inputTokens + reserve >= limit) {
|
|
554
|
+
const error = overflow(inputTokens, 0)
|
|
555
|
+
requestController.abort(error)
|
|
556
|
+
yield contextLimitEvent(inputTokens, 0)
|
|
557
|
+
throw error
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
for await (const event of provider.stream({ ...req, system }, requestController.signal)) {
|
|
561
|
+
if (event.type === "extension" && event.kind === "effective-model") {
|
|
562
|
+
const effective = event.data as { effective?: unknown; provider?: unknown } | undefined
|
|
563
|
+
if (
|
|
564
|
+
typeof effective?.effective === "string" &&
|
|
565
|
+
typeof effective.provider === "string"
|
|
566
|
+
) {
|
|
567
|
+
// Router fallback/substitution is a different model boundary.
|
|
568
|
+
// Keep the smaller of the requested and effective capacities so
|
|
569
|
+
// a failed primary provider cannot silently widen the budget.
|
|
570
|
+
const effectiveModel = `${effective.provider}::${effective.effective}`
|
|
571
|
+
const effectiveLimit = contextWindowForModel(effectiveModel)
|
|
572
|
+
limit = Math.min(limit, effectiveLimit)
|
|
573
|
+
calibration = calibrationFor(effectiveModel)
|
|
574
|
+
estimator = calibration.estimator
|
|
575
|
+
admittedFactor = calibration.snapshot().factor
|
|
576
|
+
inputTokens = Math.max(
|
|
577
|
+
inputTokens,
|
|
578
|
+
estimateMessages(req.messages, estimator) +
|
|
579
|
+
estimateSystem(system, estimator) +
|
|
580
|
+
estimateTools(tools, estimator),
|
|
581
|
+
)
|
|
582
|
+
reserve = Math.min(256, Math.floor(limit / 10))
|
|
583
|
+
outputAllowance = Math.max(0, limit - inputTokens - reserve)
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
const currentFactor = calibration.snapshot().factor
|
|
587
|
+
if (currentFactor > admittedFactor) {
|
|
588
|
+
inputTokens = Math.max(
|
|
589
|
+
inputTokens,
|
|
590
|
+
estimateMessages(req.messages, estimator) +
|
|
591
|
+
estimateSystem(system, estimator) +
|
|
592
|
+
estimateTools(tools, estimator),
|
|
593
|
+
)
|
|
594
|
+
reserve = Math.min(256, Math.floor(limit / 10))
|
|
595
|
+
outputAllowance = Math.max(0, limit - inputTokens - reserve)
|
|
596
|
+
}
|
|
597
|
+
admittedFactor = currentFactor
|
|
598
|
+
let added = 0
|
|
599
|
+
if (event.type === "text") {
|
|
600
|
+
added = streamedText.add(event.text, calibration.snapshot().factor)
|
|
601
|
+
} else if (event.type === "tool_call") {
|
|
602
|
+
added = estimator(event.name) + estimator(safeStringify(event.args))
|
|
603
|
+
} else if (event.type === "extension" && event.kind === "reasoning") {
|
|
604
|
+
const reasoning = (event.data as { text?: unknown } | undefined)?.text
|
|
605
|
+
if (typeof reasoning === "string") {
|
|
606
|
+
added = streamedReasoning.add(reasoning, calibration.snapshot().factor)
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
if (added > 0 && outputTokens + added > outputAllowance) {
|
|
610
|
+
const error = overflow(inputTokens, outputTokens + added)
|
|
611
|
+
requestController.abort(error)
|
|
612
|
+
yield contextLimitEvent(inputTokens, outputTokens + added)
|
|
613
|
+
throw error
|
|
614
|
+
}
|
|
615
|
+
outputTokens += added
|
|
616
|
+
yield event as ProviderEvent
|
|
617
|
+
}
|
|
618
|
+
} finally {
|
|
619
|
+
signal.removeEventListener("abort", forwardAbort)
|
|
620
|
+
if (!requestController.signal.aborted) {
|
|
621
|
+
requestController.abort(new AgentError("aborted", "provider stream closed"))
|
|
622
|
+
}
|
|
623
|
+
}
|
|
454
624
|
},
|
|
455
625
|
}
|
|
456
|
-
// [Fase 3 / CTX-03] Estimator terkalibrasi terhadap usage aktual provider.
|
|
457
|
-
const calibration = createCalibratedEstimator()
|
|
458
626
|
const liveToolSchemas = () =>
|
|
459
627
|
registeredTools.map((t) => ({
|
|
460
628
|
name: t.name,
|
|
@@ -463,11 +631,14 @@ export async function createMinicodeSession(
|
|
|
463
631
|
}))
|
|
464
632
|
const core = createCoreSession({
|
|
465
633
|
...rest,
|
|
634
|
+
contextWindowTokens: contextWindowForModel(currentContextModel()),
|
|
635
|
+
contextWindowTokensForModel: contextWindowForModel,
|
|
466
636
|
provider: dynamicProvider,
|
|
467
637
|
system: computeLiveSystem(),
|
|
638
|
+
systemForContext: computeLiveSystem,
|
|
468
639
|
permissions: withEffectBarrier,
|
|
469
640
|
permissionMode: livePermissionMode,
|
|
470
|
-
estimator:
|
|
641
|
+
estimator: calibratedEstimator,
|
|
471
642
|
recovery: cappedRecovery,
|
|
472
643
|
executor: parallelExecutor({
|
|
473
644
|
concurrency: safeConcurrency ?? LIMITS.EXECUTOR_CONCURRENCY,
|
|
@@ -479,14 +650,29 @@ export async function createMinicodeSession(
|
|
|
479
650
|
})
|
|
480
651
|
core.events.on("provider:extension", (e) => {
|
|
481
652
|
if (e.kind !== "usage") return
|
|
482
|
-
const d = e.data as
|
|
483
|
-
|
|
484
|
-
|
|
653
|
+
const d = e.data as
|
|
654
|
+
| {
|
|
655
|
+
inputTokens?: number
|
|
656
|
+
totalTokens?: number
|
|
657
|
+
model?: string
|
|
658
|
+
provider?: string
|
|
659
|
+
source?: string
|
|
660
|
+
}
|
|
661
|
+
| undefined
|
|
662
|
+
if (!d || d.source === "compaction") return
|
|
663
|
+
const reportedModel =
|
|
664
|
+
typeof d.model === "string" && d.model.length > 0
|
|
665
|
+
? typeof d.provider === "string" && d.provider.length > 0
|
|
666
|
+
? `${d.provider}::${d.model}`
|
|
667
|
+
: d.model
|
|
668
|
+
: currentContextModel()
|
|
669
|
+
const fallbackLocal =
|
|
485
670
|
estimateSystem(computeLiveSystem(), minicodeEstimator) +
|
|
486
671
|
estimateTools(liveToolSchemas(), minicodeEstimator) +
|
|
487
672
|
estimateMessages(core.state.history, minicodeEstimator)
|
|
488
|
-
|
|
489
|
-
|
|
673
|
+
const localEstimatedTokens = lastRequestLocalEstimate?.tokens ?? fallbackLocal
|
|
674
|
+
calibrationFor(reportedModel).observeProviderUsage({
|
|
675
|
+
localEstimatedTokens,
|
|
490
676
|
providerInputTokens: d.inputTokens,
|
|
491
677
|
providerTotalTokens: d.totalTokens,
|
|
492
678
|
})
|
|
@@ -530,5 +716,22 @@ export async function createMinicodeSession(
|
|
|
530
716
|
return origRun(input, runOpts)
|
|
531
717
|
}
|
|
532
718
|
}
|
|
533
|
-
return
|
|
719
|
+
return {
|
|
720
|
+
get state() {
|
|
721
|
+
return core.state
|
|
722
|
+
},
|
|
723
|
+
get events() {
|
|
724
|
+
return core.events
|
|
725
|
+
},
|
|
726
|
+
get contextTokens() {
|
|
727
|
+
return core.contextTokens
|
|
728
|
+
},
|
|
729
|
+
run(input: string, runOpts?: { signal?: AbortSignal; model?: string }) {
|
|
730
|
+
activeContextModel = runOpts?.model ?? opts.model
|
|
731
|
+
return core.run(input, runOpts)
|
|
732
|
+
},
|
|
733
|
+
abort() {
|
|
734
|
+
core.abort()
|
|
735
|
+
},
|
|
736
|
+
}
|
|
534
737
|
}
|
package/src/config.ts
CHANGED
|
@@ -37,6 +37,10 @@ export interface ProviderEntry {
|
|
|
37
37
|
/** API key. Kosong bila provider memakai OAuth (`auth: "oauth"`). */
|
|
38
38
|
apiKey: string
|
|
39
39
|
models: string[]
|
|
40
|
+
/** Context window tokens by exact model id; `*` is a provider-wide fallback.
|
|
41
|
+
* Values are operator-supplied because gateways often expose aliases whose
|
|
42
|
+
* actual model capacity cannot be discovered reliably at runtime. */
|
|
43
|
+
contextWindows?: Record<string, number>
|
|
40
44
|
providerHint?: string
|
|
41
45
|
/** Knob generik reasoning effort — dipetakan per-wire (openai reasoning_effort, anthropic thinking, gemini). */
|
|
42
46
|
reasoningEffort?: "low" | "medium" | "high"
|
|
@@ -104,9 +108,32 @@ export function localConfigNotice(cwd: string, allowLocal: boolean): string | un
|
|
|
104
108
|
export function normalizeConfig(raw: unknown): MinicodeConfig {
|
|
105
109
|
const cfg = raw as Record<string, unknown>
|
|
106
110
|
const providers = Array.isArray(cfg?.providers)
|
|
107
|
-
? (cfg.providers as ProviderEntry[])
|
|
108
|
-
(p) => p && typeof p.id === "string" && typeof p.baseUrl === "string"
|
|
109
|
-
|
|
111
|
+
? (cfg.providers as ProviderEntry[])
|
|
112
|
+
.filter((p) => p && typeof p.id === "string" && typeof p.baseUrl === "string")
|
|
113
|
+
.map((p) => {
|
|
114
|
+
const source = (p as { contextWindows?: unknown }).contextWindows
|
|
115
|
+
const validContextWindows: Record<string, number> = {}
|
|
116
|
+
if (source && typeof source === "object" && !Array.isArray(source)) {
|
|
117
|
+
for (const [model, tokens] of Object.entries(source as Record<string, unknown>)) {
|
|
118
|
+
if (
|
|
119
|
+
(model === "*" || model.length > 0) &&
|
|
120
|
+
typeof tokens === "number" &&
|
|
121
|
+
Number.isSafeInteger(tokens) &&
|
|
122
|
+
tokens > 0 &&
|
|
123
|
+
tokens <= 20_000_000
|
|
124
|
+
) {
|
|
125
|
+
validContextWindows[model] = tokens
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
const contextWindows =
|
|
130
|
+
Object.keys(validContextWindows).length > 0 ? validContextWindows : undefined
|
|
131
|
+
return {
|
|
132
|
+
...p,
|
|
133
|
+
contextWindows:
|
|
134
|
+
contextWindows && Object.keys(contextWindows).length > 0 ? contextWindows : undefined,
|
|
135
|
+
}
|
|
136
|
+
})
|
|
110
137
|
: []
|
|
111
138
|
// Server MCP sah bila punya `command` (stdio) ATAU `url` (HTTP). Entri tanpa
|
|
112
139
|
// keduanya dibuang di sini supaya kegagalan tampak saat config dibaca, bukan
|
package/src/constants.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
/** Centralized magic numbers — full English naming. Single source for limits. */
|
|
2
2
|
export const LIMITS = {
|
|
3
|
+
/** Maksimum timer JS; nilai lebih besar diklem agar tidak berubah jadi 1ms. */
|
|
4
|
+
MAX_TIMER_DELAY_MS: 2_147_483_647,
|
|
3
5
|
/** File size limits */
|
|
4
6
|
READ_FILE_MAX_BYTES: 2_000_000,
|
|
5
7
|
WRITE_FILE_MAX_CHARS: 5_000_000,
|
package/src/daemon/control.ts
CHANGED
|
@@ -22,7 +22,7 @@ export interface HostedSessionInfo {
|
|
|
22
22
|
runStatus: string | null
|
|
23
23
|
presentationHead: number
|
|
24
24
|
/** P0.2 (Q5): WorkMode efektif sesi yang di-host (bila diketahui host). */
|
|
25
|
-
workMode?: "DISCUSS" | "PLAN" | "
|
|
25
|
+
workMode?: "DISCUSS" | "PLAN" | "BUILD"
|
|
26
26
|
/**
|
|
27
27
|
* P2.3: hasil recovery run terakhir yang durable (mis. UNKNOWN setelah
|
|
28
28
|
* restart). Operator dapat membedakan LIVE vs reconstructed/interrupted
|
package/src/mcp/server.ts
CHANGED
|
@@ -240,9 +240,8 @@ async function invokeTool(
|
|
|
240
240
|
* the whole process. As a durable task namespace that is unsafe: it is a
|
|
241
241
|
* constant, so every MCP context that has ever run against the same `root`
|
|
242
242
|
* shares one identity space, and it can also collide with anything else that
|
|
243
|
-
* ever uses that string. `
|
|
244
|
-
*
|
|
245
|
-
* overwrite each other's files last-writer-wins.
|
|
243
|
+
* ever uses that string. Because `mcp serve` is single-tenant, concurrent
|
|
244
|
+
* requests must not share this durable namespace and overwrite files last-writer-wins.
|
|
246
245
|
*
|
|
247
246
|
* WHAT THIS IDENTIFIES. One server instance = one logical MCP context. That
|
|
248
247
|
* matches this implementation's actual lifecycle, which was verified rather
|