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,267 @@
1
+ // P2.12 — klien IPC minimal (dipakai CLI `minicode daemon …` dan test).
2
+ //
3
+ // Sengaja ada di `src/`, bukan `cli/`: test butuh klien tanpa menjalankan
4
+ // seluruh CLI, dan modul non-ui tidak boleh mengimpor `cli/`. Klien ini juga
5
+ // PEMBUKTI liveness sesungguhnya — `discover()` hanya menghasilkan "suspect",
6
+ // dan status "alive" hanya boleh lahir dari probe koneksi yang berhasil di
7
+ // sini (recency != liveness).
8
+
9
+ import { connect, type Socket } from "node:net"
10
+ import { type DiscoveryResult, discover, readEndpoint } from "./discovery.ts"
11
+ import { encodeFrame, FrameDecoder } from "./framing.ts"
12
+ import { DAEMON_PROTOCOL, type ServerMessage, type SubscribeFrom } from "./protocol.ts"
13
+
14
+ export interface ConnectTarget {
15
+ host: string
16
+ port: number
17
+ }
18
+
19
+ export type ClientEvent =
20
+ | { kind: "message"; msg: ServerMessage }
21
+ | { kind: "closed"; reason: string }
22
+ | { kind: "protocol-error"; message: string }
23
+
24
+ export interface ProbeResult {
25
+ alive: boolean
26
+ reason: string
27
+ target: ConnectTarget | null
28
+ discovery: DiscoveryResult
29
+ }
30
+
31
+ /**
32
+ * Probe kehidupan daemon: baca endpoint -> coba TCP connect.
33
+ *
34
+ * SATU-SATUNYA tempat yang boleh menyata `alive: true`. Semua pemanggil lain
35
+ * memakai hasil di sini, bukan umur file.
36
+ */
37
+ export async function probeDaemon(cwd?: string, timeoutMs = 800): Promise<ProbeResult> {
38
+ const discovery = discover(cwd)
39
+ if (!discovery.endpoint) {
40
+ return {
41
+ alive: false,
42
+ reason: discovery.reason ?? "tidak ada endpoint",
43
+ target: null,
44
+ discovery,
45
+ }
46
+ }
47
+ const target: ConnectTarget = { host: discovery.endpoint.host, port: discovery.endpoint.port }
48
+ try {
49
+ await withTimeout(openAndClose(target), timeoutMs, "probe timeout")
50
+ return { alive: true, reason: "probe koneksi berhasil", target, discovery }
51
+ } catch (e) {
52
+ return { alive: false, reason: String((e as Error).message ?? e), target, discovery }
53
+ }
54
+ }
55
+
56
+ function openAndClose(target: ConnectTarget): Promise<void> {
57
+ return new Promise((resolve, reject) => {
58
+ const sock = connect({ host: target.host, port: target.port })
59
+ const done = (fn: () => void) => {
60
+ sock.removeAllListeners()
61
+ sock.destroy()
62
+ fn()
63
+ }
64
+ sock.once("connect", () => done(resolve))
65
+ sock.once("error", (e) => done(() => reject(e)))
66
+ })
67
+ }
68
+
69
+ function withTimeout<T>(p: Promise<T>, ms: number, msg: string): Promise<T> {
70
+ return new Promise((resolve, reject) => {
71
+ const t = setTimeout(() => reject(new Error(msg)), ms)
72
+ t.unref?.()
73
+ p.then(
74
+ (v) => {
75
+ clearTimeout(t)
76
+ resolve(v)
77
+ },
78
+ (e) => {
79
+ clearTimeout(t)
80
+ reject(e)
81
+ },
82
+ )
83
+ })
84
+ }
85
+
86
+ export interface DaemonClientOptions {
87
+ target: ConnectTarget
88
+ capability: string
89
+ consumer: string
90
+ }
91
+
92
+ export class DaemonClient {
93
+ readonly #sock: Socket
94
+ readonly #decoder = new FrameDecoder()
95
+ readonly #listeners = new Set<(e: ClientEvent) => void>()
96
+ #closed = false
97
+ welcome: Extract<ServerMessage, { t: "welcome" }> | null = null
98
+ #pendingControl = new Map<string, (msg: ServerMessage) => void>()
99
+
100
+ private constructor(sock: Socket) {
101
+ this.#sock = sock
102
+ sock.on("data", (chunk: string | Buffer) => {
103
+ let msgs: unknown[]
104
+ try {
105
+ // Beberapa runtime memuntahkan data sebagai string bila encoding
106
+ // diset; framing butuh byte mentah agar tidak salah hitung panjang.
107
+ msgs = this.#decoder.push(typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk)
108
+ } catch (e) {
109
+ this.#emit({ kind: "protocol-error", message: String((e as Error).message ?? e) })
110
+ this.close("protocol-error")
111
+ return
112
+ }
113
+ for (const raw of msgs) {
114
+ if (!raw || typeof raw !== "object" || !("t" in raw)) continue
115
+ const msg = raw as ServerMessage
116
+ if (msg.t === "control_result") {
117
+ const waiter = this.#pendingControl.get(msg.idem)
118
+ if (waiter) {
119
+ this.#pendingControl.delete(msg.idem)
120
+ waiter(msg)
121
+ }
122
+ }
123
+ this.#emit({ kind: "message", msg })
124
+ }
125
+ })
126
+ sock.on("close", () => this.#emit({ kind: "closed", reason: "socket tertutup" }))
127
+ sock.on("error", (e) =>
128
+ this.#emit({ kind: "closed", reason: String((e as Error).message ?? e) }),
129
+ )
130
+ }
131
+
132
+ static async connect(opts: DaemonClientOptions): Promise<DaemonClient> {
133
+ const sock = await new Promise<Socket>((resolve, reject) => {
134
+ const s = connect({ host: opts.target.host, port: opts.target.port })
135
+ s.once("connect", () => {
136
+ s.removeAllListeners("error")
137
+ resolve(s)
138
+ })
139
+ s.once("error", reject)
140
+ })
141
+ const client = new DaemonClient(sock)
142
+ await client.hello(opts.capability, opts.consumer)
143
+ return client
144
+ }
145
+
146
+ on(fn: (e: ClientEvent) => void): () => void {
147
+ this.#listeners.add(fn)
148
+ return () => this.#listeners.delete(fn)
149
+ }
150
+
151
+ #emit(e: ClientEvent): void {
152
+ for (const fn of [...this.#listeners]) {
153
+ try {
154
+ fn(e)
155
+ } catch {
156
+ // Listener yang melempar tidak boleh mematikan klien untuk yang lain.
157
+ }
158
+ }
159
+ }
160
+
161
+ #send(msg: unknown): void {
162
+ if (this.#closed) return
163
+ this.#sock.write(encodeFrame(msg))
164
+ }
165
+
166
+ async hello(
167
+ capability: string,
168
+ consumer: string,
169
+ timeoutMs = 2_000,
170
+ ): Promise<Extract<ServerMessage, { t: "welcome" }>> {
171
+ const gotWelcome = new Promise<Extract<ServerMessage, { t: "welcome" }>>((resolve, reject) => {
172
+ const off = this.on((e) => {
173
+ if (e.kind === "message" && e.msg.t === "welcome") {
174
+ off()
175
+ resolve(e.msg)
176
+ } else if (e.kind === "message" && e.msg.t === "error") {
177
+ off()
178
+ reject(new Error(`${e.msg.code}: ${e.msg.message}`))
179
+ } else if (e.kind === "closed") {
180
+ off()
181
+ reject(new Error(`koneksi ditutup saat hello: ${e.reason}`))
182
+ }
183
+ })
184
+ })
185
+ this.#send({ t: "hello", protocol: DAEMON_PROTOCOL, cap: capability, consumer })
186
+ this.welcome = await withTimeout(gotWelcome, timeoutMs, "hello timeout")
187
+ return this.welcome
188
+ }
189
+
190
+ /** Tunggu pesan tertentu (untuk test & handshake berurutan). */
191
+ next(pred: (m: ServerMessage) => boolean, timeoutMs = 3_000): Promise<ServerMessage> {
192
+ return withTimeout(
193
+ new Promise<ServerMessage>((resolve) => {
194
+ const off = this.on((e) => {
195
+ if (e.kind === "message" && pred(e.msg)) {
196
+ off()
197
+ resolve(e.msg)
198
+ }
199
+ })
200
+ }),
201
+ timeoutMs,
202
+ "menunggu pesan timeout",
203
+ )
204
+ }
205
+
206
+ subscribe(sid: string, from: SubscribeFrom): void {
207
+ this.#send({ t: "subscribe", sid, from, consumer: this.welcome?.consumer ?? "" })
208
+ }
209
+
210
+ ack(sid: string, seq: number): void {
211
+ this.#send({ t: "ack", sid, seq, consumer: this.welcome?.consumer ?? "" })
212
+ }
213
+
214
+ control(
215
+ op: string,
216
+ args: Record<string, unknown>,
217
+ idem: string,
218
+ timeoutMs = 3_000,
219
+ ): Promise<Extract<ServerMessage, { t: "control_result" }>> {
220
+ const waiter = new Promise<Extract<ServerMessage, { t: "control_result" }>>(
221
+ (resolve, reject) => {
222
+ this.#pendingControl.set(idem, (m) => {
223
+ resolve(m as Extract<ServerMessage, { t: "control_result" }>)
224
+ })
225
+ const off = this.on((e) => {
226
+ if (e.kind === "closed") {
227
+ off()
228
+ this.#pendingControl.delete(idem)
229
+ reject(new Error(`koneksi ditutup: ${e.reason}`))
230
+ }
231
+ })
232
+ },
233
+ )
234
+ this.#send({ t: "control", op, idem, args, consumer: this.welcome?.consumer ?? "" })
235
+ return withTimeout(waiter, timeoutMs, "control timeout")
236
+ }
237
+
238
+ ping(id: string): Promise<ServerMessage> {
239
+ // Pasang penunggu SEBELUM mengirim: balasan bisa datang lebih cepat dari
240
+ // penambahan listener bila urutannya dibalik.
241
+ const waiter = this.next((m) => m.t === "pong" && m.id === id)
242
+ this.#send({ t: "ping", id })
243
+ return waiter
244
+ }
245
+
246
+ close(reason = "klien menutup"): void {
247
+ if (this.#closed) return
248
+ this.#send({ t: "goodbye" })
249
+ this.#closed = true
250
+ try {
251
+ this.#sock.end()
252
+ } catch {
253
+ this.#sock.destroy()
254
+ }
255
+ this.#emit({ kind: "closed", reason })
256
+ }
257
+
258
+ get closed(): boolean {
259
+ return this.#closed
260
+ }
261
+ }
262
+
263
+ /** Baca endpoint langsung (tanpa probe) — untuk diagnostik. */
264
+ export function readTarget(cwd?: string): ConnectTarget | null {
265
+ const ep = readEndpoint(cwd)
266
+ return ep ? { host: ep.host, port: ep.port } : null
267
+ }
@@ -0,0 +1,350 @@
1
+ // P2.12 — API kontrol: cakupan, idempotensi, dan penolakan stale.
2
+ //
3
+ // Kenapa satu tempat: sembilan operasi kontrol punya aturan yang sama
4
+ // (scope → idempotensi → stale → eksekusi). Menyebar aturan itu ke handler
5
+ // masing-masing membuat satu operasi melompati validasi yang operasi lain
6
+ // patuhi — dan celah persis di situ yang dicari penyerang lokal.
7
+
8
+ import type { RuntimeView } from "../runtime/runtime-status.ts"
9
+ import { absentRuntimeView } from "../runtime/runtime-status-provider.ts"
10
+ import { readWriterEpoch } from "../session/persistence.ts"
11
+ import type { ApprovalBroker } from "./approvals.ts"
12
+ import type { ControlOp, DaemonScope, RefusalBody, RefusalCode, ServerMessage } from "./protocol.ts"
13
+ import { isControlOp, requiredScope } from "./protocol.ts"
14
+ import { sanitizeLabel } from "./sanitize.ts"
15
+ import type { Telemetry } from "./telemetry.ts"
16
+
17
+ export interface HostedSessionInfo {
18
+ sid: string
19
+ hosted: boolean
20
+ writerEpoch: number
21
+ runId: string | null
22
+ runStatus: string | null
23
+ presentationHead: number
24
+ }
25
+
26
+ /**
27
+ * Aksi yang dilakukan host atas sesi. Dipasang dari composition root (cli/)
28
+ * karena `src/**` non-ui tidak boleh mengimpor `cli/` — dan sebaliknya.
29
+ * Tanpa aksi terpasang, operasi yang butuh aksi menolak (fail-closed), bukan
30
+ * pura-pura berhasil.
31
+ */
32
+ export interface ControlActions {
33
+ listSessions(): HostedSessionInfo[]
34
+ sessionStatus(sid: string): HostedSessionInfo | null
35
+ interrupt(
36
+ sid: string,
37
+ runId: string | null,
38
+ ): { ok: true } | { ok: false; code: RefusalCode; message: string }
39
+ cancel(
40
+ sid: string,
41
+ runId: string | null,
42
+ ): { ok: true } | { ok: false; code: RefusalCode; message: string }
43
+ shutdown(reason: string): void
44
+ }
45
+
46
+ export interface ControlDeps {
47
+ incarnation: string
48
+ actions: ControlActions | null
49
+ approvals: ApprovalBroker
50
+ telemetry: Telemetry
51
+ /** false = tekanan penyimpanan; op mutasi ditolak, op baca tetap jalan. */
52
+ storageOk: () => boolean
53
+ shuttingDown: () => boolean
54
+ /**
55
+ * Status runtime kanonik (P13.1) — SATU model yang sama dengan yang dipakai
56
+ * CLI. Opsional supaya host tanpa runtime (atau test lama) tetap compiles;
57
+ * bila absen, daemon menyajikan view ABSENT kanonik, bukan status karangan.
58
+ */
59
+ runtimeStatus?: () => RuntimeView
60
+ }
61
+
62
+ export interface ControlRequest {
63
+ consumerId: string
64
+ scopes: readonly DaemonScope[]
65
+ op: string
66
+ idem: string
67
+ args: Record<string, unknown>
68
+ }
69
+
70
+ export type ControlOutcome =
71
+ | { ok: true; result: unknown; replayed: boolean }
72
+ | { ok: false; refusal: RefusalBody }
73
+
74
+ function refuse(
75
+ code: RefusalCode,
76
+ message: string,
77
+ detail?: RefusalBody["detail"],
78
+ ): ControlOutcome {
79
+ return { ok: false, refusal: { code, message, ...(detail ? { detail } : {}) } }
80
+ }
81
+
82
+ /**
83
+ * Cache idempotensi. Terbatas ukuran + TTL — idempotensi tak boleh menjadi
84
+ * ingatan yang tumbuh tanpa batas mengikuti jumlah permintaan konsumen.
85
+ *
86
+ * Dua perilaku yang sengaja berbeda:
87
+ * - kunci sama + payload sama -> kembalikan hasil ASLI (retry aman)
88
+ * - kunci sama + payload beda -> tolak IDEMPOTENT_REPLAY
89
+ * Alasan yang kedua: mengembalikan hasil lama untuk pekerjaan berbeda akan
90
+ * menyembunyikan bug konsumen yang memakai ulang kunci; mengeksekusi ulang
91
+ * berarti pekerjaan terjadi dua kali. Dua-duanya lebih buruk daripada menolak
92
+ * dengan jelas.
93
+ */
94
+ export class IdempotencyStore {
95
+ readonly #byKey = new Map<string, { fingerprint: string; outcome: ControlOutcome; at: number }>()
96
+ readonly max: number
97
+ readonly ttlMs: number
98
+
99
+ constructor(opts: { max?: number; ttlMs?: number } = {}) {
100
+ this.max = Math.max(1, opts.max ?? 512)
101
+ this.ttlMs = Math.max(1_000, opts.ttlMs ?? 5 * 60_000)
102
+ }
103
+
104
+ lookup(key: string, fingerprint: string, now = Date.now()): ControlOutcome | null {
105
+ const hit = this.#byKey.get(key)
106
+ if (!hit) return null
107
+ if (now - hit.at > this.ttlMs) {
108
+ this.#byKey.delete(key)
109
+ return null
110
+ }
111
+ if (hit.fingerprint !== fingerprint)
112
+ return {
113
+ ok: false,
114
+ refusal: {
115
+ code: "IDEMPOTENT_REPLAY",
116
+ message: "kunci idempoten dipakai ulang dengan payload berbeda",
117
+ },
118
+ }
119
+ return hit.outcome
120
+ }
121
+
122
+ remember(key: string, fingerprint: string, outcome: ControlOutcome, now = Date.now()): void {
123
+ if (this.#byKey.size >= this.max) {
124
+ // Buang yang tertua (Map mempertahankan urutan sisipan).
125
+ const oldest = this.#byKey.keys().next().value
126
+ if (oldest !== undefined) this.#byKey.delete(oldest)
127
+ }
128
+ this.#byKey.set(key, { fingerprint, outcome, at: now })
129
+ }
130
+
131
+ get size(): number {
132
+ return this.#byKey.size
133
+ }
134
+
135
+ clear(): void {
136
+ this.#byKey.clear()
137
+ }
138
+ }
139
+
140
+ function fingerprintOf(op: string, args: Record<string, unknown>): string {
141
+ const keys = Object.keys(args).sort()
142
+ const parts = keys.map((k) => `${k}=${stableString(args[k])}`)
143
+ return `${op}|${parts.join("&")}`
144
+ }
145
+
146
+ function stableString(v: unknown): string {
147
+ if (v === null || v === undefined) return "null"
148
+ if (typeof v !== "object") return String(v)
149
+ if (Array.isArray(v)) return `[${v.map(stableString).join(",")}]`
150
+ const rec = v as Record<string, unknown>
151
+ return (
152
+ "{" +
153
+ Object.keys(rec)
154
+ .sort()
155
+ .map((k) => `${k}:${stableString(rec[k])}`)
156
+ .join(",") +
157
+ "}"
158
+ )
159
+ }
160
+
161
+ /**
162
+ * Jalankan satu operasi kontrol urut: scope → idempotensi → stale → aksi.
163
+ *
164
+ * Urutan itu penting: mengecek idempotensi SEBELUM scope akan membocorkan
165
+ * "operasi ini pernah dijalankan" kepada konsumen yang tak punya izin
166
+ * menjalankannya.
167
+ */
168
+ export function dispatchControl(
169
+ req: ControlRequest,
170
+ deps: ControlDeps,
171
+ idem: IdempotencyStore,
172
+ ): ControlOutcome {
173
+ const telemetry = deps.telemetry
174
+
175
+ if (!isControlOp(req.op)) {
176
+ telemetry.inc("control.refused")
177
+ return refuse("PROTOCOL_ERROR", `operasi tak dikenal: ${sanitizeLabel(req.op, 64)}`)
178
+ }
179
+ const op: ControlOp = req.op
180
+ const need = requiredScope(op)
181
+ if (!req.scopes.includes(need)) {
182
+ telemetry.inc("control.refused")
183
+ return refuse("SCOPE_DENIED", `operasi ${op} membutuhkan cakupan ${need}`, { need })
184
+ }
185
+ if (typeof req.idem !== "string" || req.idem.length === 0 || req.idem.length > 200) {
186
+ telemetry.inc("control.refused")
187
+ return refuse("PROTOCOL_ERROR", "idem wajib berupa string 1..200 karakter")
188
+ }
189
+
190
+ const key = req.consumerId + String.fromCharCode(1) + req.idem
191
+ const fp = fingerprintOf(op, req.args)
192
+ const prior = idem.lookup(key, fp)
193
+ if (prior) {
194
+ if (prior.ok) {
195
+ telemetry.inc("idempotent.replay")
196
+ return { ...prior, replayed: true }
197
+ }
198
+ telemetry.inc("control.refused")
199
+ return prior
200
+ }
201
+
202
+ const outcome = runOp(op, req, deps)
203
+ // Hanya hasil sukses yang diingat: kegagalan bisa bersifat sementara
204
+ // (tekanan disk, lease lepas) dan wajib bisa dicoba ulang dengan idem sama.
205
+ if (outcome.ok) idem.remember(key, fp, outcome)
206
+ telemetry.inc(outcome.ok ? "control.executed" : "control.refused")
207
+ return outcome
208
+ }
209
+
210
+ function runOp(op: ControlOp, req: ControlRequest, deps: ControlDeps): ControlOutcome {
211
+ const args = req.args
212
+ const sid = typeof args.sid === "string" ? args.sid : ""
213
+
214
+ if (
215
+ op === "daemon.status" ||
216
+ op === "daemon.shutdown" ||
217
+ op === "session.list" ||
218
+ op === "approval.list"
219
+ ) {
220
+ if (deps.shuttingDown() && op !== "daemon.status") {
221
+ return refuse("SHUTTING_DOWN", "daemon sedang berhenti")
222
+ }
223
+ }
224
+
225
+ switch (op) {
226
+ case "daemon.status": {
227
+ return {
228
+ ok: true,
229
+ result: {
230
+ incarnation: deps.incarnation,
231
+ shuttingDown: deps.shuttingDown(),
232
+ storageOk: deps.storageOk(),
233
+ actions: deps.actions !== null,
234
+ // P13.1: status runtime KANONIK ikut piggyback di op yang sudah ada.
235
+ // Tidak ada endpoint health terpisah — satu model, satu sumber.
236
+ runtime: deps.runtimeStatus ? deps.runtimeStatus() : absentRuntimeView(),
237
+ },
238
+ replayed: false,
239
+ }
240
+ }
241
+
242
+ case "daemon.shutdown": {
243
+ if (!deps.actions)
244
+ return refuse("PROTOCOL_ERROR", "host tidak terpasang - tak ada yang bisa dihentikan")
245
+ const reason = sanitizeLabel(String(args.reason ?? "control"), 120)
246
+ const actions = deps.actions
247
+ // TUNDAA satu putaran event loop: berhenti secara langsung akan menutup
248
+ // koneksi operator SEBELUM frame control_result sempat terkirim, sehingga
249
+ // pemanggil CLI melihat "socket tertutup" untuk perintah yang sebenarnya
250
+ // berhasil. Keputusan tetap dibuat sekarang; hanya eksekusinya yang nanti.
251
+ setImmediate(() => actions.shutdown(reason))
252
+ return { ok: true, result: { accepted: true, reason }, replayed: false }
253
+ }
254
+
255
+ case "session.list": {
256
+ if (!deps.actions) return refuse("PROTOCOL_ERROR", "host tidak terpasang")
257
+ return { ok: true, result: deps.actions.listSessions(), replayed: false }
258
+ }
259
+
260
+ case "session.status": {
261
+ if (!sid) return refuse("SESSION_MISMATCH", "args.sid wajib diisi")
262
+ if (!deps.actions) return refuse("PROTOCOL_ERROR", "host tidak terpasang")
263
+ const info = deps.actions.sessionStatus(sid)
264
+ if (!info)
265
+ return refuse("SESSION_MISMATCH", `sesi ${sanitizeLabel(sid, 64)} tidak di-host daemon ini`)
266
+ return { ok: true, result: info, replayed: false }
267
+ }
268
+
269
+ case "approval.list": {
270
+ if (!sid) return refuse("SESSION_MISMATCH", "args.sid wajib diisi")
271
+ return { ok: true, result: deps.approvals.list(sid), replayed: false }
272
+ }
273
+
274
+ case "approval.decide": {
275
+ const approvalId = typeof args.approvalId === "string" ? args.approvalId : ""
276
+ const decisionRaw = typeof args.decision === "string" ? args.decision : ""
277
+ if (!approvalId) return refuse("SESSION_MISMATCH", "args.approvalId wajib diisi")
278
+ if (decisionRaw !== "accept" && decisionRaw !== "deny") {
279
+ return refuse("PROTOCOL_ERROR", 'args.decision harus "accept" atau "deny"')
280
+ }
281
+ // [RC-2] Cek kepemilikan session SEBELUM mutasi DB: baca baris tanpa menulis,
282
+ // tolak mismatch SESSION_MISMATCH tanpa membangunkan waiter/mengubah state.
283
+ const existing = deps.approvals.read(approvalId)
284
+ if (sid && existing && existing.sid !== sid) {
285
+ // Approval milik sesi lain: menolaknya menggagalkan keputusan yang
286
+ // sebenarnya valid, jadi jangan — laporkan kecocokan yang salah saja.
287
+ return refuse("SESSION_MISMATCH", "approval bukan milik sesi yang disebut", {
288
+ actual: existing.sid,
289
+ })
290
+ }
291
+ const r = deps.approvals.decide(approvalId, decisionRaw)
292
+ if (!r.ok) return { ok: false, refusal: r.refusal }
293
+ deps.telemetry.inc("approval.decided")
294
+ return { ok: true, result: { approvalId, state: r.row.state }, replayed: false }
295
+ }
296
+
297
+ case "run.interrupt":
298
+ case "run.cancel": {
299
+ if (!sid) return refuse("SESSION_MISMATCH", "args.sid wajib diisi")
300
+ if (!deps.storageOk())
301
+ return refuse("STORAGE_PRESSURE", "penyimpanan di bawah tekanan — operasi mutasi ditahan")
302
+ if (!deps.actions) return refuse("PROTOCOL_ERROR", "host tidak terpasang")
303
+ const info = deps.actions.sessionStatus(sid)
304
+ if (!info)
305
+ return refuse("SESSION_MISMATCH", `sesi ${sanitizeLabel(sid, 64)} tidak di-host daemon ini`)
306
+ // Pagaran epoch: konsumen yang menyebut epoch harus cocok dengan dunia
307
+ // sekarang. Epoch beda = otoritas penulis telah pindah; perintah dari
308
+ // penampil lama tidak boleh menyentuh sesi yang kini milik penulis lain.
309
+ if (typeof args.expectedEpoch === "number") {
310
+ const actual = readWriterEpoch(sid)
311
+ if (actual !== args.expectedEpoch) {
312
+ return refuse("STALE_EPOCH", "epoch penulis berpindah — perintah basi ditolak", {
313
+ expected: args.expectedEpoch,
314
+ actual,
315
+ })
316
+ }
317
+ }
318
+ const runId = typeof args.runId === "string" ? args.runId : info.runId
319
+ if (!runId) return refuse("RUN_TERMINAL", "tidak ada run aktif untuk diinterupsi")
320
+ if (
321
+ info.runStatus === "COMPLETED" ||
322
+ info.runStatus === "FAILED" ||
323
+ info.runStatus === "INTERRUPTED"
324
+ ) {
325
+ return refuse(
326
+ "RUN_TERMINAL",
327
+ `run ${sanitizeLabel(runId, 64)} sudah ${info.runStatus} — tak bisa diulang`,
328
+ )
329
+ }
330
+ // LEASE_LOST: daemon mem-host sesi ini tetapi penulisnya sudah basi —
331
+ // perintah akan diabaikan oleh sesi yang sudah menyerahkan otoritas.
332
+ if (!info.hosted) {
333
+ return refuse("LEASE_LOST", "sesi bukan milik daemon ini (penulis di proses lain)")
334
+ }
335
+ const res =
336
+ op === "run.interrupt"
337
+ ? deps.actions.interrupt(sid, runId)
338
+ : deps.actions.cancel(sid, runId)
339
+ if (!res.ok) return { ok: false, refusal: { code: res.code, message: res.message } }
340
+ return { ok: true, result: { sid, runId, op }, replayed: false }
341
+ }
342
+ }
343
+ return refuse("PROTOCOL_ERROR", "operasi tak dikenal")
344
+ }
345
+
346
+ /** Susun pesan `control_result` dari hasil dispatch. */
347
+ export function toControlMessage(outcome: ControlOutcome, idem: string): ServerMessage {
348
+ if (outcome.ok) return { t: "control_result", idem, ok: true, result: outcome.result }
349
+ return { t: "control_result", idem, ok: false, refusal: outcome.refusal }
350
+ }