minicode-ai 0.11.0 → 0.13.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.
- package/CHANGELOG.md +98 -0
- package/LICENSE +21 -21
- package/README.md +4 -4
- package/cli/args.ts +46 -0
- package/cli/commands/acp.ts +163 -10
- package/cli/commands/config.ts +33 -18
- package/cli/commands/daemon.ts +515 -0
- package/cli/commands/exec.ts +145 -53
- package/cli/commands/openwork.ts +986 -0
- package/cli/commands/sessions.ts +4 -1
- package/cli/commands/stats.ts +34 -4
- package/cli/commands.ts +217 -2
- package/cli/index.ts +146 -14
- package/cli/recovery-warning.ts +115 -0
- package/cli/router.ts +32 -1
- package/cli/setup.ts +2332 -171
- package/cli/tui.ts +113 -7
- package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
- package/docs/OUTPUT_EVENT_MODEL.md +289 -0
- package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
- package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
- package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
- package/docs/OUTPUT_UX_RULES.md +449 -0
- package/docs/PLAN_UIUX_V6.md +2 -2
- package/docs/README.md +4 -3
- package/docs/TERMINAL_CONTRACT.md +278 -66
- package/docs/architecture.md +89 -7
- package/docs/changelog.md +1 -1
- package/docs/choosing-mode.md +2 -2
- package/docs/cli.md +9 -5
- package/docs/concepts.md +1 -1
- package/docs/contributing.md +9 -2
- package/docs/environment.md +6 -2
- package/docs/exec.md +46 -5
- package/docs/memory-sessions.md +2 -0
- package/docs/policy-sandbox.md +1 -1
- package/docs/pricing-budget.md +1 -1
- package/docs/quickstart.md +2 -2
- package/docs/repl.md +6 -2
- package/docs/security-model.md +1 -1
- package/docs/security.md +1 -1
- package/docs/skills.md +2 -2
- package/docs/terminal.md +9 -5
- package/docs/tools.md +1 -1
- package/package.json +35 -5
- package/src/app/session.ts +261 -15
- package/src/app/tool-layer.ts +94 -7
- package/src/daemon/approvals.ts +361 -0
- package/src/daemon/capability.ts +145 -0
- package/src/daemon/children.ts +142 -0
- package/src/daemon/client.ts +267 -0
- package/src/daemon/control.ts +350 -0
- package/src/daemon/discovery.ts +234 -0
- package/src/daemon/feed.ts +155 -0
- package/src/daemon/framing.ts +94 -0
- package/src/daemon/host.ts +316 -0
- package/src/daemon/protocol.ts +217 -0
- package/src/daemon/resource.ts +170 -0
- package/src/daemon/sanitize.ts +57 -0
- package/src/daemon/server.ts +627 -0
- package/src/daemon/store.ts +317 -0
- package/src/daemon/subscription.ts +270 -0
- package/src/daemon/telemetry.ts +81 -0
- package/src/hooks/run.ts +12 -1
- package/src/lib/atomic-write.ts +29 -3
- package/src/lib/db-path.ts +26 -0
- package/src/lib/keystore.ts +544 -42
- package/src/lib/net.ts +43 -1
- package/src/lib/safe-open.ts +116 -1
- package/src/lib/session-id.ts +15 -0
- package/src/lsp/client.ts +123 -5
- package/src/mcp/client.ts +139 -17
- package/src/mcp/server.ts +177 -50
- package/src/mcp/transport.ts +16 -19
- package/src/memory/vector.ts +770 -55
- package/src/policy/allowlist.ts +14 -2
- package/src/policy/bash-guard.ts +105 -10
- package/src/policy/compaction.ts +82 -5
- package/src/policy/consequence-engine.ts +220 -0
- package/src/policy/context.ts +132 -0
- package/src/policy/executor.ts +187 -121
- package/src/policy/no-progress.ts +559 -0
- package/src/policy/permission.ts +4 -8
- package/src/policy/pricing.ts +17 -3
- package/src/policy/scrub.ts +69 -2
- package/src/policy/tool-contract.ts +515 -0
- package/src/policy/usage.ts +310 -24
- package/src/policy/verifier.ts +6 -3
- package/src/policy/work-mode.ts +182 -0
- package/src/presentation/adapter.ts +533 -26
- package/src/presentation/events.ts +151 -0
- package/src/presentation/model.ts +180 -27
- package/src/presentation/projection.ts +858 -0
- package/src/presentation/reducer.ts +645 -310
- package/src/presentation/store.ts +12 -7
- package/src/providers/anthropic.ts +18 -10
- package/src/providers/responses.ts +17 -7
- package/src/runtime/capability.ts +409 -0
- package/src/runtime/child-execution.ts +274 -0
- package/src/runtime/composition.ts +958 -0
- package/src/runtime/dispatch.ts +591 -0
- package/src/runtime/execution-backend.ts +632 -0
- package/src/runtime/execution-events.ts +272 -0
- package/src/runtime/execution-id.ts +230 -0
- package/src/runtime/execution-journal.ts +926 -0
- package/src/runtime/execution-kernel.ts +456 -0
- package/src/runtime/execution-registry.ts +379 -0
- package/src/runtime/process-supervision.ts +276 -0
- package/src/runtime/production-execution.ts +551 -0
- package/src/runtime/production-runtime.ts +217 -0
- package/src/runtime/recovery-safety.ts +70 -0
- package/src/runtime/recovery.ts +477 -0
- package/src/runtime/runtime-capabilities.ts +179 -0
- package/src/runtime/runtime-diagnostics.ts +141 -0
- package/src/runtime/runtime-host.ts +365 -0
- package/src/runtime/runtime-status-facts.ts +222 -0
- package/src/runtime/runtime-status-provider.ts +74 -0
- package/src/runtime/runtime-status.ts +459 -0
- package/src/runtime/runtime-task-admission.ts +101 -0
- package/src/runtime/supervisor.ts +444 -0
- package/src/session/authority.ts +168 -0
- package/src/session/checkpoint.ts +88 -1
- package/src/session/context-adapter.ts +251 -0
- package/src/session/context-assembly.ts +242 -0
- package/src/session/context-identity.ts +389 -0
- package/src/session/context-projection.ts +248 -0
- package/src/session/context-selector.ts +500 -0
- package/src/session/cross-session-adoption.ts +249 -0
- package/src/session/full-history-fold.ts +171 -0
- package/src/session/identity.ts +192 -0
- package/src/session/journal.ts +805 -102
- package/src/session/open-work-intent.ts +732 -0
- package/src/session/open-work.ts +767 -0
- package/src/session/pending-tools.ts +94 -0
- package/src/session/persistence.ts +3569 -127
- package/src/session/runtime-header.ts +208 -0
- package/src/session/shadow-git.ts +13 -5
- package/src/session/verification.ts +1623 -0
- package/src/task/assignment.ts +136 -0
- package/src/task/autonomous-adapter.ts +168 -0
- package/src/task/autonomous-context.ts +630 -0
- package/src/task/autonomous-policy.ts +490 -0
- package/src/task/continuity.ts +179 -0
- package/src/task/execution-cancellation.ts +165 -0
- package/src/task/graph-validate.ts +379 -0
- package/src/task/graph.ts +305 -0
- package/src/task/identity.ts +230 -0
- package/src/task/model.ts +417 -0
- package/src/task/production-scheduler.ts +293 -0
- package/src/task/readiness.ts +229 -0
- package/src/task/scheduler-observability.ts +387 -0
- package/src/task/scheduler.ts +1197 -0
- package/src/task/scheduling-policy.ts +165 -0
- package/src/task/session-authority.ts +148 -0
- package/src/task/session-ownership.ts +211 -0
- package/src/task/store.ts +2887 -0
- package/src/task/sync.ts +343 -0
- package/src/task/trigger.ts +260 -0
- package/src/tools/bash.ts +377 -211
- package/src/tools/code_run.ts +1 -1
- package/src/tools/delete_file.ts +1 -1
- package/src/tools/edit.ts +33 -6
- package/src/tools/evidence.ts +30 -0
- package/src/tools/git.ts +4 -4
- package/src/tools/glob.ts +12 -3
- package/src/tools/grep.ts +1 -1
- package/src/tools/lsp.ts +4 -4
- package/src/tools/mcp_call.ts +11 -4
- package/src/tools/memory.ts +153 -18
- package/src/tools/move_file.ts +1 -1
- package/src/tools/patch.ts +1 -1
- package/src/tools/read_file.ts +1 -1
- package/src/tools/read_image.ts +1 -1
- package/src/tools/submit_result.ts +1 -1
- package/src/tools/task.ts +437 -41
- package/src/tools/todo.ts +662 -35
- package/src/tools/web_fetch.ts +4 -2
- package/src/tools/web_search.ts +9 -3
- package/src/tools/write_file.ts +1 -1
- package/src/ui/assistant/simple.ts +123 -50
- package/src/ui/assistant/turn-status.ts +17 -3
- package/src/ui/contract.ts +184 -0
- package/src/ui/footer.ts +54 -18
- package/src/ui/i18n/en.ts +62 -6
- package/src/ui/i18n/id.ts +62 -6
- package/src/ui/input/prompt-engine.ts +120 -25
- package/src/ui/render/errors.ts +39 -1
- package/src/ui/render/markdown-table.ts +455 -0
- package/src/ui/render/markdown.ts +22 -1
- package/src/ui/render/table-grid.ts +184 -0
- package/src/ui/render/table.ts +15 -76
- package/src/ui/runtime/screen.ts +7 -2
- package/src/ui/runtime/statusline.ts +25 -6
- package/src/ui/tui/app.ts +598 -133
- package/src/ui/tui/transcript.ts +531 -89
- package/vendor/minicore/VENDOR.md +1 -1
- package/vendor/minicore/src/core/budget.ts +25 -25
- package/vendor/minicore/src/core/compact.ts +75 -75
- package/vendor/minicore/src/core/errors.ts +59 -59
- package/vendor/minicore/src/core/events.ts +73 -73
- package/vendor/minicore/src/core/executor.ts +139 -139
- package/vendor/minicore/src/core/history.ts +31 -31
- package/vendor/minicore/src/core/index.ts +41 -41
- package/vendor/minicore/src/core/loop.ts +355 -355
- package/vendor/minicore/src/core/permission.ts +22 -22
- package/vendor/minicore/src/core/provider.ts +39 -39
- package/vendor/minicore/src/core/recovery.ts +35 -35
- package/vendor/minicore/src/core/session.ts +327 -327
- package/vendor/minicore/src/core/snapshot.ts +146 -146
- package/vendor/minicore/src/core/tokens.ts +107 -107
- package/vendor/minicore/src/core/tool.ts +115 -115
- package/vendor/minicore/src/core/types.ts +50 -50
- package/vendor/minicore/src/providers/openai-compat.ts +417 -417
- package/AGENTS.md +0 -45
- package/PLAN.md +0 -491
- package/docs/ARCHITECTURE.html +0 -1248
- package/docs/CONTROL-PLANE-MAP.md +0 -139
- package/docs/HARNESS.md +0 -150
- package/docs/SUMMARY.md +0 -52
- package/docs/UI_RENDER_PIPELINE.md +0 -165
- package/docs/USAGE.md +0 -11
|
@@ -0,0 +1,559 @@
|
|
|
1
|
+
// [Fase 3 / LOOP-12, LOOP-G19, LOOP-G27] Detektor deterministik No-Progress &
|
|
2
|
+
// Oscillation.
|
|
3
|
+
//
|
|
4
|
+
// Menutup tiga modus macet otonom tanpa menyentuh kernel frozen:
|
|
5
|
+
// 1. Exact Action-Error Fingerprint (`REPEATED_ACTION_ERROR`): pemanggilan
|
|
6
|
+
// tool dengan nama + argumen kanonis + headline error yang identik N kali
|
|
7
|
+
// berturut-turut diblokir pada percobaan ke-(N+1).
|
|
8
|
+
// 2. Workspace State Oscillation (`WORKSPACE_REVERT_CYCLE`): file mengalami
|
|
9
|
+
// siklus bolak-balik kembali ke hash lama sebanyak M siklus (mis.
|
|
10
|
+
// H1 -> H2 -> H1 -> H2 -> H1 untuk M=2) tanpa verifikasi lulus di antaranya.
|
|
11
|
+
// 3. Read-Only Thrashing (`READ_ONLY_THRASHING`): pemanggilan tool murni-baca
|
|
12
|
+
// (`sideEffectTier === "PURE_READ"`) berturut-turut melampaui ambang batas
|
|
13
|
+
// saat sesi berada pada postur kerja aktif (bukan readonly/explore/plan)
|
|
14
|
+
// tanpa pembaruan rencana (`todo_write`), mutasi, atau jawaban ke user.
|
|
15
|
+
//
|
|
16
|
+
// Modul ini berada di `src/policy/` dan hanya mengimpor `./tool-contract.ts` +
|
|
17
|
+
// pustaka standar Node agar batas lapisan tetap bersih.
|
|
18
|
+
|
|
19
|
+
import { createHash } from "node:crypto"
|
|
20
|
+
import { readFile, stat } from "node:fs/promises"
|
|
21
|
+
import { isAbsolute, relative, resolve } from "node:path"
|
|
22
|
+
import { contractForTool } from "./tool-contract.ts"
|
|
23
|
+
|
|
24
|
+
export type NoProgressPosture = "active" | "readonly" | "explore" | "plan"
|
|
25
|
+
|
|
26
|
+
export type LoopGuardKind = "NO_PROGRESS" | "OSCILLATION"
|
|
27
|
+
|
|
28
|
+
export type LoopGuardReason =
|
|
29
|
+
| "REPEATED_ACTION_ERROR"
|
|
30
|
+
| "WORKSPACE_REVERT_CYCLE"
|
|
31
|
+
| "READ_ONLY_THRASHING"
|
|
32
|
+
|
|
33
|
+
export type NoProgressVerdict =
|
|
34
|
+
| { readonly allowed: true }
|
|
35
|
+
| {
|
|
36
|
+
readonly allowed: false
|
|
37
|
+
readonly kind: LoopGuardKind
|
|
38
|
+
readonly reason: LoopGuardReason
|
|
39
|
+
readonly message: string
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export class NoProgressError extends Error {
|
|
43
|
+
readonly name = "NoProgressError"
|
|
44
|
+
readonly kind: LoopGuardKind
|
|
45
|
+
readonly reason: LoopGuardReason
|
|
46
|
+
|
|
47
|
+
constructor(kind: LoopGuardKind, reason: LoopGuardReason, message: string) {
|
|
48
|
+
super(message)
|
|
49
|
+
this.kind = kind
|
|
50
|
+
this.reason = reason
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface NoProgressOptions {
|
|
55
|
+
/** Maksimum kegagalan identik berturut-turut sebelum panggilan berikutnya diblokir (default 3). */
|
|
56
|
+
readonly maxRepeatedErrors?: number
|
|
57
|
+
/** Maksimum siklus kembali ke hash file lama tanpa verifikasi hijau (default 2). */
|
|
58
|
+
readonly maxOscillations?: number
|
|
59
|
+
/** Maksimum panggilan PURE_READ berturut-turut di postur aktif (default 15). */
|
|
60
|
+
readonly maxConsecutiveReadCalls?: number
|
|
61
|
+
/** Postur sesi saat ini; non-"active" menonaktifkan detektor read-only thrashing. */
|
|
62
|
+
readonly getPosture?: () => NoProgressPosture
|
|
63
|
+
/**
|
|
64
|
+
* [Fase 6A / ACE-04] Maksimum retry terjustifikasi setelah bukti baru
|
|
65
|
+
* (default 1). Hard cap absolut: tidak pernah menambah budget tanpa batas.
|
|
66
|
+
*/
|
|
67
|
+
readonly maxNewEvidenceRetries?: number
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function canonicalize(value: unknown): string {
|
|
71
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null"
|
|
72
|
+
if (Array.isArray(value)) return `[${value.map(canonicalize).join(",")}]`
|
|
73
|
+
const keys = Object.keys(value as Record<string, unknown>).sort()
|
|
74
|
+
return `{${keys
|
|
75
|
+
.map((k) => `${JSON.stringify(k)}:${canonicalize((value as Record<string, unknown>)[k])}`)
|
|
76
|
+
.join(",")}}`
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Hash argumen kanonis (identik dengan `hashArgs` pada `src/session/journal.ts`). */
|
|
80
|
+
export function canonicalArgsHash(args: unknown): string {
|
|
81
|
+
return createHash("sha256")
|
|
82
|
+
.update(canonicalize(args ?? {}))
|
|
83
|
+
.digest("hex")
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Ambil headline error yang stabil (baris pertama bermakna, menormalkan angka
|
|
88
|
+
* durasi volatil agar timeout/error yang sama menghasilkan sidik jari sama).
|
|
89
|
+
*/
|
|
90
|
+
export function normalizeErrorHeadline(errorText: string): string {
|
|
91
|
+
const firstLine =
|
|
92
|
+
String(errorText ?? "")
|
|
93
|
+
.split(/\r?\n/)
|
|
94
|
+
.map((line) => line.trim())
|
|
95
|
+
.find((line) => line.length > 0) ?? "error"
|
|
96
|
+
return firstLine
|
|
97
|
+
.replace(/\bduration_ms=\d+/g, "duration_ms=#")
|
|
98
|
+
.replace(/\s+/g, " ")
|
|
99
|
+
.slice(0, 240)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function computeActionErrorFingerprint(
|
|
103
|
+
toolName: string,
|
|
104
|
+
args: unknown,
|
|
105
|
+
errorText: string,
|
|
106
|
+
): string {
|
|
107
|
+
const payload = `${toolName}\0${canonicalArgsHash(args)}\0${normalizeErrorHeadline(errorText)}`
|
|
108
|
+
return createHash("sha256").update(payload, "utf8").digest("hex")
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const HASH_MAX_BYTES = 8 * 1024 * 1024
|
|
112
|
+
|
|
113
|
+
async function hashWorkspaceFile(
|
|
114
|
+
absPath: string,
|
|
115
|
+
): Promise<{ ok: true; hash: string | null } | { ok: false }> {
|
|
116
|
+
try {
|
|
117
|
+
const st = await stat(absPath)
|
|
118
|
+
if (!st.isFile() || st.size > HASH_MAX_BYTES) return { ok: false }
|
|
119
|
+
const bytes = await readFile(absPath)
|
|
120
|
+
return { ok: true, hash: createHash("sha256").update(bytes).digest("hex") }
|
|
121
|
+
} catch (err) {
|
|
122
|
+
if ((err as NodeJS.ErrnoException)?.code === "ENOENT") return { ok: true, hash: null }
|
|
123
|
+
return { ok: false }
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function targetRelPathForTool(
|
|
128
|
+
toolName: string,
|
|
129
|
+
args: unknown,
|
|
130
|
+
workspaceRoot: string,
|
|
131
|
+
): string | null {
|
|
132
|
+
const a = (args ?? {}) as Record<string, unknown>
|
|
133
|
+
const raw =
|
|
134
|
+
toolName === "write_file" ||
|
|
135
|
+
toolName === "edit" ||
|
|
136
|
+
toolName === "apply_patch" ||
|
|
137
|
+
toolName === "delete_file"
|
|
138
|
+
? a.path
|
|
139
|
+
: toolName === "move_file"
|
|
140
|
+
? a.to
|
|
141
|
+
: undefined
|
|
142
|
+
if (typeof raw !== "string" || !raw.trim()) return null
|
|
143
|
+
const root = resolve(workspaceRoot)
|
|
144
|
+
const rel = relative(root, resolve(root, raw)).replace(/\\/g, "/")
|
|
145
|
+
if (!rel || rel.startsWith("..") || isAbsolute(rel)) return null
|
|
146
|
+
return rel
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function normalizeTrackPath(rawPath: string): string {
|
|
150
|
+
return rawPath.trim().replace(/\\/g, "/").replace(/^\.\//, "")
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
interface FileHashTracker {
|
|
154
|
+
history: (string | null)[]
|
|
155
|
+
visits: Map<string, number>
|
|
156
|
+
oscillationMessage: string | null
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const HASH_NULL_SENTINEL = "__ABSENT__"
|
|
160
|
+
|
|
161
|
+
function hashKey(h: string | null): string {
|
|
162
|
+
return h === null ? HASH_NULL_SENTINEL : h
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export interface NoProgressDetector {
|
|
166
|
+
evaluateBeforeCall(call: { id?: string; name: string; args?: unknown }): NoProgressVerdict
|
|
167
|
+
assertBeforeCall(call: { id?: string; name: string; args?: unknown }): void
|
|
168
|
+
capturePreMutation(
|
|
169
|
+
call: { id: string; name: string; args?: unknown },
|
|
170
|
+
workspaceRoot: string,
|
|
171
|
+
): Promise<void>
|
|
172
|
+
/**
|
|
173
|
+
* [Fase 3] Titik masuk barrier async tunggal: tunggu seluruh pencatatan
|
|
174
|
+
* post-mutation step sebelumnya selesai dulu (menutup race async antar-step),
|
|
175
|
+
* evaluasi guard, lalu rekam hash pra-mutasi.
|
|
176
|
+
*/
|
|
177
|
+
beforeToolEffectCheck(
|
|
178
|
+
call: { id: string; name: string; args?: unknown },
|
|
179
|
+
workspaceRoot: string,
|
|
180
|
+
): Promise<void>
|
|
181
|
+
flushPending(): Promise<void>
|
|
182
|
+
recordOutcome(input: {
|
|
183
|
+
id?: string
|
|
184
|
+
name: string
|
|
185
|
+
args?: unknown
|
|
186
|
+
isError?: boolean
|
|
187
|
+
content?: string
|
|
188
|
+
}): NoProgressVerdict
|
|
189
|
+
recordFileMutation(input: {
|
|
190
|
+
path: string
|
|
191
|
+
preTargetHash: string | null
|
|
192
|
+
postTargetHash: string | null
|
|
193
|
+
}): NoProgressVerdict
|
|
194
|
+
completePostMutation(
|
|
195
|
+
call: { id: string; name: string; args?: unknown; isError?: boolean },
|
|
196
|
+
workspaceRoot: string,
|
|
197
|
+
): Promise<NoProgressVerdict>
|
|
198
|
+
noteVerificationPassed(): void
|
|
199
|
+
noteAssistantResponse(): void
|
|
200
|
+
reset(): void
|
|
201
|
+
snapshot(): {
|
|
202
|
+
readonly repeatedErrorStreak: number
|
|
203
|
+
readonly consecutiveReadCalls: number
|
|
204
|
+
readonly oscillatingPaths: readonly string[]
|
|
205
|
+
/** [Fase 6A / ACE-04] Ada bukti baru sejak blokir REPEATED_ACTION_ERROR. */
|
|
206
|
+
readonly newEvidenceSinceFailure: boolean
|
|
207
|
+
/** [Fase 6A / ACE-04] Retry terjustifikasi yang sudah dipakai untuk blokir aktif. */
|
|
208
|
+
readonly justifiedRetriesUsed: number
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export function createNoProgressDetector(options: NoProgressOptions = {}): NoProgressDetector {
|
|
213
|
+
const maxRepeatedErrors =
|
|
214
|
+
typeof options.maxRepeatedErrors === "number" &&
|
|
215
|
+
Number.isFinite(options.maxRepeatedErrors) &&
|
|
216
|
+
options.maxRepeatedErrors >= 1
|
|
217
|
+
? Math.floor(options.maxRepeatedErrors)
|
|
218
|
+
: 3
|
|
219
|
+
const maxOscillations =
|
|
220
|
+
typeof options.maxOscillations === "number" &&
|
|
221
|
+
Number.isFinite(options.maxOscillations) &&
|
|
222
|
+
options.maxOscillations >= 1
|
|
223
|
+
? Math.floor(options.maxOscillations)
|
|
224
|
+
: 2
|
|
225
|
+
const maxConsecutiveReadCalls =
|
|
226
|
+
typeof options.maxConsecutiveReadCalls === "number" &&
|
|
227
|
+
Number.isFinite(options.maxConsecutiveReadCalls) &&
|
|
228
|
+
options.maxConsecutiveReadCalls >= 1
|
|
229
|
+
? Math.floor(options.maxConsecutiveReadCalls)
|
|
230
|
+
: 15
|
|
231
|
+
const getPosture = options.getPosture ?? (() => "active" as const)
|
|
232
|
+
const maxNewEvidenceRetries =
|
|
233
|
+
typeof options.maxNewEvidenceRetries === "number" &&
|
|
234
|
+
Number.isFinite(options.maxNewEvidenceRetries) &&
|
|
235
|
+
options.maxNewEvidenceRetries >= 0
|
|
236
|
+
? Math.floor(options.maxNewEvidenceRetries)
|
|
237
|
+
: 1
|
|
238
|
+
|
|
239
|
+
let lastErrorFingerprint: string | null = null
|
|
240
|
+
let lastErrorActionKey: string | null = null
|
|
241
|
+
let repeatedErrorStreak = 0
|
|
242
|
+
|
|
243
|
+
// [Fase 6A / ACE-04] Blokir REPEATED_ACTION_ERROR bersifat PERSISTEN sampai
|
|
244
|
+
// ada bukti baru — sukses yang tidak relevan tidak boleh membuka jalan
|
|
245
|
+
// mengulang perintah yang sama secara buta.
|
|
246
|
+
let activeBlock: { fingerprint: string; actionKey: string; streak: number } | null = null
|
|
247
|
+
let newEvidenceAfterBlock = false
|
|
248
|
+
let justifiedRetries = 0
|
|
249
|
+
|
|
250
|
+
let consecutiveReadCalls = 0
|
|
251
|
+
|
|
252
|
+
const fileTrackers = new Map<string, FileHashTracker>()
|
|
253
|
+
const inflightPreHash = new Map<string, { relPath: string; preHash: string | null }>()
|
|
254
|
+
const pendingPost = new Set<Promise<unknown>>()
|
|
255
|
+
|
|
256
|
+
const evaluateBeforeCall: NoProgressDetector["evaluateBeforeCall"] = (call) => {
|
|
257
|
+
const name = String(call.name ?? "")
|
|
258
|
+
const actionKey = `${name}\0${canonicalArgsHash(call.args)}`
|
|
259
|
+
|
|
260
|
+
// Sinyal 1a: blokir persisten. Hanya boleh dibuka oleh SATU retry
|
|
261
|
+
// terjustifikasi setelah bukti diagnostik/mutasi baru, dengan hard cap.
|
|
262
|
+
if (activeBlock !== null && actionKey === activeBlock.actionKey) {
|
|
263
|
+
if (newEvidenceAfterBlock && justifiedRetries < maxNewEvidenceRetries) {
|
|
264
|
+
justifiedRetries += 1
|
|
265
|
+
newEvidenceAfterBlock = false
|
|
266
|
+
return { allowed: true }
|
|
267
|
+
}
|
|
268
|
+
return {
|
|
269
|
+
allowed: false,
|
|
270
|
+
kind: "NO_PROGRESS",
|
|
271
|
+
reason: "REPEATED_ACTION_ERROR",
|
|
272
|
+
message:
|
|
273
|
+
`[LOOP_GUARD kind=NO_PROGRESS reason=REPEATED_ACTION_ERROR count=${activeBlock.streak}] ` +
|
|
274
|
+
`Identical tool call failed ${activeBlock.streak} times consecutively with the same error. ` +
|
|
275
|
+
`Read fresh diagnostic evidence or change your approach before retrying.`,
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// Sinyal 1b: panggilan identik yang sudah gagal N kali berturut-turut.
|
|
280
|
+
if (
|
|
281
|
+
repeatedErrorStreak >= maxRepeatedErrors &&
|
|
282
|
+
lastErrorActionKey !== null &&
|
|
283
|
+
actionKey === lastErrorActionKey
|
|
284
|
+
) {
|
|
285
|
+
return {
|
|
286
|
+
allowed: false,
|
|
287
|
+
kind: "NO_PROGRESS",
|
|
288
|
+
reason: "REPEATED_ACTION_ERROR",
|
|
289
|
+
message:
|
|
290
|
+
`[LOOP_GUARD kind=NO_PROGRESS reason=REPEATED_ACTION_ERROR count=${repeatedErrorStreak}] ` +
|
|
291
|
+
`Identical tool call failed ${repeatedErrorStreak} times consecutively with the same error. ` +
|
|
292
|
+
`Stop repeating this command and revise your approach.`,
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// Sinyal 2: file target sudah terdeteksi dalam siklus revert berulang.
|
|
297
|
+
const contract = contractForTool(name)
|
|
298
|
+
if (contract?.sideEffectTier === "WORKSPACE_MUTATION") {
|
|
299
|
+
const a = (call.args ?? {}) as Record<string, unknown>
|
|
300
|
+
const rawPath =
|
|
301
|
+
typeof a.path === "string" ? a.path : typeof a.to === "string" ? a.to : undefined
|
|
302
|
+
if (rawPath) {
|
|
303
|
+
const key = normalizeTrackPath(rawPath)
|
|
304
|
+
const tracker = fileTrackers.get(key)
|
|
305
|
+
if (tracker?.oscillationMessage) {
|
|
306
|
+
return {
|
|
307
|
+
allowed: false,
|
|
308
|
+
kind: "OSCILLATION",
|
|
309
|
+
reason: "WORKSPACE_REVERT_CYCLE",
|
|
310
|
+
message: tracker.oscillationMessage,
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// Sinyal 3: read-only thrashing di postur kerja aktif.
|
|
317
|
+
const isPureRead = contract?.sideEffectTier === "PURE_READ"
|
|
318
|
+
if (isPureRead) {
|
|
319
|
+
if (getPosture() === "active") {
|
|
320
|
+
if (consecutiveReadCalls >= maxConsecutiveReadCalls) {
|
|
321
|
+
const observedCount = consecutiveReadCalls
|
|
322
|
+
// Reset setelah satu intervensi supaya model menerima peringatan keras
|
|
323
|
+
// sebagai tool error dan dapat langsung memanggil todo_write / bertindak.
|
|
324
|
+
consecutiveReadCalls = 0
|
|
325
|
+
return {
|
|
326
|
+
allowed: false,
|
|
327
|
+
kind: "NO_PROGRESS",
|
|
328
|
+
reason: "READ_ONLY_THRASHING",
|
|
329
|
+
message:
|
|
330
|
+
`[LOOP_GUARD kind=NO_PROGRESS reason=READ_ONLY_THRASHING count=${observedCount}] ` +
|
|
331
|
+
`Exceeded ${maxConsecutiveReadCalls} consecutive read-only tool calls without updating the plan, ` +
|
|
332
|
+
`mutating workspace state, or responding to the user. Formulate a plan (todo_write) or act on what you have read.`,
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
consecutiveReadCalls += 1
|
|
336
|
+
}
|
|
337
|
+
} else {
|
|
338
|
+
// Pembaruan rencana (`todo_write`), mutasi file/env, delegasi, atau ask_user
|
|
339
|
+
// memutus rentetan baca murni.
|
|
340
|
+
consecutiveReadCalls = 0
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
return { allowed: true }
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
const recordFileMutation: NoProgressDetector["recordFileMutation"] = (input) => {
|
|
347
|
+
const key = normalizeTrackPath(input.path)
|
|
348
|
+
if (!key) return { allowed: true }
|
|
349
|
+
// No-op write (isi tidak berubah) tidak dihitung sebagai transisi bolak-balik.
|
|
350
|
+
if (input.preTargetHash === input.postTargetHash) return { allowed: true }
|
|
351
|
+
|
|
352
|
+
let tracker = fileTrackers.get(key)
|
|
353
|
+
if (!tracker) {
|
|
354
|
+
const visits = new Map<string, number>()
|
|
355
|
+
const preK = hashKey(input.preTargetHash)
|
|
356
|
+
visits.set(preK, 1)
|
|
357
|
+
tracker = {
|
|
358
|
+
history: [input.preTargetHash],
|
|
359
|
+
visits,
|
|
360
|
+
oscillationMessage: null,
|
|
361
|
+
}
|
|
362
|
+
fileTrackers.set(key, tracker)
|
|
363
|
+
} else if (tracker.history[tracker.history.length - 1] !== input.preTargetHash) {
|
|
364
|
+
// Sinkronkan state awal bila file diubah dari luar di sela dua operasi.
|
|
365
|
+
const preK = hashKey(input.preTargetHash)
|
|
366
|
+
tracker.history.push(input.preTargetHash)
|
|
367
|
+
tracker.visits.set(preK, (tracker.visits.get(preK) ?? 0) + 1)
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
const postK = hashKey(input.postTargetHash)
|
|
371
|
+
tracker.history.push(input.postTargetHash)
|
|
372
|
+
const count = (tracker.visits.get(postK) ?? 0) + 1
|
|
373
|
+
tracker.visits.set(postK, count)
|
|
374
|
+
|
|
375
|
+
// `count - 1` = berapa kali file kembali ke hash yang sama setelah pernah
|
|
376
|
+
// meninggalkannya (H1 -> H2 -> H1 = 1 siklus; -> H2 -> H1 = 2 siklus).
|
|
377
|
+
const revertCycles = count - 1
|
|
378
|
+
if (revertCycles >= maxOscillations) {
|
|
379
|
+
const msg =
|
|
380
|
+
`[LOOP_GUARD kind=OSCILLATION reason=WORKSPACE_REVERT_CYCLE path=${key}] ` +
|
|
381
|
+
`File state is oscillating between identical versions without progress.`
|
|
382
|
+
tracker.oscillationMessage = msg
|
|
383
|
+
return {
|
|
384
|
+
allowed: false,
|
|
385
|
+
kind: "OSCILLATION",
|
|
386
|
+
reason: "WORKSPACE_REVERT_CYCLE",
|
|
387
|
+
message: msg,
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
return { allowed: true }
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
const flushPending = async (): Promise<void> => {
|
|
394
|
+
while (pendingPost.size > 0) {
|
|
395
|
+
await Promise.allSettled([...pendingPost])
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
return {
|
|
400
|
+
evaluateBeforeCall,
|
|
401
|
+
assertBeforeCall(call) {
|
|
402
|
+
const verdict = evaluateBeforeCall(call)
|
|
403
|
+
if (!verdict.allowed) {
|
|
404
|
+
throw new NoProgressError(verdict.kind, verdict.reason, verdict.message)
|
|
405
|
+
}
|
|
406
|
+
},
|
|
407
|
+
async capturePreMutation(call, workspaceRoot) {
|
|
408
|
+
const contract = contractForTool(call.name)
|
|
409
|
+
if (contract?.sideEffectTier !== "WORKSPACE_MUTATION" || !call.id) return
|
|
410
|
+
const rel = targetRelPathForTool(call.name, call.args, workspaceRoot)
|
|
411
|
+
if (!rel) return
|
|
412
|
+
const pre = await hashWorkspaceFile(resolve(workspaceRoot, rel))
|
|
413
|
+
if (pre.ok) {
|
|
414
|
+
inflightPreHash.set(call.id, { relPath: rel, preHash: pre.hash })
|
|
415
|
+
}
|
|
416
|
+
},
|
|
417
|
+
async beforeToolEffectCheck(call, workspaceRoot) {
|
|
418
|
+
await flushPending()
|
|
419
|
+
const verdict = evaluateBeforeCall(call)
|
|
420
|
+
if (!verdict.allowed) {
|
|
421
|
+
throw new NoProgressError(verdict.kind, verdict.reason, verdict.message)
|
|
422
|
+
}
|
|
423
|
+
const contract = contractForTool(call.name)
|
|
424
|
+
if (contract?.sideEffectTier !== "WORKSPACE_MUTATION" || !call.id) return
|
|
425
|
+
const rel = targetRelPathForTool(call.name, call.args, workspaceRoot)
|
|
426
|
+
if (!rel) return
|
|
427
|
+
const pre = await hashWorkspaceFile(resolve(workspaceRoot, rel))
|
|
428
|
+
if (pre.ok) {
|
|
429
|
+
inflightPreHash.set(call.id, { relPath: rel, preHash: pre.hash })
|
|
430
|
+
}
|
|
431
|
+
},
|
|
432
|
+
flushPending,
|
|
433
|
+
recordOutcome(input) {
|
|
434
|
+
const name = String(input.name ?? "")
|
|
435
|
+
const content = String(input.content ?? "")
|
|
436
|
+
// [LF-2] Jangan hitung error yang berasal dari LOOP_GUARD sendiri sebagai
|
|
437
|
+
// kegagalan tool. Hanya cocokkan pesan SINTETIS yang ber-prefix eksak di
|
|
438
|
+
// AWAL string (`[LOOP_GUARD kind=...]` — format nyata observable di modul
|
|
439
|
+
// ini), bukan substring di tengah output tool eksternal.
|
|
440
|
+
if (/^\[LOOP_GUARD kind=(?:NO_PROGRESS|OSCILLATION)\b/.test(content.trimStart())) {
|
|
441
|
+
return { allowed: true }
|
|
442
|
+
}
|
|
443
|
+
if (input.isError === true) {
|
|
444
|
+
const fp = computeActionErrorFingerprint(name, input.args, content)
|
|
445
|
+
const actionKey = `${name}\0${canonicalArgsHash(input.args)}`
|
|
446
|
+
if (fp === lastErrorFingerprint && actionKey === lastErrorActionKey) {
|
|
447
|
+
repeatedErrorStreak += 1
|
|
448
|
+
} else {
|
|
449
|
+
lastErrorFingerprint = fp
|
|
450
|
+
lastErrorActionKey = actionKey
|
|
451
|
+
repeatedErrorStreak = 1
|
|
452
|
+
}
|
|
453
|
+
if (repeatedErrorStreak >= maxRepeatedErrors) {
|
|
454
|
+
if (activeBlock === null || activeBlock.actionKey !== actionKey) {
|
|
455
|
+
// Blokir baru: buka budget retry dari nol.
|
|
456
|
+
activeBlock = { fingerprint: fp, actionKey, streak: repeatedErrorStreak }
|
|
457
|
+
justifiedRetries = 0
|
|
458
|
+
} else {
|
|
459
|
+
// Retry terjustifikasi gagal lagi: pertahankan budget yang sudah
|
|
460
|
+
// terpakai (hard cap) dan cabut bukti yang sudah dikonsumsi.
|
|
461
|
+
activeBlock = { ...activeBlock, streak: repeatedErrorStreak }
|
|
462
|
+
}
|
|
463
|
+
newEvidenceAfterBlock = false
|
|
464
|
+
return {
|
|
465
|
+
allowed: false,
|
|
466
|
+
kind: "NO_PROGRESS",
|
|
467
|
+
reason: "REPEATED_ACTION_ERROR",
|
|
468
|
+
message:
|
|
469
|
+
`[LOOP_GUARD kind=NO_PROGRESS reason=REPEATED_ACTION_ERROR count=${repeatedErrorStreak}] ` +
|
|
470
|
+
`Identical tool call failed ${repeatedErrorStreak} times consecutively with the same error. ` +
|
|
471
|
+
`Stop repeating this command and revise your approach.`,
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
return { allowed: true }
|
|
475
|
+
}
|
|
476
|
+
// Eksekusi sukses memutus streak error berulang. [Fase 6A / ACE-04]
|
|
477
|
+
// Sukses baca diagnostik atau mutasi workspace = bukti baru yang
|
|
478
|
+
// membenarkan SATU retry; sukses lain tidak membuka blokir.
|
|
479
|
+
if (activeBlock !== null) {
|
|
480
|
+
const tier = contractForTool(name)?.sideEffectTier
|
|
481
|
+
if (tier === "PURE_READ" || tier === "WORKSPACE_MUTATION") {
|
|
482
|
+
newEvidenceAfterBlock = true
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
lastErrorFingerprint = null
|
|
486
|
+
lastErrorActionKey = null
|
|
487
|
+
repeatedErrorStreak = 0
|
|
488
|
+
return { allowed: true }
|
|
489
|
+
},
|
|
490
|
+
recordFileMutation,
|
|
491
|
+
async completePostMutation(call, workspaceRoot) {
|
|
492
|
+
const task = (async (): Promise<NoProgressVerdict> => {
|
|
493
|
+
const entry = call.id ? inflightPreHash.get(call.id) : undefined
|
|
494
|
+
if (call.id) inflightPreHash.delete(call.id)
|
|
495
|
+
if (!entry || call.isError === true) return { allowed: true }
|
|
496
|
+
const post = await hashWorkspaceFile(resolve(workspaceRoot, entry.relPath))
|
|
497
|
+
if (!post.ok) return { allowed: true }
|
|
498
|
+
return recordFileMutation({
|
|
499
|
+
path: entry.relPath,
|
|
500
|
+
preTargetHash: entry.preHash,
|
|
501
|
+
postTargetHash: post.hash,
|
|
502
|
+
})
|
|
503
|
+
})()
|
|
504
|
+
pendingPost.add(task)
|
|
505
|
+
try {
|
|
506
|
+
return await task
|
|
507
|
+
} finally {
|
|
508
|
+
pendingPost.delete(task)
|
|
509
|
+
}
|
|
510
|
+
},
|
|
511
|
+
noteVerificationPassed() {
|
|
512
|
+
// Verifikasi hijau menandai titik tumpu baru: bersihkan riwayat osilasi
|
|
513
|
+
// masa lalu namun pertahankan hash terakhir sebagai baseline baru.
|
|
514
|
+
for (const [, tracker] of fileTrackers) {
|
|
515
|
+
const latest = tracker.history[tracker.history.length - 1] ?? null
|
|
516
|
+
const visits = new Map<string, number>()
|
|
517
|
+
visits.set(hashKey(latest), 1)
|
|
518
|
+
tracker.history = [latest]
|
|
519
|
+
tracker.visits = visits
|
|
520
|
+
tracker.oscillationMessage = null
|
|
521
|
+
}
|
|
522
|
+
// [Fase 6A / ACE-04] Verifikasi hijau adalah kemajuan nyata: blokir
|
|
523
|
+
// repeated-error tidak lagi relevan.
|
|
524
|
+
activeBlock = null
|
|
525
|
+
newEvidenceAfterBlock = false
|
|
526
|
+
justifiedRetries = 0
|
|
527
|
+
lastErrorFingerprint = null
|
|
528
|
+
lastErrorActionKey = null
|
|
529
|
+
repeatedErrorStreak = 0
|
|
530
|
+
},
|
|
531
|
+
noteAssistantResponse() {
|
|
532
|
+
consecutiveReadCalls = 0
|
|
533
|
+
},
|
|
534
|
+
reset() {
|
|
535
|
+
lastErrorFingerprint = null
|
|
536
|
+
lastErrorActionKey = null
|
|
537
|
+
repeatedErrorStreak = 0
|
|
538
|
+
consecutiveReadCalls = 0
|
|
539
|
+
activeBlock = null
|
|
540
|
+
newEvidenceAfterBlock = false
|
|
541
|
+
justifiedRetries = 0
|
|
542
|
+
fileTrackers.clear()
|
|
543
|
+
inflightPreHash.clear()
|
|
544
|
+
},
|
|
545
|
+
snapshot() {
|
|
546
|
+
const oscillatingPaths: string[] = []
|
|
547
|
+
for (const [p, t] of fileTrackers) {
|
|
548
|
+
if (t.oscillationMessage) oscillatingPaths.push(p)
|
|
549
|
+
}
|
|
550
|
+
return {
|
|
551
|
+
repeatedErrorStreak,
|
|
552
|
+
consecutiveReadCalls,
|
|
553
|
+
oscillatingPaths,
|
|
554
|
+
newEvidenceSinceFailure: newEvidenceAfterBlock,
|
|
555
|
+
justifiedRetriesUsed: justifiedRetries,
|
|
556
|
+
}
|
|
557
|
+
},
|
|
558
|
+
}
|
|
559
|
+
}
|
package/src/policy/permission.ts
CHANGED
|
@@ -26,6 +26,8 @@ export type PermissionMode = "auto" | "readonly" | "plan" | "allow-all" | "ask"
|
|
|
26
26
|
export type PermissionAsk = (call: {
|
|
27
27
|
name: string
|
|
28
28
|
args?: unknown
|
|
29
|
+
/** [Fase 2 / LOOP-INV-08] Identitas pemanggilan untuk pengikatan approval. */
|
|
30
|
+
id?: string
|
|
29
31
|
}) => Promise<"allow" | "deny" | "always">
|
|
30
32
|
|
|
31
33
|
const READONLY_TOOLS = new Set([
|
|
@@ -82,14 +84,8 @@ const NO_PROMPT_TOOLS = new Set(["todo_write", "submit_result", "bash_output", "
|
|
|
82
84
|
// `ask_user` di-gate: model yang bisa bertanya tanpa batas bisa membanjiri
|
|
83
85
|
// user (atau memancing jawaban kredensial) — persetujuan sekali per sesi
|
|
84
86
|
// via `[a] Always` tetap tersedia.
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
"mcp_call",
|
|
88
|
-
"mcp_read",
|
|
89
|
-
"mcp_prompt",
|
|
90
|
-
"git_commit",
|
|
91
|
-
"ask_user",
|
|
92
|
-
])
|
|
87
|
+
// [Fase 2 / TOOL-01] Diimpor dari registry kontrak tool (satu sumber).
|
|
88
|
+
import { GATED_TOOLS } from "./tool-contract.ts"
|
|
93
89
|
|
|
94
90
|
// Denylist bash kini di src/policy/bash-guard.ts — pemeriksaan dilakukan pada
|
|
95
91
|
// bentuk TERNORMALISASI (quote dibuang, variabel sederhana disubstitusi), bukan
|
package/src/policy/pricing.ts
CHANGED
|
@@ -239,7 +239,7 @@ export async function syncPricing(url: string = MODELS_DEV_URL): Promise<SyncRes
|
|
|
239
239
|
const hostname = new URL(url).hostname
|
|
240
240
|
if (await isPrivateHostWithDns(hostname)) throw new Error(`private host rejected: ${hostname}`)
|
|
241
241
|
} catch (e) {
|
|
242
|
-
if (
|
|
242
|
+
if (e instanceof Error && e.message.includes("private host")) throw e
|
|
243
243
|
}
|
|
244
244
|
const res = await fetch(url, {
|
|
245
245
|
signal: AbortSignal.timeout(LIMITS.PRICING_FETCH_TIMEOUT_MS * 4),
|
|
@@ -254,7 +254,7 @@ export async function syncPricing(url: string = MODELS_DEV_URL): Promise<SyncRes
|
|
|
254
254
|
if (await isPrivateHostWithDns(nextHost))
|
|
255
255
|
throw new Error(`private host rejected: ${nextHost}`)
|
|
256
256
|
} catch (e) {
|
|
257
|
-
if (
|
|
257
|
+
if (e instanceof Error && e.message.includes("private host")) throw e
|
|
258
258
|
}
|
|
259
259
|
}
|
|
260
260
|
throw new Error(`models.dev → redirect ${res.status} not followed`)
|
|
@@ -296,6 +296,20 @@ export async function syncPricing(url: string = MODELS_DEV_URL): Promise<SyncRes
|
|
|
296
296
|
* Overlay (models.dev) diperiksa lebih dulu karena lebih baru; bawaan menjadi
|
|
297
297
|
* jaring pengaman.
|
|
298
298
|
*/
|
|
299
|
+
// [Audit #2 C.F4] Cache urutan kunci per-tabel (terpanjang dulu). `Object.keys`
|
|
300
|
+
// + sort semula dijalankan setiap `findPrice` (per event token). BUILTIN_PRICING
|
|
301
|
+
// adalah const (cache stabil); overlay di-REASSIGN (bukan di-mutasi), jadi
|
|
302
|
+
// WeakMap otomatis miss saat overlay diganti objek baru.
|
|
303
|
+
const priceKeyOrderCache = new WeakMap<Record<string, ModelPrice>, string[]>()
|
|
304
|
+
function priceKeysDescLength(table: Record<string, ModelPrice>): string[] {
|
|
305
|
+
let keys = priceKeyOrderCache.get(table)
|
|
306
|
+
if (!keys) {
|
|
307
|
+
keys = Object.keys(table).sort((a, b) => b.length - a.length)
|
|
308
|
+
priceKeyOrderCache.set(table, keys)
|
|
309
|
+
}
|
|
310
|
+
return keys
|
|
311
|
+
}
|
|
312
|
+
|
|
299
313
|
export function findPrice(
|
|
300
314
|
model: string,
|
|
301
315
|
overlayMap: Record<string, ModelPrice> = overlay ?? {},
|
|
@@ -320,7 +334,7 @@ export function findPrice(
|
|
|
320
334
|
const segments = m.split(/[/:]/)
|
|
321
335
|
|
|
322
336
|
for (const table of [overlayMap, BUILTIN_PRICING]) {
|
|
323
|
-
const keys =
|
|
337
|
+
const keys = priceKeysDescLength(table)
|
|
324
338
|
for (const k of keys) {
|
|
325
339
|
const kl = k.toLowerCase()
|
|
326
340
|
for (const s of segments) {
|