minicode-ai 0.11.1 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +89 -0
- package/LICENSE +21 -21
- package/README.md +4 -4
- package/cli/args.ts +46 -0
- package/cli/commands/acp.ts +163 -10
- package/cli/commands/config.ts +33 -18
- package/cli/commands/daemon.ts +515 -0
- package/cli/commands/exec.ts +145 -53
- package/cli/commands/openwork.ts +986 -0
- package/cli/commands/sessions.ts +4 -1
- package/cli/commands/stats.ts +34 -4
- package/cli/commands.ts +217 -2
- package/cli/index.ts +146 -14
- package/cli/recovery-warning.ts +115 -0
- package/cli/router.ts +32 -1
- package/cli/setup.ts +2332 -171
- package/cli/tui.ts +113 -7
- package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
- package/docs/OUTPUT_EVENT_MODEL.md +289 -0
- package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
- package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
- package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
- package/docs/OUTPUT_UX_RULES.md +449 -0
- package/docs/PLAN_UIUX_V6.md +2 -2
- package/docs/README.md +4 -3
- package/docs/TERMINAL_CONTRACT.md +278 -71
- package/docs/architecture.md +89 -7
- package/docs/changelog.md +1 -1
- package/docs/choosing-mode.md +2 -2
- package/docs/cli.md +9 -5
- package/docs/concepts.md +1 -1
- package/docs/contributing.md +9 -2
- package/docs/environment.md +6 -2
- package/docs/exec.md +46 -5
- package/docs/memory-sessions.md +2 -0
- package/docs/policy-sandbox.md +1 -1
- package/docs/pricing-budget.md +1 -1
- package/docs/quickstart.md +2 -2
- package/docs/repl.md +6 -2
- package/docs/security-model.md +1 -1
- package/docs/security.md +1 -1
- package/docs/skills.md +2 -2
- package/docs/terminal.md +9 -5
- package/docs/tools.md +1 -1
- package/package.json +35 -5
- package/src/app/session.ts +261 -15
- package/src/app/tool-layer.ts +94 -7
- package/src/daemon/approvals.ts +361 -0
- package/src/daemon/capability.ts +145 -0
- package/src/daemon/children.ts +142 -0
- package/src/daemon/client.ts +267 -0
- package/src/daemon/control.ts +350 -0
- package/src/daemon/discovery.ts +234 -0
- package/src/daemon/feed.ts +155 -0
- package/src/daemon/framing.ts +94 -0
- package/src/daemon/host.ts +316 -0
- package/src/daemon/protocol.ts +217 -0
- package/src/daemon/resource.ts +170 -0
- package/src/daemon/sanitize.ts +57 -0
- package/src/daemon/server.ts +627 -0
- package/src/daemon/store.ts +317 -0
- package/src/daemon/subscription.ts +270 -0
- package/src/daemon/telemetry.ts +81 -0
- package/src/hooks/run.ts +12 -1
- package/src/lib/atomic-write.ts +29 -3
- package/src/lib/db-path.ts +26 -0
- package/src/lib/keystore.ts +544 -42
- package/src/lib/net.ts +43 -1
- package/src/lib/safe-open.ts +116 -1
- package/src/lib/session-id.ts +15 -0
- package/src/lsp/client.ts +123 -5
- package/src/mcp/client.ts +139 -17
- package/src/mcp/server.ts +177 -50
- package/src/mcp/transport.ts +16 -19
- package/src/memory/vector.ts +770 -55
- package/src/policy/allowlist.ts +14 -2
- package/src/policy/bash-guard.ts +105 -10
- package/src/policy/compaction.ts +82 -5
- package/src/policy/consequence-engine.ts +220 -0
- package/src/policy/context.ts +132 -0
- package/src/policy/executor.ts +187 -121
- package/src/policy/no-progress.ts +559 -0
- package/src/policy/permission.ts +4 -8
- package/src/policy/pricing.ts +17 -3
- package/src/policy/scrub.ts +69 -2
- package/src/policy/tool-contract.ts +515 -0
- package/src/policy/usage.ts +310 -24
- package/src/policy/verifier.ts +6 -3
- package/src/policy/work-mode.ts +182 -0
- package/src/presentation/adapter.ts +533 -26
- package/src/presentation/events.ts +151 -0
- package/src/presentation/model.ts +180 -27
- package/src/presentation/projection.ts +858 -0
- package/src/presentation/reducer.ts +645 -310
- package/src/presentation/store.ts +12 -7
- package/src/providers/anthropic.ts +18 -10
- package/src/providers/responses.ts +2 -2
- package/src/runtime/capability.ts +409 -0
- package/src/runtime/child-execution.ts +274 -0
- package/src/runtime/composition.ts +958 -0
- package/src/runtime/dispatch.ts +591 -0
- package/src/runtime/execution-backend.ts +632 -0
- package/src/runtime/execution-events.ts +272 -0
- package/src/runtime/execution-id.ts +230 -0
- package/src/runtime/execution-journal.ts +926 -0
- package/src/runtime/execution-kernel.ts +456 -0
- package/src/runtime/execution-registry.ts +379 -0
- package/src/runtime/process-supervision.ts +276 -0
- package/src/runtime/production-execution.ts +551 -0
- package/src/runtime/production-runtime.ts +217 -0
- package/src/runtime/recovery-safety.ts +70 -0
- package/src/runtime/recovery.ts +477 -0
- package/src/runtime/runtime-capabilities.ts +179 -0
- package/src/runtime/runtime-diagnostics.ts +141 -0
- package/src/runtime/runtime-host.ts +365 -0
- package/src/runtime/runtime-status-facts.ts +222 -0
- package/src/runtime/runtime-status-provider.ts +74 -0
- package/src/runtime/runtime-status.ts +459 -0
- package/src/runtime/runtime-task-admission.ts +101 -0
- package/src/runtime/supervisor.ts +444 -0
- package/src/session/authority.ts +168 -0
- package/src/session/checkpoint.ts +88 -1
- package/src/session/context-adapter.ts +251 -0
- package/src/session/context-assembly.ts +242 -0
- package/src/session/context-identity.ts +389 -0
- package/src/session/context-projection.ts +248 -0
- package/src/session/context-selector.ts +500 -0
- package/src/session/cross-session-adoption.ts +249 -0
- package/src/session/full-history-fold.ts +171 -0
- package/src/session/identity.ts +192 -0
- package/src/session/journal.ts +805 -102
- package/src/session/open-work-intent.ts +732 -0
- package/src/session/open-work.ts +767 -0
- package/src/session/pending-tools.ts +94 -0
- package/src/session/persistence.ts +3569 -127
- package/src/session/runtime-header.ts +208 -0
- package/src/session/shadow-git.ts +13 -5
- package/src/session/verification.ts +1623 -0
- package/src/task/assignment.ts +136 -0
- package/src/task/autonomous-adapter.ts +168 -0
- package/src/task/autonomous-context.ts +630 -0
- package/src/task/autonomous-policy.ts +490 -0
- package/src/task/continuity.ts +179 -0
- package/src/task/execution-cancellation.ts +165 -0
- package/src/task/graph-validate.ts +379 -0
- package/src/task/graph.ts +305 -0
- package/src/task/identity.ts +230 -0
- package/src/task/model.ts +417 -0
- package/src/task/production-scheduler.ts +293 -0
- package/src/task/readiness.ts +229 -0
- package/src/task/scheduler-observability.ts +387 -0
- package/src/task/scheduler.ts +1197 -0
- package/src/task/scheduling-policy.ts +165 -0
- package/src/task/session-authority.ts +148 -0
- package/src/task/session-ownership.ts +211 -0
- package/src/task/store.ts +2887 -0
- package/src/task/sync.ts +343 -0
- package/src/task/trigger.ts +260 -0
- package/src/tools/bash.ts +377 -211
- package/src/tools/code_run.ts +1 -1
- package/src/tools/delete_file.ts +1 -1
- package/src/tools/edit.ts +33 -6
- package/src/tools/evidence.ts +30 -0
- package/src/tools/git.ts +4 -4
- package/src/tools/glob.ts +12 -3
- package/src/tools/grep.ts +1 -1
- package/src/tools/lsp.ts +4 -4
- package/src/tools/mcp_call.ts +11 -4
- package/src/tools/memory.ts +153 -18
- package/src/tools/move_file.ts +1 -1
- package/src/tools/patch.ts +1 -1
- package/src/tools/read_file.ts +1 -1
- package/src/tools/read_image.ts +1 -1
- package/src/tools/submit_result.ts +1 -1
- package/src/tools/task.ts +437 -41
- package/src/tools/todo.ts +662 -35
- package/src/tools/web_fetch.ts +4 -2
- package/src/tools/web_search.ts +9 -3
- package/src/tools/write_file.ts +1 -1
- package/src/ui/assistant/simple.ts +123 -50
- package/src/ui/assistant/turn-status.ts +17 -3
- package/src/ui/contract.ts +184 -0
- package/src/ui/footer.ts +52 -19
- package/src/ui/i18n/en.ts +58 -6
- package/src/ui/i18n/id.ts +58 -6
- package/src/ui/input/prompt-engine.ts +120 -25
- package/src/ui/render/errors.ts +39 -1
- package/src/ui/render/markdown-table.ts +455 -0
- package/src/ui/render/markdown.ts +22 -1
- package/src/ui/render/table-grid.ts +184 -0
- package/src/ui/render/table.ts +15 -76
- package/src/ui/runtime/screen.ts +7 -2
- package/src/ui/runtime/statusline.ts +25 -6
- package/src/ui/tui/app.ts +507 -169
- package/src/ui/tui/transcript.ts +531 -89
- package/vendor/minicore/VENDOR.md +1 -1
- package/vendor/minicore/src/core/budget.ts +25 -25
- package/vendor/minicore/src/core/compact.ts +75 -75
- package/vendor/minicore/src/core/errors.ts +59 -59
- package/vendor/minicore/src/core/events.ts +73 -73
- package/vendor/minicore/src/core/executor.ts +139 -139
- package/vendor/minicore/src/core/history.ts +31 -31
- package/vendor/minicore/src/core/index.ts +41 -41
- package/vendor/minicore/src/core/loop.ts +355 -355
- package/vendor/minicore/src/core/permission.ts +22 -22
- package/vendor/minicore/src/core/provider.ts +39 -39
- package/vendor/minicore/src/core/recovery.ts +35 -35
- package/vendor/minicore/src/core/session.ts +327 -327
- package/vendor/minicore/src/core/snapshot.ts +146 -146
- package/vendor/minicore/src/core/tokens.ts +107 -107
- package/vendor/minicore/src/core/tool.ts +115 -115
- package/vendor/minicore/src/core/types.ts +50 -50
- package/vendor/minicore/src/providers/openai-compat.ts +417 -417
- package/AGENTS.md +0 -45
- package/PLAN.md +0 -491
- package/docs/ARCHITECTURE.html +0 -1248
- package/docs/CONTROL-PLANE-MAP.md +0 -139
- package/docs/HARNESS.md +0 -150
- package/docs/SUMMARY.md +0 -52
- package/docs/UI_RENDER_PIPELINE.md +0 -169
- package/docs/USAGE.md +0 -11
package/cli/commands/config.ts
CHANGED
|
@@ -53,6 +53,20 @@ function showHelp(text: string, asked: boolean, unknown?: string): never {
|
|
|
53
53
|
process.exit(asked ? 0 : 2)
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
+
/**
|
|
57
|
+
* Cetak pesan "usage:" ke stderr lalu keluar 2 (salah pakai = exit 2).
|
|
58
|
+
*
|
|
59
|
+
* SATU writer untuk semua cabang usage — sebelumnya tiap cabang punya
|
|
60
|
+
* panggilan stderr sendiri sehingga tiap cabang menambah writer baru dan
|
|
61
|
+
* menyentuh batas inventaris OAP-008. Pola yang sama dipakai perintah lain
|
|
62
|
+
* ("kumpulkan, tulis sekali"): output ke stderr tetap persis sama, dan
|
|
63
|
+
* `never` menjaga alur kontrol (setelahnya unreachable) seperti `process.exit`.
|
|
64
|
+
*/
|
|
65
|
+
function usageError(message: string): never {
|
|
66
|
+
console.error(message)
|
|
67
|
+
process.exit(2)
|
|
68
|
+
}
|
|
69
|
+
|
|
56
70
|
const isHelpFlag = (s: string | undefined): boolean =>
|
|
57
71
|
s === undefined || s === "--help" || s === "-h"
|
|
58
72
|
|
|
@@ -82,8 +96,7 @@ export async function handleConfig(
|
|
|
82
96
|
const apiKey = getArg("--apiKey")
|
|
83
97
|
const id = getArg("--id")
|
|
84
98
|
if (!baseUrl || !apiKey) {
|
|
85
|
-
|
|
86
|
-
process.exit(2)
|
|
99
|
+
usageError("usage: minicode config add --baseUrl <url> --apiKey <key> [--id <id>]")
|
|
87
100
|
}
|
|
88
101
|
const entry = await detectAndSave(baseUrl, apiKey, id, {
|
|
89
102
|
// Default GLOBAL seperti remove/set-key: menulis provider+key ke
|
|
@@ -131,8 +144,7 @@ export async function handleConfig(
|
|
|
131
144
|
} else if (sub === "remove") {
|
|
132
145
|
const id = positionalArg(args, 2)
|
|
133
146
|
if (!id) {
|
|
134
|
-
|
|
135
|
-
process.exit(2)
|
|
147
|
+
usageError("usage: minicode config remove <id> [--global|--local] [--cwd <dir>]")
|
|
136
148
|
}
|
|
137
149
|
await removeProvider(id, { global: !args.includes("--local"), cwd: getArg("--cwd") })
|
|
138
150
|
console.log(
|
|
@@ -145,13 +157,21 @@ export async function handleConfig(
|
|
|
145
157
|
// jujur). Config hanya menyimpan referensi `keystore:provider:<id>`.
|
|
146
158
|
const id = positionalArg(args, 2)
|
|
147
159
|
if (!id) {
|
|
148
|
-
|
|
149
|
-
process.exit(2)
|
|
160
|
+
usageError("usage: minicode config set-key <id> [--global|--local] [--cwd <dir>]")
|
|
150
161
|
}
|
|
151
162
|
const { deleteSecret, setSecret } = await import("../../src/lib/keystore.ts")
|
|
152
163
|
const key = `provider:${id}`
|
|
153
164
|
if (sub === "delete-key") {
|
|
154
|
-
|
|
165
|
+
// deleteSecret fail-closed: false = store tak bisa dibaca/di-parse atau
|
|
166
|
+
// tak bisa ditulis, jadi key MASIH ADA di berkas. Jangan klaim "Removed"
|
|
167
|
+
// dalam kasus itu.
|
|
168
|
+
const removed = await deleteSecret(key)
|
|
169
|
+
if (!removed) {
|
|
170
|
+
console.error(
|
|
171
|
+
"could not remove stored key (keystore unreadable or unwritable — no change made)",
|
|
172
|
+
)
|
|
173
|
+
process.exit(1)
|
|
174
|
+
}
|
|
155
175
|
console.log(
|
|
156
176
|
`${c.green(glyphs.check)} Removed stored key for ${c.bold(sanitizeAnsiLine(id))} — update config apiKey manually (provider stays disabled until re-set)`,
|
|
157
177
|
)
|
|
@@ -173,7 +193,7 @@ export async function handleConfig(
|
|
|
173
193
|
}
|
|
174
194
|
const backend = await setSecret(key, secret)
|
|
175
195
|
if (!backend) {
|
|
176
|
-
console.error("could not store secret (keystore unavailable
|
|
196
|
+
console.error("could not store secret (keystore unavailable, locked, corrupt, or unwritable)")
|
|
177
197
|
process.exit(1)
|
|
178
198
|
}
|
|
179
199
|
const { loadConfig } = await import("../../src/config.ts")
|
|
@@ -200,8 +220,7 @@ export async function handleConfig(
|
|
|
200
220
|
const baseUrl = getArg("--baseUrl")
|
|
201
221
|
const apiKey = getArg("--apiKey")
|
|
202
222
|
if (!baseUrl || !apiKey) {
|
|
203
|
-
|
|
204
|
-
process.exit(2)
|
|
223
|
+
usageError("usage: minicode config detect --baseUrl <url> --apiKey <key]")
|
|
205
224
|
}
|
|
206
225
|
const { detectModels } = await import("../../src/providers/detect.ts")
|
|
207
226
|
const res = await detectModels(baseUrl, apiKey).catch((e) => {
|
|
@@ -225,12 +244,11 @@ export async function handleConfig(
|
|
|
225
244
|
const url = getArg("--url")
|
|
226
245
|
// Dua bentuk transport: stdio (--command) atau Streamable HTTP (--url).
|
|
227
246
|
if (!id || (!command && !url)) {
|
|
228
|
-
|
|
247
|
+
usageError(
|
|
229
248
|
'usage: minicode config mcp add <id> --command <cmd> --args "<a1,a2>" [--env K=V]\n' +
|
|
230
249
|
" minicode config mcp add <id> --url <https://…> [--header K=V] [--allow-private]\n" +
|
|
231
250
|
" [--global|--local]",
|
|
232
251
|
)
|
|
233
|
-
process.exit(2)
|
|
234
252
|
}
|
|
235
253
|
const env: Record<string, string> = {}
|
|
236
254
|
for (const kv of (getArg("--env") ?? "").split(",")) {
|
|
@@ -312,8 +330,7 @@ export async function handleConfig(
|
|
|
312
330
|
} else if (mcpSub === "remove") {
|
|
313
331
|
const id = positionalArg(args, 3)
|
|
314
332
|
if (!id) {
|
|
315
|
-
|
|
316
|
-
process.exit(2)
|
|
333
|
+
usageError("usage: minicode config mcp remove <id> [--global|--local]")
|
|
317
334
|
}
|
|
318
335
|
await removeMcpServer(id, { global: !args.includes("--local"), cwd: getArg("--cwd") })
|
|
319
336
|
console.log(
|
|
@@ -330,10 +347,9 @@ export async function handleConfig(
|
|
|
330
347
|
const command = getArg("--command")
|
|
331
348
|
const cmdArgsRaw = getArg("--args") ?? ""
|
|
332
349
|
if (!ext || !command) {
|
|
333
|
-
|
|
350
|
+
usageError(
|
|
334
351
|
'usage: minicode config lsp add <ext> --command <cmd> [--args "<arg1,arg2>"] [--env K=V] [--global|--local]',
|
|
335
352
|
)
|
|
336
|
-
process.exit(2)
|
|
337
353
|
}
|
|
338
354
|
const cmdArgs = cmdArgsRaw
|
|
339
355
|
.split(",")
|
|
@@ -379,8 +395,7 @@ export async function handleConfig(
|
|
|
379
395
|
} else if (lspSub === "remove") {
|
|
380
396
|
const ext = positionalArg(args, 3)
|
|
381
397
|
if (!ext) {
|
|
382
|
-
|
|
383
|
-
process.exit(2)
|
|
398
|
+
usageError("usage: minicode config lsp remove <ext> [--global|--local]")
|
|
384
399
|
}
|
|
385
400
|
await removeLspServer(ext, { global: !args.includes("--local"), cwd: getArg("--cwd") })
|
|
386
401
|
console.log(
|
|
@@ -0,0 +1,515 @@
|
|
|
1
|
+
// P2.12 — perintah `minicode daemon …`: composition root untuk host daemon.
|
|
2
|
+
//
|
|
3
|
+
// Semua penimbunan lintas-lapisan terjadi DI SINI (bukan di src/daemon):
|
|
4
|
+
// src/daemon tidak boleh mengimpor cli/, dan sebaliknya. `ControlActions`,
|
|
5
|
+
// `FeedRegistry`, dan capability diterbitkan dari sini.
|
|
6
|
+
//
|
|
7
|
+
// Keluaran mengikuti docs/TERMINAL_CONTRACT.md: perintah human = stdout polos
|
|
8
|
+
// (tanpa ANSI/cursor control), diagnostik = stderr. Setiap jalur mengumpulkan
|
|
9
|
+
// output ke array lalu menulis SEKALI — bukan satu tulis per baris —
|
|
10
|
+
// agar jumlah writer tetap kecil dan terinventaris.
|
|
11
|
+
|
|
12
|
+
import { issueCapabilityFromEndpoint } from "../../src/daemon/capability.ts"
|
|
13
|
+
import { DaemonClient, probeDaemon } from "../../src/daemon/client.ts"
|
|
14
|
+
import type { ControlActions, HostedSessionInfo } from "../../src/daemon/control.ts"
|
|
15
|
+
import { type DaemonEndpoint, readEndpoint } from "../../src/daemon/discovery.ts"
|
|
16
|
+
import type { SessionFeed } from "../../src/daemon/feed.ts"
|
|
17
|
+
import { createStoreFeed } from "../../src/daemon/feed.ts"
|
|
18
|
+
import type { DaemonHost } from "../../src/daemon/host.ts"
|
|
19
|
+
import { DAEMON_SCOPES, type DaemonScope } from "../../src/daemon/protocol.ts"
|
|
20
|
+
import { sanitizeLabel } from "../../src/daemon/sanitize.ts"
|
|
21
|
+
import { DURABILITY } from "../../src/presentation/events.ts"
|
|
22
|
+
import {
|
|
23
|
+
type RuntimeProductionMode,
|
|
24
|
+
resolveRuntimeMode,
|
|
25
|
+
} from "../../src/runtime/production-execution.ts"
|
|
26
|
+
import { flagNameOf, valueFlags } from "../args.ts"
|
|
27
|
+
import type { CliSession, CliSessionOptions } from "../setup.ts"
|
|
28
|
+
|
|
29
|
+
export async function handleDaemon(
|
|
30
|
+
// P11.3 — router mengirim argv scoped TANPA token subcommand ("daemon"):
|
|
31
|
+
// flag global yang dikenal (sebelum subcommand) + semua token sesudahnya.
|
|
32
|
+
// Irisan lokal `args[0] === "daemon"` lama hanya benar bila daemon token
|
|
33
|
+
// pertama; dengan flag global mendahului, token routing dibaca sebagai
|
|
34
|
+
// nama aksi ("unknown daemon subcommand: daemon", exit 2 palsu). Handler
|
|
35
|
+
// mempercayai argv yang sudah scoped — jangan iris lagi di sini.
|
|
36
|
+
sub: string[],
|
|
37
|
+
getArg: (name: string) => string | undefined,
|
|
38
|
+
HELP: string,
|
|
39
|
+
): Promise<void> {
|
|
40
|
+
const first = firstPositional(sub)
|
|
41
|
+
// Bantuan cetak `<mulai|...>` (bahasa Indonesia) tapi perintahnya `start`;
|
|
42
|
+
// terima keduanya supaya yang menyalin dari --help tidak kena "unknown".
|
|
43
|
+
const action = first === "mulai" ? "start" : (first ?? "status")
|
|
44
|
+
// `--json` dibaca via includes (tak tergantung posisi): argv scoped selalu
|
|
45
|
+
// memuat flag global + token setelah subcommand. `getArg` (= subGetArg
|
|
46
|
+
// router) membaca --cwd/--port/--prompt/--who/--scopes/--ttl di mana pun.
|
|
47
|
+
const json = sub.includes("--json")
|
|
48
|
+
const cwdRaw = getArg("--cwd")
|
|
49
|
+
const cwd = cwdRaw ? cwdRaw : undefined
|
|
50
|
+
|
|
51
|
+
if (action === "help" || sub.includes("--help") || sub.includes("-h")) {
|
|
52
|
+
process.stdout.write(`${DAEMON_HELP}\n`)
|
|
53
|
+
// Nilai dispatch DIABAIKAN cli/index.ts (lihat catatannya: handler subcommand
|
|
54
|
+
// keluar sendiri). Tanpa exit, proses jatuh ke jalur prompt biasa dan
|
|
55
|
+
// "minicode daemon help" justru mencoba menjalankan sesi.
|
|
56
|
+
process.exit(0)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (action === "start") {
|
|
60
|
+
await startDaemon(sub, getArg, cwd, json)
|
|
61
|
+
return
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (action === "status") {
|
|
65
|
+
await statusDaemon(cwd, json)
|
|
66
|
+
return
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (action === "stop") {
|
|
70
|
+
await stopDaemon(cwd, json)
|
|
71
|
+
return
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (action === "issue") {
|
|
75
|
+
await issueCapability(cwd, getArg, json)
|
|
76
|
+
return
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (action === "sessions") {
|
|
80
|
+
await listSessions(cwd, json)
|
|
81
|
+
return
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
process.stderr.write(`unknown daemon subcommand: ${sanitizeLabel(action, 40)}\n${DAEMON_HELP}\n`)
|
|
85
|
+
void HELP
|
|
86
|
+
process.exit(2)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const DAEMON_HELP = `minicode daemon <mulai|status|stop|issue|sessions|help>
|
|
90
|
+
|
|
91
|
+
start [--port N] [--cwd D] [--prompt P] [--session S] [--runtime <mode>] [--json]
|
|
92
|
+
Jalankan host daemon (blocking). Tanpa --prompt hanya melayani
|
|
93
|
+
konsumen; dengan --prompt sesi di-host di dalam proses daemon.
|
|
94
|
+
--runtime constructed|owned menyalakan runtime ter-supervisi pada
|
|
95
|
+
sesi yang di-host (default: off = jalur legacy).
|
|
96
|
+
status [--cwd D] [--json]
|
|
97
|
+
Baca endpoint + PROBE koneksi. "alive" hanya bila probe berhasil.
|
|
98
|
+
stop [--cwd D] [--json]
|
|
99
|
+
Minta daemon berhenti lewat kontrol (admin scope).
|
|
100
|
+
issue --scopes <a,b> --who <nama> [--ttl <ms>] [--cwd D] [--json]
|
|
101
|
+
Terbitkan capability bercakupan dari berkas endpoint.
|
|
102
|
+
sessions[--cwd D] [--json]
|
|
103
|
+
Daftar sesi yang di-host daemon.`
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Token positional pertama yang benar-benar subcommand: lewati flag dan
|
|
107
|
+
* NILAINYA (daftar `valueFlags` di cli/args.ts). Tanpa ini,
|
|
108
|
+
* `daemon --cwd D:\x` akan membaca "D:\x" sebagai nama subcommand.
|
|
109
|
+
*/
|
|
110
|
+
function firstPositional(argv: string[]): string | undefined {
|
|
111
|
+
for (let i = 0; i < argv.length; i++) {
|
|
112
|
+
const token = argv[i]
|
|
113
|
+
if (!token) continue
|
|
114
|
+
if (token === "--") return argv[i + 1]
|
|
115
|
+
const flag = flagNameOf(token)
|
|
116
|
+
if (flag) {
|
|
117
|
+
if (valueFlags.has(flag) && !token.includes("=")) i++
|
|
118
|
+
continue
|
|
119
|
+
}
|
|
120
|
+
// flag tak dikenal: jangan dianggap subcommand (konsisten dengan hasFlag)
|
|
121
|
+
if (token.startsWith("-")) continue
|
|
122
|
+
return token
|
|
123
|
+
}
|
|
124
|
+
return undefined
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Tulis keluaran SEKALI, lalu (opsional) keluar.
|
|
129
|
+
*
|
|
130
|
+
* `exitCode = null` hanya untuk jalur yang TIDAK boleh berakhir di sini —
|
|
131
|
+
* `start` masih harus melayani konsumen setelah baris "listening" tercetak.
|
|
132
|
+
* Semua subcommand lain selalu keluar, karena `dispatch` di cli/index.ts
|
|
133
|
+
* mengabaikan hasilnya (komentar di sana: handler memanggil process.exit).
|
|
134
|
+
*/
|
|
135
|
+
function emit(lines: string[], json: string | null, exitCode: number | null = null): void {
|
|
136
|
+
// SATU tulisan per stream — lihat komentar kepala berkas.
|
|
137
|
+
if (json !== null) process.stdout.write(`${json}\n`)
|
|
138
|
+
else if (lines.length > 0) process.stdout.write(`${lines.join("\n")}\n`)
|
|
139
|
+
if (exitCode !== null) process.exit(exitCode)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Tulis diagnostik manusia ke stderr + payload JSON ke stdout, lalu keluar.
|
|
144
|
+
*
|
|
145
|
+
* `json` adalah payload MENTAH (objek) — encoding terjadi SEKALI di sini;
|
|
146
|
+
* `null` = jalur ini memang tak punya kontrak JSON. Jalur kegagalan `stop` dan
|
|
147
|
+
* `sessions` dulu mewariskan string yang SUDAH `JSON.stringify`, jadi payload
|
|
148
|
+
* ter-encode dua kali: stdout berisi string-JSON terbungkus dan
|
|
149
|
+
* `JSON.parse(stdout)` pada konsumen mesin menghasilkan string, bukan objek.
|
|
150
|
+
* Jangan me-stringify di call site.
|
|
151
|
+
*/
|
|
152
|
+
function fail(json: unknown, human: string, code = 1): never {
|
|
153
|
+
process.stderr.write(`${human}\n`)
|
|
154
|
+
if (json !== null) process.stdout.write(`${JSON.stringify(json)}\n`)
|
|
155
|
+
process.exit(code)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async function openClient(
|
|
159
|
+
cwd: string | undefined,
|
|
160
|
+
scopes: DaemonScope[],
|
|
161
|
+
who: string,
|
|
162
|
+
): Promise<{ client: DaemonClient; ep: DaemonEndpoint }> {
|
|
163
|
+
const ep = readEndpoint(cwd)
|
|
164
|
+
if (!ep) fail(null, "daemon: tidak ada endpoint — jalankan `minicode daemon start` dulu", 3)
|
|
165
|
+
const cap = issueCapabilityFromEndpoint(ep, { scopes, who })
|
|
166
|
+
const client = await DaemonClient.connect({
|
|
167
|
+
target: { host: ep.host, port: ep.port },
|
|
168
|
+
capability: cap,
|
|
169
|
+
consumer: who,
|
|
170
|
+
})
|
|
171
|
+
return { client, ep }
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// ---------------------------------------------------------------------------
|
|
175
|
+
// start
|
|
176
|
+
// ---------------------------------------------------------------------------
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* P13.3 Stage C — kebijakan scheduler daemon.
|
|
180
|
+
*
|
|
181
|
+
* Hanya jalur eksplisit `--runtime owned` yang menyalakan scheduler. Default
|
|
182
|
+
* legacy (`off`) dan `constructed` TIDAK menyalakannya: keduanya bukan jalur
|
|
183
|
+
* ownership runtime yang menyediakan admission, TaskStore, dan lease yang
|
|
184
|
+
* dibutuhkan kerja durable. Mengecualikan satu pun dari itu berarti scheduler
|
|
185
|
+
* berjalan tanpa bukti yang menjadi syarat kontinuitasnya.
|
|
186
|
+
*/
|
|
187
|
+
export function schedulerEnabledForDaemon(mode: RuntimeProductionMode): boolean {
|
|
188
|
+
return mode === "owned"
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export async function startDaemonHostedRuntime(opts: {
|
|
192
|
+
readonly sub: readonly string[]
|
|
193
|
+
readonly getArg: (name: string) => string | undefined
|
|
194
|
+
readonly cwd: string | undefined
|
|
195
|
+
/**
|
|
196
|
+
* [P13.6] Seam uji deterministik: injeksi append presentasi untuk tes
|
|
197
|
+
* forensik live-vs-durable. Produksi TIDAK mengeset ini (default jalur
|
|
198
|
+
* append sesungguhnya).
|
|
199
|
+
*/
|
|
200
|
+
readonly presentationAppend?: CliSessionOptions["presentationAppend"]
|
|
201
|
+
}): Promise<DaemonHostedRuntime> {
|
|
202
|
+
const { sub, getArg, cwd } = opts
|
|
203
|
+
const portRaw = getArg("--port")
|
|
204
|
+
const port = portRaw !== undefined && /^\d+$/.test(portRaw) ? Number(portRaw) : 0
|
|
205
|
+
const prompt = getArg("--prompt")
|
|
206
|
+
const sessionFlag = getArg("--session") ?? ""
|
|
207
|
+
// [P13.2] Mode runtime memakai FLAG GLOBAL YANG SAMA dengan CLI, default
|
|
208
|
+
// "off" → jalur legacy utuh (tak ada runtime yang dibangun, tak ada jurnal
|
|
209
|
+
// runtime, tak ada perubahan pada cara turn dieksekusi). Daemon yang mau
|
|
210
|
+
// menjalankan runtime ter-supervisi memintanya eksplisit.
|
|
211
|
+
const runtimeMode = resolveRuntimeMode(sub).mode
|
|
212
|
+
// [P13.3 Stage C] Scheduler mengikuti mode runtime, bukan flag terpisah:
|
|
213
|
+
// daemon `owned` memang ingin kerja durable berlanjut; mode lain tetap inert.
|
|
214
|
+
const schedulerEnabled = schedulerEnabledForDaemon(runtimeMode)
|
|
215
|
+
|
|
216
|
+
const { DaemonHost } = await import("../../src/daemon/host.ts")
|
|
217
|
+
const feeds = new Map<string, SessionFeed>()
|
|
218
|
+
const hosted = new Map<string, HostedSessionInfo>()
|
|
219
|
+
|
|
220
|
+
// Holder terpisah: aksi dipanggil BELUM tentu saat host sudah ada (bisa
|
|
221
|
+
// lewat kontrol lebih dulu), dan `const` berikutnya akan menolak dibaca
|
|
222
|
+
// sebelum inisialisasi. Dengan holder, "host belum siap" = penolakan jujur.
|
|
223
|
+
let hostRef: DaemonHost | null = null
|
|
224
|
+
|
|
225
|
+
// [P13.2] Holder sesi: host dibuat lebih dulu, sesi menyusul. Penutupan sesi
|
|
226
|
+
// harus idempoten (shutdown bisa dipanggil berkali-kali) dan harus MENUNGGU
|
|
227
|
+
// lifecycle sesi selesai — termasuk pembersihan anak proses yang disupervisi.
|
|
228
|
+
let sessionRef: CliSession | null = null
|
|
229
|
+
let sessionClosed = false
|
|
230
|
+
const closeHostedSession = async (): Promise<void> => {
|
|
231
|
+
if (sessionClosed) return
|
|
232
|
+
sessionClosed = true
|
|
233
|
+
const s = sessionRef
|
|
234
|
+
sessionRef = null
|
|
235
|
+
if (!s) return
|
|
236
|
+
await s.close()
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// Aksi kontrol dibangun dari state yang benar-benar diketahui proses ini.
|
|
240
|
+
// Tanpa sesi yang di-host, operasi yang butuh aksi MENOLAK — bukan berpura-
|
|
241
|
+
// pura berhasil (lihat control.ts).
|
|
242
|
+
const actions: ControlActions = {
|
|
243
|
+
listSessions: () => [...hosted.values()],
|
|
244
|
+
sessionStatus: (sid) => hosted.get(sid) ?? null,
|
|
245
|
+
interrupt: (sid) => {
|
|
246
|
+
void sid
|
|
247
|
+
return { ok: false, code: "RUN_TERMINAL", message: "tidak ada jalur interupsi pada sesi ini" }
|
|
248
|
+
},
|
|
249
|
+
cancel: (sid) => {
|
|
250
|
+
void sid
|
|
251
|
+
return {
|
|
252
|
+
ok: false,
|
|
253
|
+
code: "RUN_TERMINAL",
|
|
254
|
+
message: "tidak ada jalur pembatalan pada sesi ini",
|
|
255
|
+
}
|
|
256
|
+
},
|
|
257
|
+
shutdown: (reason) => {
|
|
258
|
+
const h = hostRef
|
|
259
|
+
if (!h) return
|
|
260
|
+
void h
|
|
261
|
+
.shutdown(reason)
|
|
262
|
+
.then(() => process.exit(0))
|
|
263
|
+
.catch(() => process.exit(1))
|
|
264
|
+
},
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const host: DaemonHost = await DaemonHost.start({
|
|
268
|
+
...(cwd !== undefined ? { cwd } : {}),
|
|
269
|
+
port,
|
|
270
|
+
feeds: {
|
|
271
|
+
get: (sid) => feeds.get(sid) ?? createStoreFeed(sid, cwd),
|
|
272
|
+
known: () => [...feeds.keys()],
|
|
273
|
+
},
|
|
274
|
+
actions,
|
|
275
|
+
// [P13.2] Sesi yang di-host ditutup saat daemon berhenti: lifecycle-nya
|
|
276
|
+
// (jurnal runtime + anak proses yang disupervisi) SELESAI sebelum daemon
|
|
277
|
+
// menutup dirinya. Tanpa ini, proses anak bisa tertinggal (yatim).
|
|
278
|
+
closeHostedSession: async () => {
|
|
279
|
+
await closeHostedSession()
|
|
280
|
+
},
|
|
281
|
+
...(sessionFlag ? { workspace: sessionFlag } : {}),
|
|
282
|
+
})
|
|
283
|
+
hostRef = host
|
|
284
|
+
|
|
285
|
+
let ctx: CliSession | null = null
|
|
286
|
+
if (prompt !== undefined && prompt.trim().length > 0) {
|
|
287
|
+
const { createCliSession } = await import("../setup.ts")
|
|
288
|
+
try {
|
|
289
|
+
ctx = await createCliSession({
|
|
290
|
+
cwd,
|
|
291
|
+
sessionId: sessionFlag,
|
|
292
|
+
prompt,
|
|
293
|
+
enterRepl: false,
|
|
294
|
+
verbose: false,
|
|
295
|
+
allowAll: false,
|
|
296
|
+
ask: true,
|
|
297
|
+
// [P13.6] Ask-mode pada sesi hosted: prompt TTY selalu deny di proses
|
|
298
|
+
// daemon non-TTY. Satu-satunya jembatan sah adalah broker persetujuan
|
|
299
|
+
// durable (approvals.ts): baris tersimpan, konsumen scope `approve`
|
|
300
|
+
// mengusulkan lewat `approval.decide`, restart ⇒ UNKNOWN, shutdown ⇒
|
|
301
|
+
// DENY. Tanpa pemasangan ini, seluruh op approval tidak tersambung ke
|
|
302
|
+
// sesi mana pun (fail-closed, bukan crash).
|
|
303
|
+
permissionAsk: host.approvals.asPermissionAsk({
|
|
304
|
+
sid: () => sessionRef?.sessionId ?? "",
|
|
305
|
+
runId: () => null,
|
|
306
|
+
}),
|
|
307
|
+
plan: false,
|
|
308
|
+
allowlist: false,
|
|
309
|
+
verify: false,
|
|
310
|
+
// [P13.2] Mode runtime yang sama dengan CLI → komposisi yang di-host
|
|
311
|
+
// punya jalur ownership proses + status kanonik yang sama.
|
|
312
|
+
runtimeMode,
|
|
313
|
+
// [P13.3 Stage C] Hanya `owned` yang menyalakan scheduler; `off` dan
|
|
314
|
+
// `constructed` mengirim false sehingga gate tetap inert.
|
|
315
|
+
schedulerEnabled,
|
|
316
|
+
// [P13.6] Seam uji forensik (produksi tak mengeset).
|
|
317
|
+
...(opts.presentationAppend ? { presentationAppend: opts.presentationAppend } : {}),
|
|
318
|
+
})
|
|
319
|
+
} catch (e) {
|
|
320
|
+
// [P13.2] Sesi gagal dibangun → daemon TIDAK boleh meninggalkan socket
|
|
321
|
+
// listening di belakang: host hidup tanpa sesi = daemon zombie yang tak
|
|
322
|
+
// bisa dilayani dan tak berguna. Host ditutup lebih dulu, lalu kegagalan
|
|
323
|
+
// ASLI diteruskan (bukan ditelan).
|
|
324
|
+
try {
|
|
325
|
+
await host.shutdown("session-setup-failed")
|
|
326
|
+
} catch {
|
|
327
|
+
// Kegagalan shutdown host tak menutupi kegagalan sesi yang sebenarnya.
|
|
328
|
+
}
|
|
329
|
+
throw e
|
|
330
|
+
}
|
|
331
|
+
sessionRef = ctx
|
|
332
|
+
const durable = createStoreFeed(ctx.sessionId, cwd)
|
|
333
|
+
const session = ctx
|
|
334
|
+
feeds.set(session.sessionId, {
|
|
335
|
+
// Durable (kepala/frontier/replay) diambil dari toko, live dari sesi
|
|
336
|
+
// hidup. Memakai kepala durable untuk replay sengaja: replay MEMBACA
|
|
337
|
+
// toko, jadi angka yang dibaca konsumen harus memang milik toko.
|
|
338
|
+
sid: session.sessionId,
|
|
339
|
+
hosted: true,
|
|
340
|
+
head: durable.head,
|
|
341
|
+
frontiers: durable.frontiers,
|
|
342
|
+
readRange: durable.readRange,
|
|
343
|
+
// [P13.5] Feed live memakai DomainEvent mentah, BUKAN proyeksi UI.
|
|
344
|
+
// Proyeksi memakai `seq`, sedangkan kontrak feed/replay memakai
|
|
345
|
+
// `eventSeq`; cast lama membuat seluruh event live diabaikan fanout.
|
|
346
|
+
// Hanya event durable yang diteruskan supaya bahasa live = bahasa replay
|
|
347
|
+
// (delta non-durable tetap milik UI, bukan riwayat sesi).
|
|
348
|
+
liveSubscribe: (fn) =>
|
|
349
|
+
session.onDomainEvent((event) => {
|
|
350
|
+
if (!DURABILITY[event.type]?.durable) return
|
|
351
|
+
fn(event)
|
|
352
|
+
}),
|
|
353
|
+
})
|
|
354
|
+
hosted.set(session.sessionId, {
|
|
355
|
+
sid: session.sessionId,
|
|
356
|
+
hosted: true,
|
|
357
|
+
writerEpoch: session.writerEpoch,
|
|
358
|
+
runId: null,
|
|
359
|
+
runStatus: null,
|
|
360
|
+
presentationHead: durable.head(),
|
|
361
|
+
})
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
return { host, session: ctx, closeHostedSession }
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* [P13.2] Hasil start daemon: host + sesi yang di-host.
|
|
369
|
+
*
|
|
370
|
+
* Dipisah dari `startDaemon` supaya lifecycle-nya bisa diuji tanpa menjalankan
|
|
371
|
+
* perintah yang "tak pernah selesai" (loop serve). Fungsi ini TIDAK menulis ke
|
|
372
|
+
* stdout/stderr — semua keluaran tetap milik `startDaemon` (writer inventory).
|
|
373
|
+
*/
|
|
374
|
+
export interface DaemonHostedRuntime {
|
|
375
|
+
readonly host: DaemonHost
|
|
376
|
+
/** Sesi yang di-host (null bila daemon dijalankan tanpa `--prompt`). */
|
|
377
|
+
readonly session: CliSession | null
|
|
378
|
+
/** Tutup sesi yang di-host (idempoten). Dipakai daemon saat shutdown. */
|
|
379
|
+
readonly closeHostedSession: () => Promise<void>
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
async function startDaemon(
|
|
383
|
+
sub: string[],
|
|
384
|
+
getArg: (name: string) => string | undefined,
|
|
385
|
+
cwd: string | undefined,
|
|
386
|
+
json: boolean,
|
|
387
|
+
): Promise<void> {
|
|
388
|
+
const { host, session } = await startDaemonHostedRuntime({ sub, getArg, cwd })
|
|
389
|
+
|
|
390
|
+
const lines = [
|
|
391
|
+
`daemon: listening on ${host.port} (incarnation ${host.incarnation})`,
|
|
392
|
+
`endpoint: ${host.endpointPath ?? "?"}`,
|
|
393
|
+
`capability: ${host.issueCapability({ scopes: [...DAEMON_SCOPES], who: "operator" })}`,
|
|
394
|
+
]
|
|
395
|
+
const payload = {
|
|
396
|
+
ok: true,
|
|
397
|
+
port: host.port,
|
|
398
|
+
incarnation: host.incarnation,
|
|
399
|
+
endpoint: host.endpointPath,
|
|
400
|
+
hostedSessions: session ? [session.sessionId] : [],
|
|
401
|
+
}
|
|
402
|
+
emit(lines, json ? JSON.stringify(payload) : null)
|
|
403
|
+
|
|
404
|
+
const onSignal = () => {
|
|
405
|
+
void host
|
|
406
|
+
.shutdown("signal")
|
|
407
|
+
.then(() => process.exit(0))
|
|
408
|
+
// Kegagalan shutdown (mis. sesi yang di-host tak bisa ditutup) TIDAK boleh
|
|
409
|
+
// hilang: proses keluar dengan kode gagal, bukan "beres".
|
|
410
|
+
.catch(() => process.exit(1))
|
|
411
|
+
}
|
|
412
|
+
process.on("SIGINT", onSignal)
|
|
413
|
+
process.on("SIGTERM", onSignal)
|
|
414
|
+
|
|
415
|
+
// Biarkan proses hidup melayani konsumen; server listen menahan event loop.
|
|
416
|
+
await new Promise<void>(() => {
|
|
417
|
+
/* sengaja tak pernah selesai sampai signal/control shutdown */
|
|
418
|
+
})
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// ---------------------------------------------------------------------------
|
|
422
|
+
// status / stop / issue / sessions
|
|
423
|
+
// ---------------------------------------------------------------------------
|
|
424
|
+
|
|
425
|
+
async function statusDaemon(cwd: string | undefined, json: boolean): Promise<void> {
|
|
426
|
+
const probe = await probeDaemon(cwd)
|
|
427
|
+
const payload = {
|
|
428
|
+
alive: probe.alive,
|
|
429
|
+
reason: probe.reason,
|
|
430
|
+
status: probe.discovery.status,
|
|
431
|
+
incarnation: probe.discovery.endpoint?.incarnation ?? null,
|
|
432
|
+
port: probe.discovery.endpoint?.port ?? null,
|
|
433
|
+
leaseAgeMs: probe.discovery.lease ? Date.now() - probe.discovery.lease.updatedAt : null,
|
|
434
|
+
}
|
|
435
|
+
const lines = probe.alive
|
|
436
|
+
? [
|
|
437
|
+
`daemon: alive on ${probe.target?.host}:${probe.target?.port}`,
|
|
438
|
+
`incarnation: ${payload.incarnation ?? "?"}`,
|
|
439
|
+
`lease age: ${payload.leaseAgeMs ?? "?"}ms`,
|
|
440
|
+
]
|
|
441
|
+
: [`daemon: not alive (${probe.reason})`, `discovery: ${probe.discovery.status}`]
|
|
442
|
+
emit(lines, json ? JSON.stringify(payload) : null, probe.alive ? 0 : 3)
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
async function stopDaemon(cwd: string | undefined, json: boolean): Promise<void> {
|
|
446
|
+
const probe = await probeDaemon(cwd)
|
|
447
|
+
if (!probe.alive)
|
|
448
|
+
// Objek mentah, bukan string: `fail()` yang meng-encode (lihat kontraknya).
|
|
449
|
+
fail(json ? { ok: false, reason: probe.reason } : null, `daemon: ${probe.reason}`, 3)
|
|
450
|
+
try {
|
|
451
|
+
const { client } = await openClient(cwd, ["admin"], "operator")
|
|
452
|
+
const res = await client.control("daemon.shutdown", { reason: "cli" }, `stop-${Date.now()}`)
|
|
453
|
+
client.close()
|
|
454
|
+
emit(
|
|
455
|
+
res.ok ? ["daemon: shutdown diminta"] : [`daemon: ditolak ${res.refusal?.code ?? ""}`],
|
|
456
|
+
json ? JSON.stringify({ ok: res.ok, refusal: res.refusal ?? null }) : null,
|
|
457
|
+
res.ok ? 0 : 1,
|
|
458
|
+
)
|
|
459
|
+
} catch (e) {
|
|
460
|
+
fail(null, `daemon: gagal menghubungi — ${String((e as Error).message ?? e)}`, 1)
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
async function issueCapability(
|
|
465
|
+
cwd: string | undefined,
|
|
466
|
+
getArg: (name: string) => string | undefined,
|
|
467
|
+
json: boolean,
|
|
468
|
+
): Promise<void> {
|
|
469
|
+
const who = getArg("--who") ?? "consumer"
|
|
470
|
+
const raw = getArg("--scopes") ?? ""
|
|
471
|
+
const ttlRaw = getArg("--ttl")
|
|
472
|
+
const scopes = raw
|
|
473
|
+
.split(",")
|
|
474
|
+
.map((s) => s.trim())
|
|
475
|
+
.filter((s): s is DaemonScope => (DAEMON_SCOPES as readonly string[]).includes(s))
|
|
476
|
+
if (scopes.length === 0) {
|
|
477
|
+
fail(
|
|
478
|
+
null,
|
|
479
|
+
`daemon issue: --scopes wajib berisi salah satu dari: ${DAEMON_SCOPES.join(", ")}`,
|
|
480
|
+
2,
|
|
481
|
+
)
|
|
482
|
+
}
|
|
483
|
+
const ep = readEndpoint(cwd)
|
|
484
|
+
if (!ep) fail(null, "daemon issue: tidak ada endpoint", 3)
|
|
485
|
+
const ttl = ttlRaw !== undefined && /^\d+$/.test(ttlRaw) ? Number(ttlRaw) : undefined
|
|
486
|
+
const token = issueCapabilityFromEndpoint(ep, {
|
|
487
|
+
scopes,
|
|
488
|
+
who,
|
|
489
|
+
...(ttl !== undefined ? { ttlMs: ttl } : {}),
|
|
490
|
+
})
|
|
491
|
+
emit([token], json ? JSON.stringify({ ok: true, capability: token, scopes, who }) : null, 0)
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
async function listSessions(cwd: string | undefined, json: boolean): Promise<void> {
|
|
495
|
+
try {
|
|
496
|
+
const { client } = await openClient(cwd, ["read:session"], "operator")
|
|
497
|
+
const res = await client.control("session.list", {}, `list-${Date.now()}`)
|
|
498
|
+
client.close()
|
|
499
|
+
if (!res.ok)
|
|
500
|
+
// Objek mentah — `fail()` meng-encode sekali (D-1).
|
|
501
|
+
fail(
|
|
502
|
+
json ? { ok: false, refusal: res.refusal } : null,
|
|
503
|
+
`daemon: ${res.refusal?.code} ${res.refusal?.message}`,
|
|
504
|
+
1,
|
|
505
|
+
)
|
|
506
|
+
const rows = Array.isArray(res.result) ? (res.result as HostedSessionInfo[]) : []
|
|
507
|
+
const lines =
|
|
508
|
+
rows.length === 0
|
|
509
|
+
? ["(tidak ada sesi yang di-host)"]
|
|
510
|
+
: rows.map((r) => `${r.sid} head=${r.presentationHead} run=${r.runStatus ?? "-"}`)
|
|
511
|
+
emit(lines, json ? JSON.stringify({ ok: true, sessions: rows }) : null, 0)
|
|
512
|
+
} catch (e) {
|
|
513
|
+
fail(null, `daemon: gagal menghubungi — ${String((e as Error).message ?? e)}`, 1)
|
|
514
|
+
}
|
|
515
|
+
}
|