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.
Files changed (221) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/LICENSE +21 -21
  3. package/README.md +4 -4
  4. package/cli/args.ts +46 -0
  5. package/cli/commands/acp.ts +163 -10
  6. package/cli/commands/config.ts +33 -18
  7. package/cli/commands/daemon.ts +515 -0
  8. package/cli/commands/exec.ts +145 -53
  9. package/cli/commands/openwork.ts +986 -0
  10. package/cli/commands/sessions.ts +4 -1
  11. package/cli/commands/stats.ts +34 -4
  12. package/cli/commands.ts +217 -2
  13. package/cli/index.ts +146 -14
  14. package/cli/recovery-warning.ts +115 -0
  15. package/cli/router.ts +32 -1
  16. package/cli/setup.ts +2332 -171
  17. package/cli/tui.ts +113 -7
  18. package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
  19. package/docs/OUTPUT_EVENT_MODEL.md +289 -0
  20. package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
  21. package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
  22. package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
  23. package/docs/OUTPUT_UX_RULES.md +449 -0
  24. package/docs/PLAN_UIUX_V6.md +2 -2
  25. package/docs/README.md +4 -3
  26. package/docs/TERMINAL_CONTRACT.md +278 -66
  27. package/docs/architecture.md +89 -7
  28. package/docs/changelog.md +1 -1
  29. package/docs/choosing-mode.md +2 -2
  30. package/docs/cli.md +9 -5
  31. package/docs/concepts.md +1 -1
  32. package/docs/contributing.md +9 -2
  33. package/docs/environment.md +6 -2
  34. package/docs/exec.md +46 -5
  35. package/docs/memory-sessions.md +2 -0
  36. package/docs/policy-sandbox.md +1 -1
  37. package/docs/pricing-budget.md +1 -1
  38. package/docs/quickstart.md +2 -2
  39. package/docs/repl.md +6 -2
  40. package/docs/security-model.md +1 -1
  41. package/docs/security.md +1 -1
  42. package/docs/skills.md +2 -2
  43. package/docs/terminal.md +9 -5
  44. package/docs/tools.md +1 -1
  45. package/package.json +35 -5
  46. package/src/app/session.ts +261 -15
  47. package/src/app/tool-layer.ts +94 -7
  48. package/src/daemon/approvals.ts +361 -0
  49. package/src/daemon/capability.ts +145 -0
  50. package/src/daemon/children.ts +142 -0
  51. package/src/daemon/client.ts +267 -0
  52. package/src/daemon/control.ts +350 -0
  53. package/src/daemon/discovery.ts +234 -0
  54. package/src/daemon/feed.ts +155 -0
  55. package/src/daemon/framing.ts +94 -0
  56. package/src/daemon/host.ts +316 -0
  57. package/src/daemon/protocol.ts +217 -0
  58. package/src/daemon/resource.ts +170 -0
  59. package/src/daemon/sanitize.ts +57 -0
  60. package/src/daemon/server.ts +627 -0
  61. package/src/daemon/store.ts +317 -0
  62. package/src/daemon/subscription.ts +270 -0
  63. package/src/daemon/telemetry.ts +81 -0
  64. package/src/hooks/run.ts +12 -1
  65. package/src/lib/atomic-write.ts +29 -3
  66. package/src/lib/db-path.ts +26 -0
  67. package/src/lib/keystore.ts +544 -42
  68. package/src/lib/net.ts +43 -1
  69. package/src/lib/safe-open.ts +116 -1
  70. package/src/lib/session-id.ts +15 -0
  71. package/src/lsp/client.ts +123 -5
  72. package/src/mcp/client.ts +139 -17
  73. package/src/mcp/server.ts +177 -50
  74. package/src/mcp/transport.ts +16 -19
  75. package/src/memory/vector.ts +770 -55
  76. package/src/policy/allowlist.ts +14 -2
  77. package/src/policy/bash-guard.ts +105 -10
  78. package/src/policy/compaction.ts +82 -5
  79. package/src/policy/consequence-engine.ts +220 -0
  80. package/src/policy/context.ts +132 -0
  81. package/src/policy/executor.ts +187 -121
  82. package/src/policy/no-progress.ts +559 -0
  83. package/src/policy/permission.ts +4 -8
  84. package/src/policy/pricing.ts +17 -3
  85. package/src/policy/scrub.ts +69 -2
  86. package/src/policy/tool-contract.ts +515 -0
  87. package/src/policy/usage.ts +310 -24
  88. package/src/policy/verifier.ts +6 -3
  89. package/src/policy/work-mode.ts +182 -0
  90. package/src/presentation/adapter.ts +533 -26
  91. package/src/presentation/events.ts +151 -0
  92. package/src/presentation/model.ts +180 -27
  93. package/src/presentation/projection.ts +858 -0
  94. package/src/presentation/reducer.ts +645 -310
  95. package/src/presentation/store.ts +12 -7
  96. package/src/providers/anthropic.ts +18 -10
  97. package/src/providers/responses.ts +17 -7
  98. package/src/runtime/capability.ts +409 -0
  99. package/src/runtime/child-execution.ts +274 -0
  100. package/src/runtime/composition.ts +958 -0
  101. package/src/runtime/dispatch.ts +591 -0
  102. package/src/runtime/execution-backend.ts +632 -0
  103. package/src/runtime/execution-events.ts +272 -0
  104. package/src/runtime/execution-id.ts +230 -0
  105. package/src/runtime/execution-journal.ts +926 -0
  106. package/src/runtime/execution-kernel.ts +456 -0
  107. package/src/runtime/execution-registry.ts +379 -0
  108. package/src/runtime/process-supervision.ts +276 -0
  109. package/src/runtime/production-execution.ts +551 -0
  110. package/src/runtime/production-runtime.ts +217 -0
  111. package/src/runtime/recovery-safety.ts +70 -0
  112. package/src/runtime/recovery.ts +477 -0
  113. package/src/runtime/runtime-capabilities.ts +179 -0
  114. package/src/runtime/runtime-diagnostics.ts +141 -0
  115. package/src/runtime/runtime-host.ts +365 -0
  116. package/src/runtime/runtime-status-facts.ts +222 -0
  117. package/src/runtime/runtime-status-provider.ts +74 -0
  118. package/src/runtime/runtime-status.ts +459 -0
  119. package/src/runtime/runtime-task-admission.ts +101 -0
  120. package/src/runtime/supervisor.ts +444 -0
  121. package/src/session/authority.ts +168 -0
  122. package/src/session/checkpoint.ts +88 -1
  123. package/src/session/context-adapter.ts +251 -0
  124. package/src/session/context-assembly.ts +242 -0
  125. package/src/session/context-identity.ts +389 -0
  126. package/src/session/context-projection.ts +248 -0
  127. package/src/session/context-selector.ts +500 -0
  128. package/src/session/cross-session-adoption.ts +249 -0
  129. package/src/session/full-history-fold.ts +171 -0
  130. package/src/session/identity.ts +192 -0
  131. package/src/session/journal.ts +805 -102
  132. package/src/session/open-work-intent.ts +732 -0
  133. package/src/session/open-work.ts +767 -0
  134. package/src/session/pending-tools.ts +94 -0
  135. package/src/session/persistence.ts +3569 -127
  136. package/src/session/runtime-header.ts +208 -0
  137. package/src/session/shadow-git.ts +13 -5
  138. package/src/session/verification.ts +1623 -0
  139. package/src/task/assignment.ts +136 -0
  140. package/src/task/autonomous-adapter.ts +168 -0
  141. package/src/task/autonomous-context.ts +630 -0
  142. package/src/task/autonomous-policy.ts +490 -0
  143. package/src/task/continuity.ts +179 -0
  144. package/src/task/execution-cancellation.ts +165 -0
  145. package/src/task/graph-validate.ts +379 -0
  146. package/src/task/graph.ts +305 -0
  147. package/src/task/identity.ts +230 -0
  148. package/src/task/model.ts +417 -0
  149. package/src/task/production-scheduler.ts +293 -0
  150. package/src/task/readiness.ts +229 -0
  151. package/src/task/scheduler-observability.ts +387 -0
  152. package/src/task/scheduler.ts +1197 -0
  153. package/src/task/scheduling-policy.ts +165 -0
  154. package/src/task/session-authority.ts +148 -0
  155. package/src/task/session-ownership.ts +211 -0
  156. package/src/task/store.ts +2887 -0
  157. package/src/task/sync.ts +343 -0
  158. package/src/task/trigger.ts +260 -0
  159. package/src/tools/bash.ts +377 -211
  160. package/src/tools/code_run.ts +1 -1
  161. package/src/tools/delete_file.ts +1 -1
  162. package/src/tools/edit.ts +33 -6
  163. package/src/tools/evidence.ts +30 -0
  164. package/src/tools/git.ts +4 -4
  165. package/src/tools/glob.ts +12 -3
  166. package/src/tools/grep.ts +1 -1
  167. package/src/tools/lsp.ts +4 -4
  168. package/src/tools/mcp_call.ts +11 -4
  169. package/src/tools/memory.ts +153 -18
  170. package/src/tools/move_file.ts +1 -1
  171. package/src/tools/patch.ts +1 -1
  172. package/src/tools/read_file.ts +1 -1
  173. package/src/tools/read_image.ts +1 -1
  174. package/src/tools/submit_result.ts +1 -1
  175. package/src/tools/task.ts +437 -41
  176. package/src/tools/todo.ts +662 -35
  177. package/src/tools/web_fetch.ts +4 -2
  178. package/src/tools/web_search.ts +9 -3
  179. package/src/tools/write_file.ts +1 -1
  180. package/src/ui/assistant/simple.ts +123 -50
  181. package/src/ui/assistant/turn-status.ts +17 -3
  182. package/src/ui/contract.ts +184 -0
  183. package/src/ui/footer.ts +54 -18
  184. package/src/ui/i18n/en.ts +62 -6
  185. package/src/ui/i18n/id.ts +62 -6
  186. package/src/ui/input/prompt-engine.ts +120 -25
  187. package/src/ui/render/errors.ts +39 -1
  188. package/src/ui/render/markdown-table.ts +455 -0
  189. package/src/ui/render/markdown.ts +22 -1
  190. package/src/ui/render/table-grid.ts +184 -0
  191. package/src/ui/render/table.ts +15 -76
  192. package/src/ui/runtime/screen.ts +7 -2
  193. package/src/ui/runtime/statusline.ts +25 -6
  194. package/src/ui/tui/app.ts +598 -133
  195. package/src/ui/tui/transcript.ts +531 -89
  196. package/vendor/minicore/VENDOR.md +1 -1
  197. package/vendor/minicore/src/core/budget.ts +25 -25
  198. package/vendor/minicore/src/core/compact.ts +75 -75
  199. package/vendor/minicore/src/core/errors.ts +59 -59
  200. package/vendor/minicore/src/core/events.ts +73 -73
  201. package/vendor/minicore/src/core/executor.ts +139 -139
  202. package/vendor/minicore/src/core/history.ts +31 -31
  203. package/vendor/minicore/src/core/index.ts +41 -41
  204. package/vendor/minicore/src/core/loop.ts +355 -355
  205. package/vendor/minicore/src/core/permission.ts +22 -22
  206. package/vendor/minicore/src/core/provider.ts +39 -39
  207. package/vendor/minicore/src/core/recovery.ts +35 -35
  208. package/vendor/minicore/src/core/session.ts +327 -327
  209. package/vendor/minicore/src/core/snapshot.ts +146 -146
  210. package/vendor/minicore/src/core/tokens.ts +107 -107
  211. package/vendor/minicore/src/core/tool.ts +115 -115
  212. package/vendor/minicore/src/core/types.ts +50 -50
  213. package/vendor/minicore/src/providers/openai-compat.ts +417 -417
  214. package/AGENTS.md +0 -45
  215. package/PLAN.md +0 -491
  216. package/docs/ARCHITECTURE.html +0 -1248
  217. package/docs/CONTROL-PLANE-MAP.md +0 -139
  218. package/docs/HARNESS.md +0 -150
  219. package/docs/SUMMARY.md +0 -52
  220. package/docs/UI_RENDER_PIPELINE.md +0 -165
  221. 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
+ }