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,57 @@
1
+ // P2.12 — pembasuh teks masuk IPC (label konsumen, pesan penolakan, ringkasan
2
+ // tool dari jaringan/lokal).
3
+ //
4
+ // Kenapa ada salinan lokal: `src/ui/render/sanitize.ts` berada di lapisan UI dan
5
+ // batas lapisan (test/ui-boundary.test.ts) MELARANG `src/**` non-ui mengimpor
6
+ // `src/ui/**`. Daemon tetap wajib membasuh input tak terpercaya sebelum
7
+ // disimpan/diteruskan — sanitizer lokal yang sederhana lebih baik daripada
8
+ // membiarkan ANSI/jalur kendali mengalir ke konsumen.
9
+ //
10
+ // Cakupannya disengaja sempit (satu string, tanpa state): cukup untuk label dan
11
+ // pesan, bukan stream teks model — stream itu tidak melewati jalur ini.
12
+ //
13
+ // Pola dibangun lewat String.fromCharCode(27) bukan literal ESC: berkas yang
14
+ // memuat byte kontrol mentah merusak tooling teks dan sering tak sengaja
15
+ // ter-strip oleh formatter — siluman yang paling sulit dicari.
16
+
17
+ const ESC = String.fromCharCode(27)
18
+ const BEL = String.fromCharCode(7)
19
+
20
+ // OSC: ESC ] … (BEL | ESC \). Dicek SEBELUM CSI: body OSC sering memuat "ESC ["
21
+ // sehingga urutan membalikkan hasilnya jadi sisa teks nyasar.
22
+ const OSC = new RegExp(`${ESC}\\][^${ESC}${BEL}]*(?:${BEL}|${ESC}\\\\)`, "g")
23
+ // CSI: ESC [ params intermediate final.
24
+ const CSI = new RegExp(`${ESC}\\[[0-9;?]*[ -/]*[@-~]`, "g")
25
+ // Escape lain (ESC SP F …) — cukup buang dua-byte-nya.
26
+ const OTHER_ESC = new RegExp(`${ESC}[ -/]*[@-~]`, "g")
27
+ // C0 tanpa \n \t (kebutuhan teks biasa) + DEL. Ditulis lewat `new RegExp`
28
+ // bukan literal regex: literal akan memaksa byte kontrol ke dalam sumber
29
+ // (melanggar aturan yang sama seperti komentar di atas), sementara
30
+ // `noControlCharactersInRegex` justru melarang literal semacam itu.
31
+ // biome-ignore lint/complexity/useRegexLiterals: lihat alasan di atas.
32
+ const CTRL = new RegExp("[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F]", "g")
33
+
34
+ export function sanitizeIncoming(s: string): string {
35
+ if (typeof s !== "string" || s.length === 0) return ""
36
+ return s.replace(OSC, "").replace(CSI, "").replace(OTHER_ESC, "").replace(CTRL, "")
37
+ }
38
+
39
+ /** Batasi panjang + basuh — untuk field yang nanti ikut dicetak/disimpan. */
40
+ export function sanitizeLabel(s: unknown, max = 120): string {
41
+ if (typeof s !== "string" || s.length === 0) return ""
42
+ return sanitizeIncoming(s).slice(0, max)
43
+ }
44
+
45
+ /** Basuh rekursif — untuk payload JSON yang datang dari peer. */
46
+ export function sanitizeJsonObject(value: unknown): unknown {
47
+ if (typeof value === "string") return sanitizeIncoming(value)
48
+ if (Array.isArray(value)) return value.map(sanitizeJsonObject)
49
+ if (value !== null && typeof value === "object") {
50
+ const out: Record<string, unknown> = {}
51
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
52
+ out[sanitizeLabel(k, 64)] = sanitizeJsonObject(v)
53
+ }
54
+ return out
55
+ }
56
+ return value
57
+ }
@@ -0,0 +1,627 @@
1
+ // P2.12 — server IPC daemon (loopback TCP).
2
+ //
3
+ // Keputusan transport: TCP loopback, bukan Unix socket / named pipe. Kontrak
4
+ // menuntut konsumen lintas-platform yang bisa dipakai Desktop di Windows;
5
+ // Unix socket tidak ada di Windows dan named pipe tidak ada di POSIX tanpa
6
+ // kode cabang. Loopback + capability bercakupan + berkas endpoint 0600
7
+ // memberi batas kepercayaan yang sama: hanya proses di mesin ini, dan hanya
8
+ // yang memegang secret.
9
+ //
10
+ // Alur per koneksi (kontrak § handshake): hello -> welcome -> subscribe ->
11
+ // frontiers -> snapshot -> cursor -> replay -> tail_marker -> LIVE.
12
+ // Replay dan live tidak boleh berbaur: event yang masih ditulis selama replay
13
+ // akan tiba dua kali bila disuntikkan di tengah — maka event live yang seq-nya
14
+ // sudah tercakup replay dibuang.
15
+
16
+ import type { Server } from "node:net"
17
+ import { createServer, type Socket } from "node:net"
18
+ import type { RuntimeView } from "../runtime/runtime-status.ts"
19
+ import type { ApprovalBroker } from "./approvals.ts"
20
+ import { type CapabilityPayload, verifyCapability } from "./capability.ts"
21
+ import {
22
+ type ControlActions,
23
+ type ControlDeps,
24
+ dispatchControl,
25
+ type IdempotencyStore,
26
+ toControlMessage,
27
+ } from "./control.ts"
28
+ import { buildSnapshot, REPLAY_PAGE_LIMIT, type SessionFeed } from "./feed.ts"
29
+ import { assertProtocol, encodeFrame, FrameDecoder, isRecord } from "./framing.ts"
30
+ import type { ApprovalView } from "./protocol.ts"
31
+ import {
32
+ DAEMON_PROTOCOL,
33
+ type DaemonScope,
34
+ type HaltReason,
35
+ type RefusalBody,
36
+ type ServerMessage,
37
+ type SubscribeFrom,
38
+ } from "./protocol.ts"
39
+ import { sanitizeJsonObject, sanitizeLabel } from "./sanitize.ts"
40
+ import { readConsumerOffset } from "./store.ts"
41
+ import { type Subscription, SubscriptionRegistry } from "./subscription.ts"
42
+ import type { Telemetry } from "./telemetry.ts"
43
+
44
+ export interface FeedRegistry {
45
+ get(sid: string): SessionFeed | undefined
46
+ known(): string[]
47
+ }
48
+
49
+ export interface DaemonServerDeps {
50
+ incarnation: string
51
+ secret: Buffer
52
+ host: string
53
+ port: number
54
+ cwd?: string
55
+ feeds: FeedRegistry
56
+ subscriptions?: SubscriptionRegistry
57
+ approvals: ApprovalBroker
58
+ control: {
59
+ actions: ControlActions | null
60
+ idem: IdempotencyStore
61
+ telemetry: Telemetry
62
+ storageOk: () => boolean
63
+ shuttingDown: () => boolean
64
+ /** Status runtime kanonik (P13.1) — opsional; tanpa itu daemon menyajikan view ABSENT. */
65
+ runtimeStatus?: () => RuntimeView
66
+ }
67
+ telemetry: Telemetry
68
+ /**
69
+ * Batas antrean per langganan. Seam uji untuk membuktikan backpressure satu
70
+ * konsumen tidak menyentuh konsumen lain; produksi memakai MAX_QUEUE_PER_CONN.
71
+ */
72
+ maxQueuePerSubscription?: number
73
+ /** Seam uji: batas antrean per identitas konsumen logis (lihat host). */
74
+ maxQueuePerConsumer?: (consumerId: string) => number | undefined
75
+ /** Dipanggil saat daemon menerima koneksi (diagnostik). */
76
+ onConnection?: (info: { remote: string; consumer: string }) => void
77
+ }
78
+
79
+ interface Conn {
80
+ id: number
81
+ socket: Socket
82
+ decoder: FrameDecoder
83
+ state: "new" | "ready"
84
+ /**
85
+ * Identitas logis (dari capability `who`) untuk offset durable, idempotensi,
86
+ * dan label wire. Stabil lintas reconnect.
87
+ */
88
+ consumerId: string | null
89
+ /**
90
+ * Identitas LIVE ber-scope koneksi. Dua koneksi dengan `consumerId` yang sama
91
+ * tetap punya langganan sendiri; tanpa pemisahan ini, koneksi kedua menutup
92
+ * langganan koneksi pertama dan teardown salah satunya mencabut keduanya.
93
+ */
94
+ subscriptionScope: string | null
95
+ scopes: DaemonScope[]
96
+ subs: Map<string, Subscription>
97
+ paused: boolean
98
+ closed: boolean
99
+ }
100
+
101
+ let connSeq = 0
102
+
103
+ // Pemisah yang tak mungkin muncul di label konsumen (sanitizeLabel membuang
104
+ // kendali). Scope live = identitas logis + id koneksi, sehingga dua koneksi
105
+ // konsumen yang sama tidak pernah berbagi kunci langganan.
106
+ const CONSUMER_SCOPE_SEP = String.fromCharCode(1)
107
+
108
+ export class DaemonServer {
109
+ readonly #deps: DaemonServerDeps
110
+ readonly #subs: SubscriptionRegistry
111
+ readonly #conns = new Map<number, Conn>()
112
+ readonly #liveUnsub = new Map<string, () => void>()
113
+ #server: Server | null = null
114
+ #port = 0
115
+ #closing = false
116
+ #startedAt = 0
117
+
118
+ constructor(deps: DaemonServerDeps) {
119
+ this.#deps = deps
120
+ this.#subs = deps.subscriptions ?? new SubscriptionRegistry()
121
+ }
122
+
123
+ get port(): number {
124
+ return this.#port
125
+ }
126
+
127
+ get connectionCount(): number {
128
+ return this.#conns.size
129
+ }
130
+
131
+ get closing(): boolean {
132
+ return this.#closing
133
+ }
134
+
135
+ async start(): Promise<{ port: number }> {
136
+ const server = createServer({ noDelay: true }, (socket) => this.#onConnection(socket))
137
+ this.#server = server
138
+ await new Promise<void>((resolve, reject) => {
139
+ const onErr = (e: Error) => reject(e)
140
+ server.once("error", onErr)
141
+ server.listen(this.#deps.port, this.#deps.host, () => {
142
+ server.off("error", onErr)
143
+ resolve()
144
+ })
145
+ })
146
+ const addr = server.address()
147
+ if (addr === null || typeof addr === "string")
148
+ throw new Error("daemon: alamat loopback tak terbaca")
149
+ this.#port = addr.port
150
+ this.#startedAt = Date.now()
151
+ return { port: this.#port }
152
+ }
153
+
154
+ #onConnection(socket: Socket): void {
155
+ this.#deps.telemetry.inc("connections.opened")
156
+ const conn: Conn = {
157
+ id: ++connSeq,
158
+ socket,
159
+ decoder: new FrameDecoder(),
160
+ state: "new",
161
+ consumerId: null,
162
+ subscriptionScope: null,
163
+ scopes: [],
164
+ subs: new Map(),
165
+ paused: false,
166
+ closed: false,
167
+ }
168
+ this.#conns.set(conn.id, conn)
169
+
170
+ socket.on("data", (chunk: Buffer) => {
171
+ try {
172
+ const msgs = conn.decoder.push(chunk)
173
+ for (const m of msgs) this.#onMessage(conn, m)
174
+ } catch (e) {
175
+ this.#sendError(conn, "PROTOCOL_ERROR", String((e as Error).message ?? e))
176
+ this.#halt(conn, "PROTOCOL_ERROR")
177
+ }
178
+ })
179
+ socket.on("drain", () => {
180
+ conn.paused = false
181
+ this.#pump(conn)
182
+ })
183
+ const teardown = () => this.#teardown(conn)
184
+ socket.on("close", teardown)
185
+ socket.on("error", teardown)
186
+ }
187
+
188
+ #teardown(conn: Conn): void {
189
+ if (conn.closed) return
190
+ conn.closed = true
191
+ this.#deps.telemetry.inc("connections.closed")
192
+ // Tutup HANYA langganan milik koneksi ini. Memakai consumerId logis di sini
193
+ // akan ikut memutus koneksi lain yang memakai identitas konsumen sama.
194
+ const scope = conn.subscriptionScope ?? conn.consumerId
195
+ if (scope) {
196
+ this.#subs.dropConsumer(scope)
197
+ this.#pruneLive()
198
+ }
199
+ this.#conns.delete(conn.id)
200
+ conn.subs.clear()
201
+ try {
202
+ // Jangan langkas-langkas: `destroy()` pada socket yang masih memegang
203
+ // tulisan tertunda (mis. frame control_result "shutdown diterima")
204
+ // membuangnya, lalu pemanggil CLI gagal padahal perintah sukses.
205
+ // `end()` mengosongkan buffer ke peer lebih dulu; paksa tutup sesudahnya.
206
+ conn.socket.end()
207
+ } catch {
208
+ // Socket sudah mati — bukan kegagalan yang perlu ditangani.
209
+ }
210
+ const sock = conn.socket
211
+ const timer = setTimeout(() => {
212
+ try {
213
+ sock.destroy()
214
+ } catch {
215
+ /* sudah tertutup */
216
+ }
217
+ }, 150)
218
+ timer.unref?.()
219
+ }
220
+
221
+ #send(conn: Conn, msg: ServerMessage): boolean {
222
+ if (conn.closed) return false
223
+ try {
224
+ const ok = conn.socket.write(encodeFrame(msg))
225
+ if (!ok) conn.paused = true
226
+ return true
227
+ } catch {
228
+ this.#teardown(conn)
229
+ return false
230
+ }
231
+ }
232
+
233
+ #sendError(conn: Conn, code: RefusalBody["code"], message: string): void {
234
+ this.#send(conn, { t: "error", code, message: sanitizeLabel(message, 400) })
235
+ }
236
+
237
+ /** Hentikan konsumen dengan alasan tegas + tutup koneksi. */
238
+ #halt(conn: Conn, reason: HaltReason): void {
239
+ if (conn.closed) return
240
+ this.#send(conn, { t: "halt", reason })
241
+ try {
242
+ conn.socket.end()
243
+ } catch {
244
+ /* jatuh ke teardown di bawah */
245
+ }
246
+ // Halte adalah keputusan, bukan negosiasi. Tanpa paksa-tutup, peer yang
247
+ // berhenti membaca bisa menggantung `end()` tanpa batas dan koneksi itu
248
+ // tetap terhitung hidup setelah overflow. `#teardown` sendiri menjadwalkan
249
+ // `destroy()` setelah 150 ms, jadi cukup satu timer di sana.
250
+ setTimeout(() => this.#teardown(conn), 50).unref?.()
251
+ }
252
+
253
+ // -------------------------------------------------------------------------
254
+ // Pesan masuk
255
+ // -------------------------------------------------------------------------
256
+
257
+ #onMessage(conn: Conn, raw: unknown): void {
258
+ if (!isRecord(raw) || typeof raw.t !== "string") {
259
+ this.#sendError(conn, "PROTOCOL_ERROR", "pesan bukan objek bertipe")
260
+ this.#halt(conn, "PROTOCOL_ERROR")
261
+ return
262
+ }
263
+ switch (raw.t) {
264
+ case "hello":
265
+ this.#onHello(conn, raw)
266
+ return
267
+ case "ping":
268
+ this.#send(conn, { t: "pong", id: String(raw.id ?? "") })
269
+ return
270
+ case "goodbye":
271
+ this.#teardown(conn)
272
+ return
273
+ default:
274
+ break
275
+ }
276
+ if (conn.state !== "ready") {
277
+ this.#sendError(conn, "INVALID_CAPABILITY", "hello diperlukan sebelum operasi lain")
278
+ this.#halt(conn, "PROTOCOL_ERROR")
279
+ return
280
+ }
281
+ switch (raw.t) {
282
+ case "subscribe":
283
+ this.#onSubscribe(conn, raw)
284
+ return
285
+ case "ack":
286
+ this.#onAck(conn, raw)
287
+ return
288
+ case "control":
289
+ this.#onControl(conn, raw)
290
+ return
291
+ default:
292
+ this.#sendError(
293
+ conn,
294
+ "PROTOCOL_ERROR",
295
+ `t tak dikenal: ${sanitizeLabel(String(raw.t), 40)}`,
296
+ )
297
+ this.#halt(conn, "PROTOCOL_ERROR")
298
+ }
299
+ }
300
+
301
+ #onHello(conn: Conn, raw: Record<string, unknown>): void {
302
+ try {
303
+ assertProtocol({ protocol: raw.protocol })
304
+ } catch (e) {
305
+ this.#deps.telemetry.inc("connections.rejected")
306
+ this.#sendError(conn, "PROTOCOL_ERROR", (e as Error).message)
307
+ this.#teardown(conn)
308
+ return
309
+ }
310
+ const check = verifyCapability(this.#deps.secret, String(raw.cap ?? ""), {
311
+ incarnation: this.#deps.incarnation,
312
+ })
313
+ if (!check.ok) {
314
+ this.#deps.telemetry.inc("connections.rejected")
315
+ // STALE_INCARNATION vs INVALID_CAPABILITY harus terbedakan: yang pertama
316
+ // berarti "daemon sudah ganti, minta capability baru", yang kedua
317
+ // berarti "capability ini memang tidak sah".
318
+ const code = check.reason === "STALE_INCARNATION" ? "STALE_INCARNATION" : "INVALID_CAPABILITY"
319
+ this.#sendError(conn, code, `capability ditolak: ${check.reason}`)
320
+ this.#teardown(conn)
321
+ return
322
+ }
323
+ const payload: CapabilityPayload = check.payload
324
+ conn.state = "ready"
325
+ conn.scopes = payload.scopes
326
+ conn.consumerId = sanitizeLabel(payload.who, 120) || `consumer-${conn.id}`
327
+ conn.subscriptionScope = `${conn.consumerId}${CONSUMER_SCOPE_SEP}conn-${conn.id}`
328
+ this.#send(conn, {
329
+ t: "welcome",
330
+ protocol: DAEMON_PROTOCOL,
331
+ incarnation: this.#deps.incarnation,
332
+ scopes: payload.scopes,
333
+ consumer: conn.consumerId,
334
+ })
335
+ this.#deps.onConnection?.({
336
+ remote: conn.socket.remoteAddress ?? "?",
337
+ consumer: conn.consumerId,
338
+ })
339
+ }
340
+
341
+ #onSubscribe(conn: Conn, raw: Record<string, unknown>): void {
342
+ const sid = typeof raw.sid === "string" ? raw.sid : ""
343
+ if (!sid) {
344
+ this.#sendError(conn, "SESSION_MISMATCH", "sid wajib diisi")
345
+ return
346
+ }
347
+ if (!conn.scopes.includes("subscribe")) {
348
+ this.#sendError(conn, "SCOPE_DENIED", "subscribe membutuhkan cakupan subscribe")
349
+ return
350
+ }
351
+ const feed = this.#deps.feeds.get(sid)
352
+ if (!feed) {
353
+ // Sesi tidak dikenal: bukan SESSION_MISMATCH (itu untuk perbedaan milik),
354
+ // tapi NOT_FOUND — konsumen bertanya tentang sesi yang tak ada sama sekali.
355
+ this.#sendError(
356
+ conn,
357
+ "NOT_FOUND",
358
+ `sesi ${sanitizeLabel(sid, 64)} tidak tersedia di daemon ini`,
359
+ )
360
+ return
361
+ }
362
+ const head = feed.head()
363
+ const fromRaw = raw.from
364
+ const from: SubscribeFrom =
365
+ fromRaw === "tail" || fromRaw === "resume"
366
+ ? fromRaw
367
+ : typeof fromRaw === "number" && Number.isFinite(fromRaw)
368
+ ? fromRaw
369
+ : // Nilai tak dikenal = resume (default paling aman: tak membanjiri
370
+ // konsumen dengan replay penuh, dan tak kehilangan progres ack).
371
+ "resume"
372
+ const consumer = conn.consumerId ?? `consumer-${conn.id}`
373
+ // Scope live ber-scope koneksi; offset tetap memakai identitas logis agar
374
+ // reconnect dengan konsumen yang sama melanjutkan dari ack terakhir.
375
+ const scope = conn.subscriptionScope ?? consumer
376
+ const consumerQueue = this.#deps.maxQueuePerConsumer?.(consumer)
377
+
378
+ const { sub, fromSeq } = this.#subs.attach(
379
+ {
380
+ consumerId: scope,
381
+ offsetConsumerId: consumer,
382
+ sid,
383
+ from,
384
+ head,
385
+ fromSeq: 0,
386
+ ...(consumerQueue !== undefined
387
+ ? { maxQueue: consumerQueue }
388
+ : this.#deps.maxQueuePerSubscription !== undefined
389
+ ? { maxQueue: this.#deps.maxQueuePerSubscription }
390
+ : {}),
391
+ ...(this.#deps.cwd !== undefined ? { cwd: this.#deps.cwd } : {}),
392
+ },
393
+ (c, s) => readConsumerOffset(c, s, this.#deps.cwd),
394
+ )
395
+ conn.subs.set(sid, sub)
396
+ this.#deps.telemetry.inc("subscribe.attached")
397
+
398
+ // Pasang listener live SEBELUM membaca toko. Keduanya sinkron hari ini,
399
+ // tetapi urutan ini membuat celah "event tiba di antara replay dan
400
+ // langganan" mustahil terjadi bila salah satu jalur kelak menjadi async:
401
+ // apa pun yang tiba lebih dulu sudah berada di antrean dan akan difilter
402
+ // terhadap cursor replay, bukan hilang begitu saja.
403
+ this.#ensureLive(sid)
404
+
405
+ // 1) frontiers 2) snapshot 3) cursor
406
+ const frontiers = feed.frontiers()
407
+ this.#send(conn, { t: "frontiers", sid, frontiers })
408
+ const { snapshot, rejected } = buildSnapshot(feed, undefined, frontiers)
409
+ this.#send(conn, { t: "snapshot", sid, consumer, snapshot })
410
+ this.#send(conn, {
411
+ t: "subscribed",
412
+ sid,
413
+ consumer,
414
+ fromSeq,
415
+ cursor: sub.cursor,
416
+ snapshotRejected: rejected,
417
+ })
418
+
419
+ // 4) replay — hanya bila memang ada yang harus dikirim.
420
+ let replayTo = sub.cursor
421
+ if (fromSeq <= head) {
422
+ let cursor = fromSeq - 1
423
+ for (;;) {
424
+ const page = feed.readRange(cursor + 1, REPLAY_PAGE_LIMIT)
425
+ if (page.events.length === 0) break
426
+ for (const ev of page.events) {
427
+ const seq = numberOr(ev.eventSeq, -1)
428
+ if (seq < fromSeq) continue
429
+ if (
430
+ !this.#send(conn, { t: "event", sid, consumer, seq, provenance: "REPLAY", event: ev })
431
+ )
432
+ return
433
+ cursor = seq
434
+ sub.cursor = seq
435
+ this.#deps.telemetry.inc("events.replayed")
436
+ }
437
+ if (page.events.length < REPLAY_PAGE_LIMIT) break
438
+ }
439
+ replayTo = sub.cursor
440
+ }
441
+ this.#send(conn, { t: "replay_done", sid, consumer, upToSeq: replayTo })
442
+ // 5) penanda live-tail: segala sesuatu SETELAH pesan ini adalah LIVE dan
443
+ // boleh saja belum durable — konsumen harus memperlakukannya beda.
444
+ this.#send(conn, { t: "tail_marker", sid, consumer, atSeq: replayTo })
445
+ // 6) kosongkan antrean live yang terkumpul selama replay (yang seq-nya
446
+ // sudah terkirim otomatis terbuang di #pump).
447
+ this.#pump(conn)
448
+ }
449
+
450
+ #onAck(conn: Conn, raw: Record<string, unknown>): void {
451
+ const sid = typeof raw.sid === "string" ? raw.sid : ""
452
+ const seq = typeof raw.seq === "number" ? raw.seq : -1
453
+ const sub = conn.subs.get(sid)
454
+ if (!sub) {
455
+ this.#sendError(conn, "SESSION_MISMATCH", "ack tanpa langganan aktif")
456
+ return
457
+ }
458
+ const res = sub.ack(seq)
459
+ if (!res.ok) {
460
+ this.#deps.telemetry.inc("ack.rejected")
461
+ this.#sendError(
462
+ conn,
463
+ res.reason === "CLOSED" ? "SHUTTING_DOWN" : "PROTOCOL_ERROR",
464
+ res.reason === "CLOSED"
465
+ ? "langganan sudah ditutup"
466
+ : `ack ${seq} di luar jangkauan (cursor ${sub.cursor})`,
467
+ )
468
+ return
469
+ }
470
+ this.#deps.telemetry.inc("ack.accepted")
471
+ this.#send(conn, { t: "ack_ok", sid, consumer: conn.consumerId ?? "", seq: res.persisted })
472
+ }
473
+
474
+ #onControl(conn: Conn, raw: Record<string, unknown>): void {
475
+ const args = isRecord(raw.args) ? (sanitizeJsonObject(raw.args) as Record<string, unknown>) : {}
476
+ const outcome = dispatchControl(
477
+ {
478
+ consumerId: conn.consumerId ?? `consumer-${conn.id}`,
479
+ scopes: conn.scopes,
480
+ op: String(raw.op ?? ""),
481
+ idem: String(raw.idem ?? ""),
482
+ args,
483
+ },
484
+ {
485
+ incarnation: this.#deps.incarnation,
486
+ actions: this.#deps.control.actions,
487
+ approvals: this.#deps.approvals,
488
+ telemetry: this.#deps.control.telemetry,
489
+ storageOk: this.#deps.control.storageOk,
490
+ shuttingDown: this.#deps.control.shuttingDown,
491
+ ...(this.#deps.control.runtimeStatus
492
+ ? { runtimeStatus: this.#deps.control.runtimeStatus }
493
+ : {}),
494
+ } satisfies ControlDeps,
495
+ this.#deps.control.idem,
496
+ )
497
+ this.#send(conn, toControlMessage(outcome, String(raw.idem ?? "")))
498
+ }
499
+
500
+ // -------------------------------------------------------------------------
501
+ // Fan-out live
502
+ // -------------------------------------------------------------------------
503
+
504
+ #ensureLive(sid: string): void {
505
+ if (this.#liveUnsub.has(sid)) return
506
+ const feed = this.#deps.feeds.get(sid)
507
+ if (!feed) return
508
+ // [RC-1] Jangan subscribe/memoize feed NON-HOSTED (store feed → liveSubscribe
509
+ // no-op). Bila sesi kemudian jadi hosted, subscriber yang tersambung saat
510
+ // jendela boot bisa re-bind dan menerima stream LIVE yang sebenarnya.
511
+ if (!feed.hosted) return
512
+ const unsub = feed.liveSubscribe((event) => this.#fanout(sid, event))
513
+ this.#liveUnsub.set(sid, unsub)
514
+ }
515
+
516
+ #pruneLive(): void {
517
+ // Lepas live untuk sesi yang tak lagi punya konsumen tertarik.
518
+ for (const [sid, unsub] of [...this.#liveUnsub]) {
519
+ const stillWanted = [...this.#conns.values()].some((c) => !c.closed && c.subs.has(sid))
520
+ if (!stillWanted) {
521
+ unsub()
522
+ this.#liveUnsub.delete(sid)
523
+ }
524
+ }
525
+ }
526
+
527
+ #fanout(sid: string, event: { eventSeq?: number }): void {
528
+ const seq = numberOr(event.eventSeq, -1)
529
+ if (seq < 0) return
530
+
531
+ // Snapshot daftar target SEBELUM menyentuh antrean: `#halt` memanggil
532
+ // `#teardown` yang memutasi daftar koneksi saat iterasi berlangsung.
533
+ for (const conn of [...this.#conns.values()]) {
534
+ if (conn.closed) continue
535
+ const sub = conn.subs.get(sid)
536
+ if (!sub || sub.closed) continue
537
+ // Event yang sudah tercakup replay = duplikat; lewati.
538
+ if (seq <= sub.cursor) continue
539
+ if (!sub.enqueue({ seq, provenance: "LIVE", event })) {
540
+ this.#deps.telemetry.inc("events.dropped.overflow")
541
+ sub.close()
542
+ this.#halt(conn, "QUEUE_OVERFLOW")
543
+ // Hentikan HANYA konsumen ini. `return` di sini akan melewati konsumen
544
+ // berikutnya pada event yang sama — satu klien lambat membuat klien
545
+ // lain kehilangan seq durable yang tak akan pernah dikirim ulang.
546
+ continue
547
+ }
548
+ this.#pump(conn)
549
+ }
550
+ }
551
+
552
+ /** Dorong isi antrean live ke socket; berhenti bila socket menahan tulisan. */
553
+ #pump(conn: Conn): void {
554
+ if (conn.closed || conn.paused) return
555
+ for (const [, sub] of conn.subs) {
556
+ for (;;) {
557
+ if (conn.closed || conn.paused) return
558
+ const item = sub.takeFirst()
559
+ if (!item) break
560
+ if (item.provenance !== "LIVE") continue
561
+ // Sudah terkirim lewat replay: mengirim ulang membuat konsumen melihat
562
+ // dua event identik dengan seq sama.
563
+ if (item.seq <= sub.cursor) continue
564
+ const sent = this.#send(conn, {
565
+ t: "event",
566
+ sid: sub.sid,
567
+ consumer: conn.consumerId ?? "",
568
+ seq: item.seq,
569
+ provenance: item.provenance,
570
+ event: item.event,
571
+ })
572
+ if (!sent) return
573
+ sub.cursor = item.seq
574
+ this.#deps.telemetry.inc("events.delivered")
575
+ }
576
+ }
577
+ }
578
+
579
+ // -------------------------------------------------------------------------
580
+ // Broadcast + shutdown
581
+ // -------------------------------------------------------------------------
582
+
583
+ /** Usulan persetujuan -> konsumen ber-cakupan approve. */
584
+ broadcastApproval(view: ApprovalView): number {
585
+ let n = 0
586
+ for (const conn of [...this.#conns.values()]) {
587
+ if (conn.closed || !conn.scopes.includes("approve")) continue
588
+ if (this.#send(conn, { t: "approval", consumer: conn.consumerId ?? "", approval: view })) n++
589
+ }
590
+ return n
591
+ }
592
+
593
+ /** Beri tahu SEMUA konsumen bahwa daemon berhenti. */
594
+ broadcastHalt(reason: HaltReason): number {
595
+ let n = 0
596
+ for (const conn of [...this.#conns.values()]) {
597
+ if (this.#send(conn, { t: "halt", reason })) n++
598
+ }
599
+ return n
600
+ }
601
+
602
+ async close(): Promise<void> {
603
+ if (this.#closing) return
604
+ this.#closing = true
605
+ this.broadcastHalt("SHUTTING_DOWN")
606
+ for (const unsub of this.#liveUnsub.values()) unsub()
607
+ this.#liveUnsub.clear()
608
+ this.#subs.clear()
609
+ for (const conn of [...this.#conns.values()]) this.#teardown(conn)
610
+ const server = this.#server
611
+ this.#server = null
612
+ if (!server) return
613
+ await new Promise<void>((resolve) => {
614
+ server.close(() => resolve())
615
+ // Koneksi yang menolak menutup diri tidak boleh menahan shutdown.
616
+ setTimeout(() => resolve(), 500).unref?.()
617
+ })
618
+ }
619
+
620
+ get startedAt(): number {
621
+ return this.#startedAt
622
+ }
623
+ }
624
+
625
+ function numberOr(v: unknown, fallback: number): number {
626
+ return typeof v === "number" && Number.isFinite(v) ? v : fallback
627
+ }