minicode-ai 0.14.0 → 0.14.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/cli/args.ts +16 -3
- package/cli/auto-update.ts +32 -2
- package/cli/commands/exec.ts +9 -0
- package/cli/index.ts +31 -13
- package/cli/setup.ts +31 -19
- package/cli/tui.ts +63 -40
- package/docs/OUTPUT_PROTOCOL_SPEC.md +6 -0
- package/docs/OUTPUT_RENDERING_SPEC.md +28 -4
- package/docs/README.md +2 -2
- package/docs/TERMINAL_CONTRACT.md +52 -26
- package/docs/agents.md +2 -2
- package/docs/choosing-mode.md +20 -13
- package/docs/cli.md +11 -11
- package/docs/environment.md +3 -3
- package/docs/getting-started.md +14 -12
- package/docs/glossary.md +1 -1
- package/docs/mcp-lsp.md +1 -1
- package/docs/policy-sandbox.md +7 -1
- package/docs/security-model.md +2 -2
- package/docs/security.md +7 -1
- package/docs/tools.md +4 -4
- package/docs/verify-benchmark.md +16 -0
- package/package.json +1 -3
- package/src/app/mentions.ts +4 -3
- package/src/app/session.ts +19 -9
- package/src/app/tool-layer.ts +10 -3
- package/src/constants.ts +17 -0
- package/src/lib/git-hardening.ts +27 -22
- package/src/lib/safe-open.ts +73 -19
- package/src/lib/trusted-exec.ts +7 -4
- package/src/mcp/client.ts +34 -9
- package/src/mcp/transport.ts +96 -42
- package/src/memory/files.ts +15 -4
- package/src/memory/vector.ts +5 -1
- package/src/policy/context.ts +21 -13
- package/src/policy/permission.ts +75 -16
- package/src/policy/tool-contract.ts +21 -10
- package/src/policy/update-check.ts +83 -6
- package/src/policy/usage.ts +17 -7
- package/src/policy/work-mode.ts +51 -17
- package/src/presentation/adapter.ts +64 -2
- package/src/presentation/events.ts +6 -0
- package/src/presentation/model.ts +1 -0
- package/src/presentation/projection.ts +2 -0
- package/src/presentation/reducer.ts +1 -0
- package/src/providers/anthropic.ts +52 -19
- package/src/providers/guards.ts +98 -13
- package/src/providers/responses.ts +61 -23
- package/src/providers/sse-bounds.ts +170 -0
- package/src/repo/repomap.ts +10 -11
- package/src/runtime/execution-backend.ts +7 -8
- package/src/sandbox/docker.ts +113 -9
- package/src/session/checkpoint.ts +9 -2
- package/src/session/persistence.ts +5 -2
- package/src/session/verification.ts +55 -16
- package/src/skills/loader.ts +16 -3
- package/src/tools/bash.ts +6 -3
- package/src/tools/code_run.ts +6 -5
- package/src/tools/context.ts +8 -0
- package/src/tools/delete_file.ts +2 -1
- package/src/tools/edit.ts +2 -1
- package/src/tools/git.ts +128 -54
- package/src/tools/glob.ts +2 -1
- package/src/tools/grep.ts +31 -6
- package/src/tools/lsp.ts +5 -4
- package/src/tools/mcp_call.ts +3 -1
- package/src/tools/memory.ts +175 -180
- package/src/tools/move_file.ts +2 -1
- package/src/tools/patch.ts +2 -1
- package/src/tools/read_file.ts +94 -1
- package/src/tools/read_image.ts +2 -1
- package/src/tools/task.ts +2 -1
- package/src/tools/todo.ts +4 -5
- package/src/tools/web_fetch.ts +28 -12
- package/src/tools/web_search.ts +28 -9
- package/src/tools/write_file.ts +2 -1
- package/src/ui/assistant/simple.ts +72 -3
- package/src/ui/footer.ts +17 -12
- package/src/ui/i18n/en.ts +6 -3
- package/src/ui/i18n/id.ts +6 -3
- package/src/ui/render/width.ts +107 -79
- package/src/ui/runtime/screen.ts +49 -37
- package/src/ui/tui/app.ts +261 -209
- package/src/ui/tui/transcript.ts +39 -0
- package/CHANGELOG.md +0 -1167
- package/docs/PLAN_UIUX_V6.md +0 -209
- package/docs/changelog.md +0 -3
package/src/policy/usage.ts
CHANGED
|
@@ -237,10 +237,8 @@ export function watchContextWindowLimit(opts: {
|
|
|
237
237
|
bus: EventBus
|
|
238
238
|
/** Batas window konteks (W). Bila 0/undefined → no-op. */
|
|
239
239
|
windowTokens: number
|
|
240
|
-
/**
|
|
241
|
-
|
|
242
|
-
/** Token output turn berjalan (dari usage collector). */
|
|
243
|
-
getOutputTokens: () => number
|
|
240
|
+
/** Snapshot token request provider aktif; window berlaku per request. */
|
|
241
|
+
getRequestTokens: () => { inputTokens: number; outputTokens: number } | null
|
|
244
242
|
onOver: (allowed: number, actual: number) => void
|
|
245
243
|
}): () => void {
|
|
246
244
|
const W = opts.windowTokens
|
|
@@ -248,9 +246,12 @@ export function watchContextWindowLimit(opts: {
|
|
|
248
246
|
let fired = false
|
|
249
247
|
const check = () => {
|
|
250
248
|
if (fired) return
|
|
251
|
-
const
|
|
252
|
-
|
|
253
|
-
|
|
249
|
+
const request = opts.getRequestTokens()
|
|
250
|
+
// Belum ada usage untuk request aktif: jangan memakai snapshot request
|
|
251
|
+
// sebelumnya atau total token kumulatif turn sebagai pengganti.
|
|
252
|
+
if (!request) return
|
|
253
|
+
const allowedOutput = Math.max(256, Math.floor(W - request.inputTokens))
|
|
254
|
+
const output = request.outputTokens
|
|
254
255
|
if (output > allowedOutput) {
|
|
255
256
|
fired = true
|
|
256
257
|
opts.onOver(allowedOutput, output)
|
|
@@ -556,6 +557,15 @@ export function createUsageCollector(
|
|
|
556
557
|
getTurnCount: () => sessionTurns,
|
|
557
558
|
/** [Fase 3 / CTX-03] Laporan token terakhir dari provider untuk kalibrasi. */
|
|
558
559
|
lastProviderTokens: () => lastProviderUsage,
|
|
560
|
+
/** Snapshot request provider aktif; null di antara request agar watcher
|
|
561
|
+
* window tidak keliru memakai total kumulatif turn/sesi. */
|
|
562
|
+
currentRequestTokens: () =>
|
|
563
|
+
pendingRequestTokens
|
|
564
|
+
? {
|
|
565
|
+
inputTokens: pendingRequestTokens.inputTokens,
|
|
566
|
+
outputTokens: pendingRequestTokens.outputTokens,
|
|
567
|
+
}
|
|
568
|
+
: null,
|
|
559
569
|
modelUsed: () => ({ effective: effectiveModel, provider: effectiveProvider }),
|
|
560
570
|
reset: () => {
|
|
561
571
|
// [Fase 7 / Live #2] reset() = batas turn. `pendingRequestTokens` masih
|
package/src/policy/work-mode.ts
CHANGED
|
@@ -11,8 +11,13 @@
|
|
|
11
11
|
// menduplikasi READONLY_TOOLS atau membangun engine kedua.
|
|
12
12
|
|
|
13
13
|
import type { PermissionHandler, ToolCall } from "#minicore"
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
14
|
+
import type { PermissionMode } from "./permission.ts"
|
|
15
|
+
import {
|
|
16
|
+
LOCAL_READONLY_TOOL_NAMES,
|
|
17
|
+
NETWORK_READ_TOOL_NAMES,
|
|
18
|
+
PLAN_EXTRA_TOOL_NAMES,
|
|
19
|
+
READONLY_TOOL_NAMES,
|
|
20
|
+
} from "./tool-contract.ts"
|
|
16
21
|
|
|
17
22
|
export type WorkMode = "DISCUSS" | "PLAN" | "EXECUTE"
|
|
18
23
|
|
|
@@ -76,6 +81,24 @@ function ceilingFor(workMode: RestrictiveWorkMode, baseMode: PermissionMode): "r
|
|
|
76
81
|
return baseMode === "allowlist" || baseMode === "readonly" ? "readonly" : "plan"
|
|
77
82
|
}
|
|
78
83
|
|
|
84
|
+
// Tool Access Policy — ceiling capability WorkMode dihitung LANGSUNG dari
|
|
85
|
+
// registry kontrak tool (satu sumber), bukan lewat handler PermissionMode
|
|
86
|
+
// `readonly`/`plan` (yang dulunya diduplikasi sebagai primitif ceiling).
|
|
87
|
+
//
|
|
88
|
+
// - DISCUSS → tepat 16 `LOCAL_READONLY_TOOL_NAMES` (network read ditolak
|
|
89
|
+
// terpisah di check() dengan alasan khusus).
|
|
90
|
+
// - PLAN → 18 `READONLY_TOOL_NAMES` (+ `PLAN_EXTRA_TOOL_NAMES`), atau
|
|
91
|
+
// read-only saja bila PM sudah `readonly`/`allowlist` (lebih ketat).
|
|
92
|
+
function ceilingAllows(
|
|
93
|
+
name: string,
|
|
94
|
+
workMode: RestrictiveWorkMode,
|
|
95
|
+
baseMode: PermissionMode,
|
|
96
|
+
): boolean {
|
|
97
|
+
if (workMode === "DISCUSS") return LOCAL_READONLY_TOOL_NAMES.includes(name)
|
|
98
|
+
if (baseMode === "readonly" || baseMode === "allowlist") return READONLY_TOOL_NAMES.has(name)
|
|
99
|
+
return READONLY_TOOL_NAMES.has(name) || PLAN_EXTRA_TOOL_NAMES.has(name)
|
|
100
|
+
}
|
|
101
|
+
|
|
79
102
|
export function createWorkModePermissionHandler(opts: {
|
|
80
103
|
workMode: WorkMode
|
|
81
104
|
base: PermissionHandler
|
|
@@ -86,15 +109,26 @@ export function createWorkModePermissionHandler(opts: {
|
|
|
86
109
|
// mengkonsultasi handler per tool call, jadi __setWorkMode runtime menggeser
|
|
87
110
|
// ceiling tanpa mengganti handler. EXECUTE = delegasi base (perilaku identik).
|
|
88
111
|
let wm: WorkMode = opts.workMode
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
112
|
+
// Handler deny ceiling — hanya untuk seam describeDenial (alasan yang sama
|
|
113
|
+
// dengan perilaku lama: "read-only mode" / "plan mode"). Tidak ada lagi
|
|
114
|
+
// handler PermissionMode `readonly`/`plan` sebagai primitif ceiling.
|
|
115
|
+
const ceilingDenyHandlers: Record<"readonly" | "plan", PermissionHandler> = {
|
|
116
|
+
readonly: {
|
|
117
|
+
async check() {
|
|
118
|
+
return "deny"
|
|
119
|
+
},
|
|
120
|
+
describeDenial() {
|
|
121
|
+
return "read-only mode"
|
|
122
|
+
},
|
|
123
|
+
},
|
|
124
|
+
plan: {
|
|
125
|
+
async check() {
|
|
126
|
+
return "deny"
|
|
127
|
+
},
|
|
128
|
+
describeDenial() {
|
|
129
|
+
return "plan mode"
|
|
130
|
+
},
|
|
131
|
+
},
|
|
98
132
|
}
|
|
99
133
|
const discussNetworkDeny: PermissionHandler = {
|
|
100
134
|
async check() {
|
|
@@ -157,12 +191,12 @@ export function createWorkModePermissionHandler(opts: {
|
|
|
157
191
|
// (PLAN × allowlist/readonly = read-only), bukan membekukan yang lama.
|
|
158
192
|
// Baca WorkMode sekarang (`wm` mutable) — __setWorkMode runtime menggeser
|
|
159
193
|
// ceiling DISCUSS↔PLAN.
|
|
160
|
-
const
|
|
161
|
-
|
|
162
|
-
// (
|
|
163
|
-
|
|
164
|
-
if (
|
|
165
|
-
rememberDeny(call,
|
|
194
|
+
const baseMode = ctrl.__getMode()
|
|
195
|
+
const ceilingKind = ceilingFor(wm, baseMode)
|
|
196
|
+
// Ceiling DULU (Tool Access Policy): operasi di luar ceiling tak boleh
|
|
197
|
+
// memicu prompt base (requirement S2.1 #1) — ceiling tak pernah prompt.
|
|
198
|
+
if (!ceilingAllows(call.name, wm, baseMode)) {
|
|
199
|
+
rememberDeny(call, ceilingDenyHandlers[ceilingKind])
|
|
166
200
|
return "deny"
|
|
167
201
|
}
|
|
168
202
|
// Di dalam ceiling: keputusan mutlak handler PM asli (termasuk prompt
|
|
@@ -355,6 +355,11 @@ export function createPresentationAdapter(
|
|
|
355
355
|
let currentStep = 0
|
|
356
356
|
let reasoningText = ""
|
|
357
357
|
let reasoningTruncated = false
|
|
358
|
+
let activeProviderAttempt: {
|
|
359
|
+
id: number
|
|
360
|
+
reasoningLength: number
|
|
361
|
+
reasoningTruncated: boolean
|
|
362
|
+
} | null = null
|
|
358
363
|
const toolStarts = new Map<string, number>()
|
|
359
364
|
const openTools = new Map<
|
|
360
365
|
string,
|
|
@@ -445,6 +450,7 @@ export function createPresentationAdapter(
|
|
|
445
450
|
})
|
|
446
451
|
reasoningText = ""
|
|
447
452
|
reasoningTruncated = false
|
|
453
|
+
activeProviderAttempt = null
|
|
448
454
|
}
|
|
449
455
|
// Pemetaan task domain → plan presentational. Sengaja memakai
|
|
450
456
|
// `normalizeTodos` (pemilik semantik domain) alih-alih memetakan status
|
|
@@ -729,6 +735,7 @@ export function createPresentationAdapter(
|
|
|
729
735
|
currentStep = 0
|
|
730
736
|
reasoningText = ""
|
|
731
737
|
reasoningTruncated = false
|
|
738
|
+
activeProviderAttempt = null
|
|
732
739
|
turnStartTs = Date.now()
|
|
733
740
|
resetTurnCounters()
|
|
734
741
|
publish({
|
|
@@ -1023,10 +1030,59 @@ export function createPresentationAdapter(
|
|
|
1023
1030
|
|
|
1024
1031
|
sub("provider:text", (e: { text?: unknown }) => {
|
|
1025
1032
|
if (typeof e?.text !== "string" || !e.text) return
|
|
1026
|
-
publish({
|
|
1033
|
+
publish({
|
|
1034
|
+
...base(currentTurn),
|
|
1035
|
+
type: "model.delta",
|
|
1036
|
+
turnId: currentTurn,
|
|
1037
|
+
delta: e.text,
|
|
1038
|
+
...(activeProviderAttempt ? { attemptId: activeProviderAttempt.id } : {}),
|
|
1039
|
+
})
|
|
1027
1040
|
})
|
|
1028
1041
|
|
|
1029
1042
|
sub("provider:extension", (e: { kind?: unknown; data?: unknown }) => {
|
|
1043
|
+
if (e?.kind === "minicode:attempt") {
|
|
1044
|
+
const data = e.data as {
|
|
1045
|
+
phase?: unknown
|
|
1046
|
+
attemptId?: unknown
|
|
1047
|
+
hadVisibleOutput?: unknown
|
|
1048
|
+
} | null
|
|
1049
|
+
if (
|
|
1050
|
+
typeof data?.attemptId === "number" &&
|
|
1051
|
+
Number.isSafeInteger(data.attemptId) &&
|
|
1052
|
+
data.attemptId > 0
|
|
1053
|
+
) {
|
|
1054
|
+
if (data.phase === "started") {
|
|
1055
|
+
activeProviderAttempt = {
|
|
1056
|
+
id: data.attemptId,
|
|
1057
|
+
reasoningLength: reasoningText.length,
|
|
1058
|
+
reasoningTruncated,
|
|
1059
|
+
}
|
|
1060
|
+
} else if (activeProviderAttempt?.id === data.attemptId && data.phase === "completed") {
|
|
1061
|
+
activeProviderAttempt = null
|
|
1062
|
+
} else if (activeProviderAttempt?.id === data.attemptId && data.phase === "invalidated") {
|
|
1063
|
+
reasoningText = reasoningText.slice(0, activeProviderAttempt.reasoningLength)
|
|
1064
|
+
reasoningTruncated = activeProviderAttempt.reasoningTruncated
|
|
1065
|
+
activeProviderAttempt = null
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
if (
|
|
1069
|
+
data?.phase === "invalidated" &&
|
|
1070
|
+
data.hadVisibleOutput === true &&
|
|
1071
|
+
typeof data.attemptId === "number" &&
|
|
1072
|
+
Number.isSafeInteger(data.attemptId)
|
|
1073
|
+
) {
|
|
1074
|
+
publish({
|
|
1075
|
+
...base(currentTurn),
|
|
1076
|
+
type: "diagnostic.raised",
|
|
1077
|
+
turnId: currentTurn,
|
|
1078
|
+
category: "PROVIDER_ATTEMPT_INVALIDATED",
|
|
1079
|
+
severity: "warning",
|
|
1080
|
+
message: `Provider attempt ${data.attemptId} streamed partial output; it was discarded and is excluded from the final answer.`,
|
|
1081
|
+
attemptId: data.attemptId,
|
|
1082
|
+
})
|
|
1083
|
+
}
|
|
1084
|
+
return
|
|
1085
|
+
}
|
|
1030
1086
|
if (e?.kind === "error") {
|
|
1031
1087
|
const data = e.data as { message?: unknown; error?: unknown } | null
|
|
1032
1088
|
const message =
|
|
@@ -1055,7 +1111,13 @@ export function createPresentationAdapter(
|
|
|
1055
1111
|
} else {
|
|
1056
1112
|
reasoningTruncated = true
|
|
1057
1113
|
}
|
|
1058
|
-
publish({
|
|
1114
|
+
publish({
|
|
1115
|
+
...base(currentTurn),
|
|
1116
|
+
type: "reasoning.delta",
|
|
1117
|
+
turnId: currentTurn,
|
|
1118
|
+
delta: text,
|
|
1119
|
+
...(activeProviderAttempt ? { attemptId: activeProviderAttempt.id } : {}),
|
|
1120
|
+
})
|
|
1059
1121
|
})
|
|
1060
1122
|
|
|
1061
1123
|
sub("context:compacted", (e: { reason?: unknown }) => {
|
|
@@ -196,6 +196,8 @@ export interface TurnCancelledEvent extends Base {
|
|
|
196
196
|
export interface ModelDeltaEvent extends Base {
|
|
197
197
|
type: "model.delta"
|
|
198
198
|
delta: string
|
|
199
|
+
/** Guard-local provider stream attempt; invalidation diagnostics reference it. */
|
|
200
|
+
attemptId?: number
|
|
199
201
|
}
|
|
200
202
|
export interface ModelCompletedEvent extends Base {
|
|
201
203
|
type: "model.completed"
|
|
@@ -206,6 +208,8 @@ export interface ModelCompletedEvent extends Base {
|
|
|
206
208
|
export interface ReasoningDeltaEvent extends Base {
|
|
207
209
|
type: "reasoning.delta"
|
|
208
210
|
delta: string
|
|
211
|
+
/** Guard-local provider stream attempt; failed reasoning is rolled back. */
|
|
212
|
+
attemptId?: number
|
|
209
213
|
}
|
|
210
214
|
export interface ReasoningCompletedEvent extends Base {
|
|
211
215
|
type: "reasoning.completed"
|
|
@@ -374,6 +378,8 @@ export interface DiagnosticRaisedEvent extends Base {
|
|
|
374
378
|
category: string
|
|
375
379
|
severity: SemanticSeverity
|
|
376
380
|
message: string
|
|
381
|
+
/** Provider attempt whose live output was invalidated, when applicable. */
|
|
382
|
+
attemptId?: number
|
|
377
383
|
cause?: string
|
|
378
384
|
action?: string
|
|
379
385
|
}
|
|
@@ -546,6 +546,7 @@ export interface MachineEventInput {
|
|
|
546
546
|
summary?: unknown
|
|
547
547
|
promptRef?: string
|
|
548
548
|
delta?: unknown
|
|
549
|
+
attemptId?: unknown
|
|
549
550
|
text?: unknown
|
|
550
551
|
truncated?: boolean
|
|
551
552
|
toolSummary?: unknown
|
|
@@ -780,6 +781,7 @@ export function machinePayload(event: MachineEventInput): Record<string, unknown
|
|
|
780
781
|
put("truncated", typeof event.truncated === "boolean" ? event.truncated : undefined)
|
|
781
782
|
put("toolSummary", asString(event.toolSummary))
|
|
782
783
|
put("durationMs", asNumber(event.durationMs))
|
|
784
|
+
put("attemptId", asNumber(event.attemptId))
|
|
783
785
|
put("tsStart", asNumber(event.tsStart))
|
|
784
786
|
put(
|
|
785
787
|
"paths",
|
|
@@ -750,6 +750,7 @@ export function reduce(
|
|
|
750
750
|
category: event.category,
|
|
751
751
|
severity: event.severity,
|
|
752
752
|
message: event.message,
|
|
753
|
+
...(event.attemptId !== undefined ? { attemptId: event.attemptId } : {}),
|
|
753
754
|
...(event.cause ? { cause: event.cause } : {}),
|
|
754
755
|
...(event.action ? { action: event.action } : {}),
|
|
755
756
|
}
|
|
@@ -5,6 +5,12 @@ import type { ToolSchema } from "#minicore/core/tool.ts"
|
|
|
5
5
|
import type { Content, Message } from "#minicore/core/types.ts"
|
|
6
6
|
import { LIMITS } from "../constants.ts"
|
|
7
7
|
import { thinkingFamily } from "./effort.ts"
|
|
8
|
+
import {
|
|
9
|
+
appendToolArgument,
|
|
10
|
+
boundedSseBody,
|
|
11
|
+
parseProviderToolArguments,
|
|
12
|
+
readProviderErrorBody,
|
|
13
|
+
} from "./sse-bounds.ts"
|
|
8
14
|
|
|
9
15
|
export interface AnthropicConfig {
|
|
10
16
|
id?: string
|
|
@@ -128,13 +134,17 @@ export function createAnthropicProvider(config: AnthropicConfig): ModelProvider
|
|
|
128
134
|
throw new ProviderError("network", e instanceof Error ? e.message : String(e))
|
|
129
135
|
}
|
|
130
136
|
if (!response.ok) {
|
|
131
|
-
const txt = await response
|
|
137
|
+
const txt = await readProviderErrorBody(response).catch(() => "")
|
|
132
138
|
throw toAnthropicError(response.status, txt, response.headers)
|
|
133
139
|
}
|
|
134
140
|
if (!response.body) throw new ProviderError("network", "empty response body")
|
|
135
141
|
|
|
136
142
|
// buffer for tool inputs across deltas — per-stream (was global, now isolated)
|
|
137
|
-
const pendingTools = new Map<
|
|
143
|
+
const pendingTools = new Map<
|
|
144
|
+
number,
|
|
145
|
+
{ id: string; name: string; args: string; argsBytes: number }
|
|
146
|
+
>()
|
|
147
|
+
let pendingToolArgBytes = 0
|
|
138
148
|
|
|
139
149
|
// Anthropic SSE: event: ...\ndata: {...}
|
|
140
150
|
let currentEvent = ""
|
|
@@ -204,7 +214,12 @@ export function createAnthropicProvider(config: AnthropicConfig): ModelProvider
|
|
|
204
214
|
// [ST-5] Non-null guard: blok malformed tanpa id/name dikunci, bukan
|
|
205
215
|
// dipaksa `block.id!`/`block.name!` yang bisa menyimpan undefined.
|
|
206
216
|
if (typeof block.id !== "string" || typeof block.name !== "string") continue
|
|
207
|
-
pendingTools.set(raw.index ?? 0, {
|
|
217
|
+
pendingTools.set(raw.index ?? 0, {
|
|
218
|
+
id: block.id,
|
|
219
|
+
name: block.name,
|
|
220
|
+
args: "",
|
|
221
|
+
argsBytes: 0,
|
|
222
|
+
})
|
|
208
223
|
}
|
|
209
224
|
}
|
|
210
225
|
if (evType === "content_block_delta") {
|
|
@@ -212,7 +227,18 @@ export function createAnthropicProvider(config: AnthropicConfig): ModelProvider
|
|
|
212
227
|
if (d?.type === "input_json_delta") {
|
|
213
228
|
const idx = raw.index ?? 0
|
|
214
229
|
const p = pendingTools.get(idx)
|
|
215
|
-
if (p)
|
|
230
|
+
if (p) {
|
|
231
|
+
const next = appendToolArgument(
|
|
232
|
+
p.args,
|
|
233
|
+
p.argsBytes,
|
|
234
|
+
d.partial_json ?? "",
|
|
235
|
+
pendingToolArgBytes,
|
|
236
|
+
"Anthropic",
|
|
237
|
+
)
|
|
238
|
+
p.args = next.value
|
|
239
|
+
p.argsBytes = next.bytes
|
|
240
|
+
pendingToolArgBytes = next.pendingBytes
|
|
241
|
+
}
|
|
216
242
|
}
|
|
217
243
|
if (d?.type === "thinking_delta" && typeof d.thinking === "string") {
|
|
218
244
|
yield { type: "extension", kind: "reasoning", data: { text: d.thinking } }
|
|
@@ -222,17 +248,18 @@ export function createAnthropicProvider(config: AnthropicConfig): ModelProvider
|
|
|
222
248
|
const idx = raw.index ?? 0
|
|
223
249
|
const p = pendingTools.get(idx)
|
|
224
250
|
if (p) {
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
args = p.args ? JSON.parse(p.args) : {}
|
|
228
|
-
} catch {
|
|
229
|
-
args = { raw: p.args }
|
|
230
|
-
}
|
|
251
|
+
const args = parseProviderToolArguments(p.args, "Anthropic")
|
|
252
|
+
pendingToolArgBytes -= p.argsBytes
|
|
231
253
|
yield { type: "tool_call", id: p.id, name: p.name, args }
|
|
232
254
|
pendingTools.delete(idx)
|
|
233
255
|
}
|
|
234
256
|
}
|
|
235
257
|
}
|
|
258
|
+
if (pendingTools.size > 0)
|
|
259
|
+
throw new ProviderError(
|
|
260
|
+
"invalid_request",
|
|
261
|
+
"Anthropic stream ended with incomplete tool arguments",
|
|
262
|
+
)
|
|
236
263
|
},
|
|
237
264
|
}
|
|
238
265
|
return provider
|
|
@@ -392,15 +419,19 @@ async function* sseAnthropic(
|
|
|
392
419
|
body: ReadableStream<Uint8Array>,
|
|
393
420
|
signal: AbortSignal,
|
|
394
421
|
): AsyncGenerator<{ event: string; data: unknown }> {
|
|
395
|
-
const
|
|
422
|
+
const boundedBody = boundedSseBody(body, signal, "Anthropic")
|
|
423
|
+
const reader = boundedBody.getReader()
|
|
396
424
|
const decoder = new TextDecoder()
|
|
397
425
|
let buffer = ""
|
|
398
426
|
let evt = ""
|
|
427
|
+
let reachedEof = false
|
|
399
428
|
try {
|
|
400
429
|
while (true) {
|
|
401
|
-
if (signal.aborted) throw new DOMException("Aborted", "AbortError")
|
|
402
430
|
const { done, value } = await reader.read()
|
|
403
|
-
if (done)
|
|
431
|
+
if (done) {
|
|
432
|
+
reachedEof = true
|
|
433
|
+
break
|
|
434
|
+
}
|
|
404
435
|
buffer += decoder.decode(value, { stream: true })
|
|
405
436
|
let idx = buffer.indexOf("\n")
|
|
406
437
|
while (idx >= 0) {
|
|
@@ -410,18 +441,20 @@ async function* sseAnthropic(
|
|
|
410
441
|
else if (line.startsWith("data:")) {
|
|
411
442
|
const payload = line.slice(5).trim()
|
|
412
443
|
if (payload) {
|
|
444
|
+
let data: unknown
|
|
413
445
|
try {
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
446
|
+
data = JSON.parse(payload)
|
|
447
|
+
} catch {
|
|
448
|
+
throw new ProviderError("invalid_request", "Anthropic returned malformed SSE JSON")
|
|
449
|
+
}
|
|
450
|
+
yield { event: evt, data }
|
|
417
451
|
}
|
|
418
|
-
} else if (line === "")
|
|
419
|
-
evt = ""
|
|
420
|
-
}
|
|
452
|
+
} else if (line === "") evt = ""
|
|
421
453
|
idx = buffer.indexOf("\n")
|
|
422
454
|
}
|
|
423
455
|
}
|
|
424
456
|
} finally {
|
|
457
|
+
if (!reachedEof) await reader.cancel().catch(() => {})
|
|
425
458
|
reader.releaseLock()
|
|
426
459
|
}
|
|
427
460
|
}
|
package/src/providers/guards.ts
CHANGED
|
@@ -10,19 +10,30 @@
|
|
|
10
10
|
// Abort parent diteruskan apa adanya (tak pernah ditelan/dikonversi); hanya
|
|
11
11
|
// timeout MILIK guard yang diklasifikasikan ulang menjadi ProviderError
|
|
12
12
|
// "server" agar tak dikira network-putus atau abort-user.
|
|
13
|
+
import { Buffer } from "node:buffer"
|
|
13
14
|
import { abortError, ProviderError } from "#minicore/core/errors.ts"
|
|
14
15
|
import type { ModelProvider, ProviderEvent, StreamRequest } from "#minicore/core/provider.ts"
|
|
15
16
|
import { LIMITS } from "../constants.ts"
|
|
16
17
|
|
|
17
18
|
export function withStreamGuards(
|
|
18
19
|
provider: ModelProvider,
|
|
19
|
-
opts: {
|
|
20
|
+
opts: {
|
|
21
|
+
timeoutMs?: number
|
|
22
|
+
maxTextChars?: number
|
|
23
|
+
maxReasonChars?: number
|
|
24
|
+
maxToolArgBytes?: number
|
|
25
|
+
maxTotalToolArgBytes?: number
|
|
26
|
+
} = {},
|
|
20
27
|
): ModelProvider {
|
|
21
28
|
const timeoutMs = opts.timeoutMs ?? LIMITS.PROVIDER_REQUEST_TIMEOUT_MS
|
|
22
29
|
const maxTextChars = opts.maxTextChars ?? LIMITS.PROVIDER_TEXT_MAX_CHARS
|
|
23
30
|
// Reasoning = bukan bagian jawaban; cap agresif (2MB logis ≈ 500k token —
|
|
24
31
|
// jauh di atas reasoning sah mana pun, jauh di bawah OOM).
|
|
25
32
|
const maxReasonChars = opts.maxReasonChars ?? LIMITS.PROVIDER_REASON_MAX_CHARS
|
|
33
|
+
const maxToolArgBytes = opts.maxToolArgBytes ?? LIMITS.PROVIDER_TOOL_ARGS_MAX_BYTES
|
|
34
|
+
const maxTotalToolArgBytes =
|
|
35
|
+
opts.maxTotalToolArgBytes ?? LIMITS.PROVIDER_TOOL_ARGS_PENDING_MAX_BYTES
|
|
36
|
+
let nextAttemptId = 0
|
|
26
37
|
return {
|
|
27
38
|
...provider,
|
|
28
39
|
id: provider.id,
|
|
@@ -31,27 +42,76 @@ export function withStreamGuards(
|
|
|
31
42
|
},
|
|
32
43
|
async *stream(request: StreamRequest, signal: AbortSignal): AsyncIterable<ProviderEvent> {
|
|
33
44
|
if (signal.aborted) throw abortError(signal)
|
|
45
|
+
const attemptId = ++nextAttemptId
|
|
46
|
+
const attemptEvent = (
|
|
47
|
+
phase: "started" | "completed" | "invalidated",
|
|
48
|
+
fields: { hadVisibleOutput?: boolean; reason?: string } = {},
|
|
49
|
+
): ProviderEvent => ({
|
|
50
|
+
type: "extension",
|
|
51
|
+
kind: "minicode:attempt",
|
|
52
|
+
data: { phase, attemptId, ...fields },
|
|
53
|
+
})
|
|
54
|
+
yield attemptEvent("started")
|
|
34
55
|
const ctl = new AbortController()
|
|
35
56
|
const onParentAbort = () => ctl.abort(signal.reason)
|
|
36
57
|
if (signal.aborted) ctl.abort(signal.reason)
|
|
37
58
|
else signal.addEventListener("abort", onParentAbort, { once: true })
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
59
|
+
let timedOut = false
|
|
60
|
+
const timer = setTimeout(() => {
|
|
61
|
+
timedOut = true
|
|
62
|
+
ctl.abort(new Error(`provider request timed out after ${timeoutMs}ms`))
|
|
63
|
+
}, timeoutMs)
|
|
42
64
|
// Jangan menahan exit proses bila turn sudah selesai dari sisi lain.
|
|
43
65
|
;(timer as unknown as { unref?: () => void }).unref?.()
|
|
44
|
-
let timedOut = false
|
|
45
|
-
const onLinkedAbort = () => {
|
|
46
|
-
if (!signal.aborted) timedOut = true
|
|
47
|
-
}
|
|
48
|
-
ctl.signal.addEventListener("abort", onLinkedAbort, { once: true })
|
|
49
66
|
let textChars = 0
|
|
50
67
|
let reasonChars = 0
|
|
68
|
+
let toolArgumentBytes = 0
|
|
51
69
|
let marked = false
|
|
52
70
|
let reasonMarked = false
|
|
71
|
+
let finishReason: "stop" | "tool_calls" | "length" | "abort" | "error" | undefined
|
|
72
|
+
let hadVisibleOutput = false
|
|
73
|
+
let invalidated = false
|
|
53
74
|
try {
|
|
54
75
|
for await (const ev of provider.stream(request, ctl.signal)) {
|
|
76
|
+
if (
|
|
77
|
+
finishReason !== undefined &&
|
|
78
|
+
(ev.type === "text" || ev.type === "tool_call" || ev.type === "finish")
|
|
79
|
+
) {
|
|
80
|
+
throw new ProviderError("network", "provider emitted content after finish")
|
|
81
|
+
}
|
|
82
|
+
if (ev.type === "finish") {
|
|
83
|
+
finishReason = ev.reason
|
|
84
|
+
if (ev.reason !== "stop" && ev.reason !== "tool_calls") {
|
|
85
|
+
invalidated = true
|
|
86
|
+
yield attemptEvent("invalidated", {
|
|
87
|
+
hadVisibleOutput,
|
|
88
|
+
reason: `finish:${ev.reason}`,
|
|
89
|
+
})
|
|
90
|
+
}
|
|
91
|
+
yield ev
|
|
92
|
+
continue
|
|
93
|
+
}
|
|
94
|
+
if (ev.type === "tool_call") {
|
|
95
|
+
let serialized: string
|
|
96
|
+
try {
|
|
97
|
+
serialized = JSON.stringify(ev.args ?? {}) ?? ""
|
|
98
|
+
} catch {
|
|
99
|
+
throw new ProviderError(
|
|
100
|
+
"invalid_request",
|
|
101
|
+
"provider returned unserializable tool arguments",
|
|
102
|
+
)
|
|
103
|
+
}
|
|
104
|
+
const argBytes = Buffer.byteLength(serialized, "utf8")
|
|
105
|
+
toolArgumentBytes += argBytes
|
|
106
|
+
if (argBytes > maxToolArgBytes || toolArgumentBytes > maxTotalToolArgBytes) {
|
|
107
|
+
const error = new ProviderError(
|
|
108
|
+
"invalid_request",
|
|
109
|
+
"provider tool arguments exceed configured byte limits",
|
|
110
|
+
)
|
|
111
|
+
ctl.abort(error)
|
|
112
|
+
throw error
|
|
113
|
+
}
|
|
114
|
+
}
|
|
55
115
|
// F-16 diperluas (investigasi Phase 5): extension "reasoning" juga
|
|
56
116
|
// diakumulasi kernel (loop `reasoning += ev.data.text` TANPA cap) —
|
|
57
117
|
// dulu hanya ev.type "text" yang dipotong, sehingga reasoning stream
|
|
@@ -64,13 +124,18 @@ export function withStreamGuards(
|
|
|
64
124
|
textChars += ev.text.length
|
|
65
125
|
if (textChars > maxTextChars) {
|
|
66
126
|
const keep = ev.text.slice(0, ev.text.length - (textChars - maxTextChars))
|
|
67
|
-
if (keep)
|
|
127
|
+
if (keep) {
|
|
128
|
+
hadVisibleOutput = true
|
|
129
|
+
yield { type: "text", text: keep }
|
|
130
|
+
}
|
|
68
131
|
if (!marked) {
|
|
69
132
|
marked = true
|
|
133
|
+
hadVisibleOutput = true
|
|
70
134
|
yield { type: "text", text: "\n… [provider text truncated: turn cap exceeded]" }
|
|
71
135
|
}
|
|
72
136
|
continue
|
|
73
137
|
}
|
|
138
|
+
hadVisibleOutput = true
|
|
74
139
|
} else if (ev.type === "extension" && ev.kind === "reasoning") {
|
|
75
140
|
const d = ev.data as { text?: unknown } | undefined
|
|
76
141
|
if (typeof d?.text === "string" && d.text) {
|
|
@@ -78,9 +143,13 @@ export function withStreamGuards(
|
|
|
78
143
|
reasonChars += d.text.length
|
|
79
144
|
if (reasonChars > maxReasonChars) {
|
|
80
145
|
const keep = d.text.slice(0, d.text.length - (reasonChars - maxReasonChars))
|
|
81
|
-
if (keep)
|
|
146
|
+
if (keep) {
|
|
147
|
+
hadVisibleOutput = true
|
|
148
|
+
yield { type: "extension", kind: "reasoning", data: { text: keep } }
|
|
149
|
+
}
|
|
82
150
|
if (!reasonMarked) {
|
|
83
151
|
reasonMarked = true
|
|
152
|
+
hadVisibleOutput = true
|
|
84
153
|
yield {
|
|
85
154
|
type: "extension",
|
|
86
155
|
kind: "reasoning",
|
|
@@ -89,18 +158,34 @@ export function withStreamGuards(
|
|
|
89
158
|
}
|
|
90
159
|
continue
|
|
91
160
|
}
|
|
161
|
+
hadVisibleOutput = true
|
|
92
162
|
}
|
|
93
163
|
}
|
|
94
164
|
yield ev
|
|
95
165
|
}
|
|
166
|
+
if (finishReason === "stop" || finishReason === "tool_calls") {
|
|
167
|
+
yield attemptEvent("completed", { hadVisibleOutput })
|
|
168
|
+
} else if (!invalidated) {
|
|
169
|
+
invalidated = true
|
|
170
|
+
yield attemptEvent("invalidated", {
|
|
171
|
+
hadVisibleOutput,
|
|
172
|
+
reason: "missing-finish",
|
|
173
|
+
})
|
|
174
|
+
}
|
|
96
175
|
} catch (e) {
|
|
176
|
+
if (!invalidated) {
|
|
177
|
+
invalidated = true
|
|
178
|
+
yield attemptEvent("invalidated", {
|
|
179
|
+
hadVisibleOutput,
|
|
180
|
+
reason: timedOut ? "timeout" : "stream-error",
|
|
181
|
+
})
|
|
182
|
+
}
|
|
97
183
|
if (timedOut)
|
|
98
184
|
throw new ProviderError("server", `provider request timed out after ${timeoutMs}ms`)
|
|
99
185
|
throw e
|
|
100
186
|
} finally {
|
|
101
187
|
clearTimeout(timer)
|
|
102
188
|
signal.removeEventListener("abort", onParentAbort)
|
|
103
|
-
ctl.signal.removeEventListener("abort", onLinkedAbort)
|
|
104
189
|
}
|
|
105
190
|
},
|
|
106
191
|
}
|