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,141 @@
|
|
|
1
|
+
// P13.1 — Ring buffer diagnostik runtime: TERBATAS + truncation TERLIHAT.
|
|
2
|
+
//
|
|
3
|
+
// Kenapa buffer, kenapa berbatas: runtime long-running menghasilkan banyak
|
|
4
|
+
// kejadian diagnostik, dan "simpan semua" = memori tak terbatas (kelas yang
|
|
5
|
+
// sudah dikejar di daemon: MAX_QUEUE_PER_CONN). Batas keras di sini: paling
|
|
6
|
+
// banyak 512 rekaman ATAU 1 MiB, mana yang tercapai lebih dulu.
|
|
7
|
+
//
|
|
8
|
+
// Kenapa truncation WAJIB observable: buffer yang diam-diam memotong history
|
|
9
|
+
// membuat konsumen menyimpulkan "tidak terjadi apa-apa" saat sebenarnya terjadi
|
|
10
|
+
// 10.000 kejadian yang hilang. Jadi jumlah rekaman yang dibuang ikut dilaporkan
|
|
11
|
+
// dan nomor urut rekaman tertua yang masih tersimpan ikut terlihat — celah
|
|
12
|
+
// history bisa dibaca, bukan sekadar perform.
|
|
13
|
+
//
|
|
14
|
+
// INI BUKAN antrean durable dan BUKAN task store: buffer in-memory untuk
|
|
15
|
+
// diagnosis, hilang saat proses mati — itu memang yang dimaksudkan. Tidak ada
|
|
16
|
+
// state baru yang bertahan lintas restart.
|
|
17
|
+
|
|
18
|
+
/** Batas jumlah rekaman (keputusan pemilik). */
|
|
19
|
+
export const MAX_DIAGNOSTIC_RECORDS = 512
|
|
20
|
+
|
|
21
|
+
/** Batas ukuran total (keputusan pemilik): 1 MiB, mana yang tercapai lebih dulu. */
|
|
22
|
+
export const MAX_DIAGNOSTIC_BYTES = 1024 * 1024
|
|
23
|
+
|
|
24
|
+
/** Satu rekaman diagnostik. */
|
|
25
|
+
export interface DiagnosticRecord {
|
|
26
|
+
/** Nomor urut monoton dalam buffer (mulai dari 1). */
|
|
27
|
+
readonly seq: number
|
|
28
|
+
/** Waktu pencatatan (ms epoch, dari sumber jam yang disuntikkan). */
|
|
29
|
+
readonly at: number
|
|
30
|
+
/** Jenis kejadian (label pendek, tanpa data sensitif). */
|
|
31
|
+
readonly kind: string
|
|
32
|
+
/** Keterangan ringkas (tanpa rahasia). */
|
|
33
|
+
readonly message: string
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Potret buffer pada satu saat. */
|
|
37
|
+
export interface DiagnosticBufferSnapshot {
|
|
38
|
+
/** Rekaman yang masih tersimpan, urut lama→baru. */
|
|
39
|
+
readonly records: readonly DiagnosticRecord[]
|
|
40
|
+
/** Berapa rekaman yang dibuang karena batas terlampaui. */
|
|
41
|
+
readonly dropped: number
|
|
42
|
+
/** True bila ada rekaman yang dibuang (truncation terlihat). */
|
|
43
|
+
readonly truncated: boolean
|
|
44
|
+
/** Perkiraan ukuran byte yang sedang disimpan. */
|
|
45
|
+
readonly bytes: number
|
|
46
|
+
/** Seq rekaman tertua yang masih tersimpan (1 = tak ada yang dibuang). */
|
|
47
|
+
readonly sinceSeq: number
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Antarmuka buffer diagnostik. */
|
|
51
|
+
export interface DiagnosticBuffer {
|
|
52
|
+
/** Catat satu kejadian. Melebihi batas → rekaman tertua dibuang (dan dilaporkan). */
|
|
53
|
+
record(kind: string, message?: string): void
|
|
54
|
+
/** Potret saat ini (salinan — tak bisa dimutasi dari luar). */
|
|
55
|
+
snapshot(): DiagnosticBufferSnapshot
|
|
56
|
+
/** Kosongkan buffer (dan reset penanda truncation). */
|
|
57
|
+
clear(): void
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Perkiraan overhead per rekaman (kunci objek + penanda), agar hitungan byte realistis. */
|
|
61
|
+
const RECORD_OVERHEAD_BYTES = 64
|
|
62
|
+
|
|
63
|
+
const encoder = new TextEncoder()
|
|
64
|
+
|
|
65
|
+
function byteLength(text: string): number {
|
|
66
|
+
return encoder.encode(text).length
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface DiagnosticBufferOptions {
|
|
70
|
+
/** Batas rekaman (default MAX_DIAGNOSTIC_RECORDS). */
|
|
71
|
+
readonly maxRecords?: number
|
|
72
|
+
/** Batas byte (default MAX_DIAGNOSTIC_BYTES). */
|
|
73
|
+
readonly maxBytes?: number
|
|
74
|
+
/** Sumber jam (default Date.now) — disuntik agar tes deterministik. */
|
|
75
|
+
readonly now?: () => number
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function positiveInt(value: number | undefined, fallback: number): number {
|
|
79
|
+
if (value === undefined || !Number.isFinite(value)) return fallback
|
|
80
|
+
const n = Math.floor(value)
|
|
81
|
+
return n > 0 ? n : fallback
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Buat buffer diagnostik berbatas.
|
|
86
|
+
*
|
|
87
|
+
* Pembuangan terjadi dari YANG LAMA (FIFO) sehingga history terbaru selalu
|
|
88
|
+
* ada. Batas byte ditegakkan ketat: satu rekaman yang lebih besar dari batas
|
|
89
|
+
* pun ikut dibuang (dan dihitung sebagai `dropped`) — memeliharanya berarti
|
|
90
|
+
* melanggar batas memori yang justru dilindungi di sini.
|
|
91
|
+
*/
|
|
92
|
+
export function createDiagnosticBuffer(opts: DiagnosticBufferOptions = {}): DiagnosticBuffer {
|
|
93
|
+
const maxRecords = positiveInt(opts.maxRecords, MAX_DIAGNOSTIC_RECORDS)
|
|
94
|
+
const maxBytes = positiveInt(opts.maxBytes, MAX_DIAGNOSTIC_BYTES)
|
|
95
|
+
const now = opts.now ?? Date.now
|
|
96
|
+
|
|
97
|
+
const records: DiagnosticRecord[] = []
|
|
98
|
+
let bytes = 0
|
|
99
|
+
let dropped = 0
|
|
100
|
+
let nextSeq = 1
|
|
101
|
+
|
|
102
|
+
const sizeOf = (kind: string, message: string): number =>
|
|
103
|
+
RECORD_OVERHEAD_BYTES + byteLength(kind) + byteLength(message)
|
|
104
|
+
|
|
105
|
+
const evict = (): void => {
|
|
106
|
+
while (records.length > 0 && (records.length > maxRecords || bytes > maxBytes)) {
|
|
107
|
+
const oldest = records.shift()
|
|
108
|
+
if (!oldest) break
|
|
109
|
+
bytes -= sizeOf(oldest.kind, oldest.message)
|
|
110
|
+
dropped += 1
|
|
111
|
+
}
|
|
112
|
+
if (bytes < 0) bytes = 0
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return {
|
|
116
|
+
record(kind: string, message = ""): void {
|
|
117
|
+
const safeKind = typeof kind === "string" ? kind : ""
|
|
118
|
+
const safeMessage = typeof message === "string" ? message : ""
|
|
119
|
+
records.push({ seq: nextSeq, at: now(), kind: safeKind, message: safeMessage })
|
|
120
|
+
nextSeq += 1
|
|
121
|
+
bytes += sizeOf(safeKind, safeMessage)
|
|
122
|
+
evict()
|
|
123
|
+
},
|
|
124
|
+
snapshot(): DiagnosticBufferSnapshot {
|
|
125
|
+
const first = records[0]
|
|
126
|
+
return {
|
|
127
|
+
records: records.map((r) => ({ ...r })),
|
|
128
|
+
dropped,
|
|
129
|
+
truncated: dropped > 0,
|
|
130
|
+
bytes,
|
|
131
|
+
sinceSeq: first ? first.seq : nextSeq,
|
|
132
|
+
}
|
|
133
|
+
},
|
|
134
|
+
clear(): void {
|
|
135
|
+
records.length = 0
|
|
136
|
+
bytes = 0
|
|
137
|
+
dropped = 0
|
|
138
|
+
nextSeq = 1
|
|
139
|
+
},
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
// M4 — RuntimeHost lifecycle: HOST FSM eksplisit, BUKAN execution FSM.
|
|
2
|
+
//
|
|
3
|
+
// Kenapa berkas ini berubah (P1 ADR-001/010, M4): facade M3 hanya punya guard
|
|
4
|
+
// boolean (started/closed/latch) sehingga urutan shutdown/drain/close implisit.
|
|
5
|
+
// M4 memberi Host lifecycle internal yang deterministik agar admission dan
|
|
6
|
+
// shutdown dapat diputuskan tanpa menebak — tanpa mengambil alih lifecycle
|
|
7
|
+
// individual Execution (otoritas itu milik Kernel, M8).
|
|
8
|
+
//
|
|
9
|
+
// Distinction yang dikunci (jangan dicampur tanpa ADR baru):
|
|
10
|
+
// Host FSM : CREATED → STARTING → READY → DRAINING → CLOSING → CLOSED
|
|
11
|
+
// = lifecycle RuntimeHost (apakah host menerima request baru).
|
|
12
|
+
// Eksekusi : CREATED → ADMITTED → RUNNING → … (M8, BUKAN di sini).
|
|
13
|
+
// Host tak pernah memutuskan COMPLETED/FAILED/CANCELLED/TIMED_OUT eksekusi.
|
|
14
|
+
//
|
|
15
|
+
// Aturan yang dikunci:
|
|
16
|
+
// - Delegation-only M3 dipertahankan (run = delegate terinjeksi, verbatim).
|
|
17
|
+
// - Admission HANYA di READY; DRAINING/CLOSING/CLOSED/STARTING/CREATED menolak
|
|
18
|
+
// deterministik (DRAINING dihitung admissionRejectedDuringDrain).
|
|
19
|
+
// - run() baru HANYA di READY; in-flight (promise delegate yang sudah jalan)
|
|
20
|
+
// tak tersentuh host (host tak memegang cancellation — itu M4-out/M8).
|
|
21
|
+
// - shutdown(): READY→DRAINING (+DRAINING→DRAINING idempoten); hook sekali,
|
|
22
|
+
// timeout-bound, gagal → tetap DRAINING + degraded + rethrow (tak pernah
|
|
23
|
+
// resurrect ke READY).
|
|
24
|
+
// - close(): READY/DRAINING→CLOSING→CLOSED; hook sekali; gagal → tetap CLOSED
|
|
25
|
+
// + degraded + rethrow; close ganda/join = no-op; CREATED→throw.
|
|
26
|
+
// - Hook timeout default 30 dtk = CONSERVATIVE BORROWED bound (orde sama dengan
|
|
27
|
+
// timeout MCP/bash 30 dtk di repo), BUKAN angka terukur — UNKNOWN register:
|
|
28
|
+
// butuh kalibrasi beban; configurable via options. Tanpa bound, hook gantung
|
|
29
|
+
// = shutdown gantung; dengan bound, keterlambatan = degraded, bukan hang.
|
|
30
|
+
// - Signal seam: shutdown()/close() aman dipanggil dari callback sinyal
|
|
31
|
+
// (idempoten, bounded, tak throw pada pengulangan); Host TIDAK memasang
|
|
32
|
+
// process.on sendiri dan TIDAK memutuskan SIGINT=abort vs shutdown (itu
|
|
33
|
+
// policy mode CLI: TUI vs non-interaktif). Wiring milik composition root.
|
|
34
|
+
// - Tanpa import baru: tetap observation plane (M1/M2) — H12 dipertahankan.
|
|
35
|
+
|
|
36
|
+
import {
|
|
37
|
+
createChildCorrelation,
|
|
38
|
+
createRootCorrelation,
|
|
39
|
+
type ExecutionCorrelation,
|
|
40
|
+
type ExecutionKind,
|
|
41
|
+
} from "./execution-id.ts"
|
|
42
|
+
import {
|
|
43
|
+
createExecutionRegistry,
|
|
44
|
+
type ExecutionRegistry,
|
|
45
|
+
type ExecutionSnapshot,
|
|
46
|
+
type ExecutionSummary,
|
|
47
|
+
} from "./execution-registry.ts"
|
|
48
|
+
|
|
49
|
+
/** Delegate eksekusi existing (mis. session.run). Dipilih pemanggil, bukan Host. */
|
|
50
|
+
export type HostRunDelegate<TInput = unknown, TResult = unknown> = (
|
|
51
|
+
input: TInput,
|
|
52
|
+
opts: { signal?: AbortSignal },
|
|
53
|
+
) => Promise<TResult>
|
|
54
|
+
|
|
55
|
+
export interface RuntimeHostHooks {
|
|
56
|
+
/** Dipanggil SEKALI saat transisi ke READY (sync; throw = tetap CREATED). */
|
|
57
|
+
readonly onStart?: () => void
|
|
58
|
+
/** Dipanggil SEKALI saat shutdown() pertama (boleh async; timeout-bound). */
|
|
59
|
+
readonly onShutdown?: () => void | Promise<void>
|
|
60
|
+
/** Dipanggil SEKALI saat close() pertama (boleh async; timeout-bound). */
|
|
61
|
+
readonly onClose?: () => void | Promise<void>
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Host lifecycle — HANYA lifecycle host, bukan execution (M8 memisahkan). */
|
|
65
|
+
export type HostLifecycleState =
|
|
66
|
+
| "CREATED"
|
|
67
|
+
| "STARTING"
|
|
68
|
+
| "READY"
|
|
69
|
+
| "DRAINING"
|
|
70
|
+
| "CLOSING"
|
|
71
|
+
| "CLOSED"
|
|
72
|
+
|
|
73
|
+
export interface RuntimeHostOptions {
|
|
74
|
+
/** Registry observasi (default: instance baru milik host). */
|
|
75
|
+
readonly registry?: ExecutionRegistry
|
|
76
|
+
/** Runner default (mis. session.run existing). Absent = run() throw loud. */
|
|
77
|
+
readonly runner?: HostRunDelegate
|
|
78
|
+
readonly hooks?: RuntimeHostHooks
|
|
79
|
+
/** Bound hook shutdown ms (default 30_000 borrowed-conservative; UNKNOWN kalibrasi). */
|
|
80
|
+
readonly shutdownHookTimeoutMs?: number
|
|
81
|
+
/** Bound hook close ms (default 30_000 borrowed-conservative; UNKNOWN kalibrasi). */
|
|
82
|
+
readonly closeHookTimeoutMs?: number
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface HostAdmissionSpec {
|
|
86
|
+
readonly kind: ExecutionKind
|
|
87
|
+
/** Owner menurut arsitektur; bukan authority user input (otorisasi tetap policy). */
|
|
88
|
+
readonly ownerId: string
|
|
89
|
+
readonly parent?: ExecutionCorrelation
|
|
90
|
+
readonly deadlineRef?: number
|
|
91
|
+
readonly budgetRef?: string
|
|
92
|
+
readonly backendRef?: string
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface HostMetrics {
|
|
96
|
+
readonly state: HostLifecycleState
|
|
97
|
+
readonly started: boolean
|
|
98
|
+
readonly closed: boolean
|
|
99
|
+
readonly shutdownRequested: boolean
|
|
100
|
+
readonly admitted: number
|
|
101
|
+
readonly runs: number
|
|
102
|
+
readonly runErrors: number
|
|
103
|
+
readonly closes: number
|
|
104
|
+
readonly shutdowns: number
|
|
105
|
+
readonly registryEntries: number
|
|
106
|
+
readonly startCount: number
|
|
107
|
+
readonly admissionRejectedDuringDrain: number
|
|
108
|
+
readonly hookFailures: number
|
|
109
|
+
readonly lastShutdownDurationMs: number | null
|
|
110
|
+
readonly lastCloseDurationMs: number | null
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export interface RuntimeHost {
|
|
114
|
+
/** CREATED→STARTING→READY (onStart throw = tetap CREATED + error propagates). */
|
|
115
|
+
start(): void
|
|
116
|
+
/** Lifecycle state host saat ini (observasi; bukan execution state). */
|
|
117
|
+
state(): HostLifecycleState
|
|
118
|
+
/**
|
|
119
|
+
* Observasi admission — HANYA di READY. BUKAN admission FSM otoritatif
|
|
120
|
+
* (itu M4-gate + M8): membuat korelasi M1 + snapshot "ADMITTED" M2.
|
|
121
|
+
*/
|
|
122
|
+
admit(spec: HostAdmissionSpec): ExecutionCorrelation
|
|
123
|
+
/**
|
|
124
|
+
* Delegasikan eksekusi — HANYA di READY. Hasil/error verbatim; tanpa retry.
|
|
125
|
+
*/
|
|
126
|
+
run<TInput, TResult>(
|
|
127
|
+
input: TInput,
|
|
128
|
+
opts?: { runner?: HostRunDelegate<TInput, TResult>; signal?: AbortSignal },
|
|
129
|
+
): Promise<TResult>
|
|
130
|
+
/** Observasi: frozen copy atau undefined. */
|
|
131
|
+
inspect(executionId: string): ExecutionSnapshot | undefined
|
|
132
|
+
/** Observasi: ringkasan terurut. */
|
|
133
|
+
list(): ExecutionSummary[]
|
|
134
|
+
/** Metrik host + registry (copy). */
|
|
135
|
+
metrics(): { host: HostMetrics; registryEntries: number }
|
|
136
|
+
/** READY→DRAINING (idempoten); hook sekali, timeout-bound, gagal→degraded. */
|
|
137
|
+
shutdown(): Promise<{
|
|
138
|
+
shutdownRequested: true
|
|
139
|
+
observedEntries: number
|
|
140
|
+
state: HostLifecycleState
|
|
141
|
+
}>
|
|
142
|
+
/** READY/DRAINING→CLOSING→CLOSED; hook sekali; idempoten; gagal→degraded. */
|
|
143
|
+
close(): Promise<void>
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Batas hook konservatif default (ms). BORROWED, bukan terukur: orde sama
|
|
148
|
+
* dengan timeout MCP/bash 30 dtk yang sudah ada di repo. UNKNOWN register:
|
|
149
|
+
* kalibrasi beban diperlukan sebelum dianggap SLA.
|
|
150
|
+
*/
|
|
151
|
+
export const DEFAULT_HOOK_TIMEOUT_MS = 30_000
|
|
152
|
+
|
|
153
|
+
async function runHookBounded(
|
|
154
|
+
hook: (() => void | Promise<void>) | undefined,
|
|
155
|
+
timeoutMs: number,
|
|
156
|
+
label: string,
|
|
157
|
+
): Promise<{ ok: boolean; durationMs: number }> {
|
|
158
|
+
const t0 = Date.now()
|
|
159
|
+
if (!hook) return { ok: true, durationMs: Date.now() - t0 }
|
|
160
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
161
|
+
try {
|
|
162
|
+
await Promise.race([
|
|
163
|
+
Promise.resolve().then(() => hook()),
|
|
164
|
+
new Promise<never>((_, reject) => {
|
|
165
|
+
timer = setTimeout(
|
|
166
|
+
() => reject(new Error(`runtime-host: ${label} hook timeout`)),
|
|
167
|
+
timeoutMs,
|
|
168
|
+
)
|
|
169
|
+
}),
|
|
170
|
+
])
|
|
171
|
+
return { ok: true, durationMs: Date.now() - t0 }
|
|
172
|
+
} catch {
|
|
173
|
+
return { ok: false, durationMs: Date.now() - t0 }
|
|
174
|
+
} finally {
|
|
175
|
+
if (timer !== undefined) clearTimeout(timer)
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export function createRuntimeHost(opts: RuntimeHostOptions = {}): RuntimeHost {
|
|
180
|
+
const registry = opts.registry ?? createExecutionRegistry()
|
|
181
|
+
const boundRunner = opts.runner
|
|
182
|
+
const hooks = opts.hooks
|
|
183
|
+
const shutdownHookTimeoutMs = opts.shutdownHookTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS
|
|
184
|
+
const closeHookTimeoutMs = opts.closeHookTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS
|
|
185
|
+
// CREATED = factory return, belum start (bagian rantai CREATION→STARTING).
|
|
186
|
+
let state: HostLifecycleState = "CREATED"
|
|
187
|
+
let hooksStarted = false
|
|
188
|
+
let hooksClosed = false
|
|
189
|
+
let hooksShutdown = false
|
|
190
|
+
const m = {
|
|
191
|
+
admitted: 0,
|
|
192
|
+
runs: 0,
|
|
193
|
+
runErrors: 0,
|
|
194
|
+
closes: 0,
|
|
195
|
+
shutdowns: 0,
|
|
196
|
+
startCount: 0,
|
|
197
|
+
admissionRejectedDuringDrain: 0,
|
|
198
|
+
hookFailures: 0,
|
|
199
|
+
lastShutdownDurationMs: null as number | null,
|
|
200
|
+
lastCloseDurationMs: null as number | null,
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const metricsSnapshot = (): { host: HostMetrics; registryEntries: number } => ({
|
|
204
|
+
host: {
|
|
205
|
+
state,
|
|
206
|
+
started: state !== "CREATED" && state !== "STARTING",
|
|
207
|
+
closed: state === "CLOSED",
|
|
208
|
+
shutdownRequested: state === "DRAINING" || state === "CLOSING" || state === "CLOSED",
|
|
209
|
+
admitted: m.admitted,
|
|
210
|
+
runs: m.runs,
|
|
211
|
+
runErrors: m.runErrors,
|
|
212
|
+
closes: m.closes,
|
|
213
|
+
shutdowns: m.shutdowns,
|
|
214
|
+
registryEntries: registry.size(),
|
|
215
|
+
startCount: m.startCount,
|
|
216
|
+
admissionRejectedDuringDrain: m.admissionRejectedDuringDrain,
|
|
217
|
+
hookFailures: m.hookFailures,
|
|
218
|
+
lastShutdownDurationMs: m.lastShutdownDurationMs,
|
|
219
|
+
lastCloseDurationMs: m.lastCloseDurationMs,
|
|
220
|
+
},
|
|
221
|
+
registryEntries: registry.size(),
|
|
222
|
+
})
|
|
223
|
+
|
|
224
|
+
return {
|
|
225
|
+
start(): void {
|
|
226
|
+
if (state === "READY") return
|
|
227
|
+
if (state === "CLOSED" || state === "CLOSING" || state === "DRAINING")
|
|
228
|
+
throw new Error(`runtime-host: start() in ${state} (no resurrection)`)
|
|
229
|
+
if (state === "STARTING") throw new Error("runtime-host: reentrant start() in STARTING")
|
|
230
|
+
// CREATED → STARTING. Sinkron: tak ada interleaving; reentransi via
|
|
231
|
+
// onStart yang memanggil start() ditolak deterministik di atas.
|
|
232
|
+
state = "STARTING"
|
|
233
|
+
if (!hooksStarted) {
|
|
234
|
+
hooksStarted = true
|
|
235
|
+
try {
|
|
236
|
+
hooks?.onStart?.()
|
|
237
|
+
} catch (e) {
|
|
238
|
+
// Init gagal = tak pernah READY; kembali CREATED agar retry mungkin.
|
|
239
|
+
// Error diteruskan (tak ditelan); tanpa state baru (M4 melarang).
|
|
240
|
+
state = "CREATED"
|
|
241
|
+
hooksStarted = false
|
|
242
|
+
throw e
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
state = "READY"
|
|
246
|
+
m.startCount++
|
|
247
|
+
},
|
|
248
|
+
|
|
249
|
+
state(): HostLifecycleState {
|
|
250
|
+
return state
|
|
251
|
+
},
|
|
252
|
+
|
|
253
|
+
admit(spec: HostAdmissionSpec): ExecutionCorrelation {
|
|
254
|
+
if (state !== "READY") {
|
|
255
|
+
if (state === "DRAINING") m.admissionRejectedDuringDrain++
|
|
256
|
+
throw new Error(`runtime-host: admit() in ${state} (admission only in READY)`)
|
|
257
|
+
}
|
|
258
|
+
if (!spec?.kind || !spec.ownerId)
|
|
259
|
+
throw new Error("runtime-host: admit() requires kind and ownerId (never user authority)")
|
|
260
|
+
const correlation = spec.parent
|
|
261
|
+
? createChildCorrelation(spec.parent, spec.kind, spec.ownerId)
|
|
262
|
+
: createRootCorrelation(spec.kind, spec.ownerId)
|
|
263
|
+
registry.observe({
|
|
264
|
+
executionId: correlation.executionId,
|
|
265
|
+
...(correlation.parentExecutionId
|
|
266
|
+
? { parentExecutionId: correlation.parentExecutionId }
|
|
267
|
+
: {}),
|
|
268
|
+
rootExecutionId: correlation.rootExecutionId,
|
|
269
|
+
kind: correlation.kind,
|
|
270
|
+
ownerId: correlation.ownerId,
|
|
271
|
+
stateSnapshot: "ADMITTED",
|
|
272
|
+
...(spec.deadlineRef !== undefined ? { deadlineRef: spec.deadlineRef } : {}),
|
|
273
|
+
...(spec.budgetRef !== undefined ? { budgetRef: spec.budgetRef } : {}),
|
|
274
|
+
...(spec.backendRef !== undefined ? { backendRef: spec.backendRef } : {}),
|
|
275
|
+
})
|
|
276
|
+
m.admitted++
|
|
277
|
+
return correlation
|
|
278
|
+
},
|
|
279
|
+
|
|
280
|
+
async run<TInput, TResult>(
|
|
281
|
+
input: TInput,
|
|
282
|
+
callOpts?: { runner?: HostRunDelegate<TInput, TResult>; signal?: AbortSignal },
|
|
283
|
+
): Promise<TResult> {
|
|
284
|
+
// run() baru = admission kerja baru → HANYA di READY. In-flight (promise
|
|
285
|
+
// delegate yang sudah di-await) tak tersentuh host (bukan authority).
|
|
286
|
+
if (state !== "READY")
|
|
287
|
+
throw new Error(`runtime-host: run() in ${state} (new runs only in READY)`)
|
|
288
|
+
const runner = (callOpts?.runner ?? boundRunner) as
|
|
289
|
+
| HostRunDelegate<TInput, TResult>
|
|
290
|
+
| undefined
|
|
291
|
+
if (!runner)
|
|
292
|
+
throw new Error(
|
|
293
|
+
"runtime-host: run() with no runner bound (M3 facade delegates only — bind existing session.run; never invents execution)",
|
|
294
|
+
)
|
|
295
|
+
m.runs++
|
|
296
|
+
try {
|
|
297
|
+
return await runner(input, { ...(callOpts?.signal ? { signal: callOpts.signal } : {}) })
|
|
298
|
+
} catch (e) {
|
|
299
|
+
m.runErrors++
|
|
300
|
+
throw e
|
|
301
|
+
}
|
|
302
|
+
},
|
|
303
|
+
|
|
304
|
+
inspect(executionId: string): ExecutionSnapshot | undefined {
|
|
305
|
+
if (state === "CREATED" || state === "STARTING" || state === "CLOSED") return undefined
|
|
306
|
+
return registry.inspect(executionId)
|
|
307
|
+
},
|
|
308
|
+
|
|
309
|
+
list(): ExecutionSummary[] {
|
|
310
|
+
if (state === "CREATED" || state === "STARTING" || state === "CLOSED") return []
|
|
311
|
+
return registry.list()
|
|
312
|
+
},
|
|
313
|
+
|
|
314
|
+
metrics(): { host: HostMetrics; registryEntries: number } {
|
|
315
|
+
return metricsSnapshot()
|
|
316
|
+
},
|
|
317
|
+
|
|
318
|
+
async shutdown(): Promise<{
|
|
319
|
+
shutdownRequested: true
|
|
320
|
+
observedEntries: number
|
|
321
|
+
state: HostLifecycleState
|
|
322
|
+
}> {
|
|
323
|
+
if (state !== "READY" && state !== "DRAINING")
|
|
324
|
+
throw new Error(`runtime-host: shutdown() in ${state}`)
|
|
325
|
+
// Latch dulu (admit ditolak deterministik), baru hook — urutan ini yang
|
|
326
|
+
// membuat admit+shutdown konkuren deterministik.
|
|
327
|
+
state = "DRAINING"
|
|
328
|
+
m.shutdowns++
|
|
329
|
+
if (!hooksShutdown) {
|
|
330
|
+
hooksShutdown = true
|
|
331
|
+
const r = await runHookBounded(hooks?.onShutdown, shutdownHookTimeoutMs, "shutdown")
|
|
332
|
+
m.lastShutdownDurationMs = r.durationMs
|
|
333
|
+
if (!r.ok) m.hookFailures++
|
|
334
|
+
}
|
|
335
|
+
// Gagal hook = degraded + tetap DRAINING; TAK PERNAH resurrect ke READY.
|
|
336
|
+
// Error hook tak ditelan-tanpa-jejak: tercatat di hookFailures +
|
|
337
|
+
// lastShutdownDurationMs (observability), transisi tetap selesai agar
|
|
338
|
+
// shutdown total dan bounded (hook melempar tak boleh membuat shutdown
|
|
339
|
+
// harus diulang — itu lifecycle-nya sendiri).
|
|
340
|
+
return { shutdownRequested: true as const, observedEntries: registry.size(), state }
|
|
341
|
+
},
|
|
342
|
+
|
|
343
|
+
async close(): Promise<void> {
|
|
344
|
+
if (state === "CLOSED" || state === "CLOSING") return
|
|
345
|
+
if (state === "CREATED" || state === "STARTING")
|
|
346
|
+
throw new Error(`runtime-host: close() in ${state}`)
|
|
347
|
+
// READY/DRAINING → CLOSING. State dimajukan SEBELUM hook agar gagal hook
|
|
348
|
+
// tak bisa resurrect; CLOSED ditetapkan di finally (selalu terminal).
|
|
349
|
+
state = "CLOSING"
|
|
350
|
+
m.closes++
|
|
351
|
+
let hookError: unknown = null
|
|
352
|
+
if (!hooksClosed) {
|
|
353
|
+
hooksClosed = true
|
|
354
|
+
const r = await runHookBounded(hooks?.onClose, closeHookTimeoutMs, "close")
|
|
355
|
+
m.lastCloseDurationMs = r.durationMs
|
|
356
|
+
if (!r.ok) {
|
|
357
|
+
m.hookFailures++
|
|
358
|
+
hookError = new Error("runtime-host: close hook failed (degraded, still CLOSED)")
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
state = "CLOSED"
|
|
362
|
+
if (hookError) throw hookError
|
|
363
|
+
},
|
|
364
|
+
}
|
|
365
|
+
}
|