@open-mercato/starter 0.10.1-develop.7983.1.fd91207efe → 0.10.1-develop.7990.1.82d0a183c5
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/README.md +9 -1
- package/package.json +1 -1
- package/src/__tests__/setup-logs.test.mjs +318 -0
- package/src/__tests__/setup-streaming.test.mjs +307 -0
- package/src/__tests__/stage-progress.test.mjs +149 -0
- package/src/cli.mjs +90 -41
- package/src/compose.mjs +48 -0
- package/src/infra-preflight.mjs +3 -2
- package/src/infra.mjs +3 -2
- package/src/providers.mjs +11 -10
- package/src/setup-logs.mjs +201 -0
- package/src/steps.mjs +79 -43
- package/src/ui.mjs +41 -20
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import { EventEmitter } from 'node:events'
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import os from 'node:os'
|
|
5
|
+
import path from 'node:path'
|
|
6
|
+
import { spawnSync } from 'node:child_process'
|
|
7
|
+
import test from 'node:test'
|
|
8
|
+
import vm from 'node:vm'
|
|
9
|
+
import { createSpinner } from '../ui.mjs'
|
|
10
|
+
import { createSetupLogs } from '../setup-logs.mjs'
|
|
11
|
+
import { llmProviderStep, runSteps } from '../steps.mjs'
|
|
12
|
+
|
|
13
|
+
test('stage headings restore the original prefix and style only Expected:', () => {
|
|
14
|
+
const script = `Object.defineProperty(process.stdout, 'isTTY', {value:true}); const {stepHeader}=await import(${JSON.stringify(new URL('../ui.mjs', import.meta.url).href)}); stepHeader(9,9,'Database','migrations + seed')`
|
|
15
|
+
const env = { ...process.env, TERM: 'xterm' }
|
|
16
|
+
delete env.NO_COLOR
|
|
17
|
+
const result = spawnSync(process.execPath, ['--input-type=module', '-e', script], { env, encoding: 'utf8' })
|
|
18
|
+
assert.equal(result.status, 0)
|
|
19
|
+
assert.match(result.stdout.replace(/\u001b\[[0-9;]*m/g, ''), /\n ── Step 9\/9 Database\n Expected:/)
|
|
20
|
+
assert.doesNotMatch(result.stdout, /🧭/)
|
|
21
|
+
assert.match(result.stdout, /\x1b\[1m\x1b\[33mExpected:\x1b\[0m\x1b\[0m migrations \+ seed/)
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
test('working spinner animates with elapsed time, pauses, and is replaced on completion', () => {
|
|
25
|
+
const output = []
|
|
26
|
+
const statuses = []
|
|
27
|
+
let tick
|
|
28
|
+
let elapsed = 0
|
|
29
|
+
let cleared = 0
|
|
30
|
+
const spinner = createSpinner('working…', {
|
|
31
|
+
output: { isTTY: true, columns: 80, write: (chunk) => output.push(chunk) },
|
|
32
|
+
env: {}, log: (line) => statuses.push(line), frames: ['⠋', '⠙'], now: () => elapsed,
|
|
33
|
+
setIntervalImpl: (callback) => { tick = callback; return 1 }, clearIntervalImpl: () => { cleared += 1 },
|
|
34
|
+
})
|
|
35
|
+
assert.match(output.join(''), /⠋ working….*\(0s\)/)
|
|
36
|
+
elapsed = 12000
|
|
37
|
+
tick()
|
|
38
|
+
assert.match(output.join(''), /⠙ working….*\(12s\)/)
|
|
39
|
+
spinner.pause()
|
|
40
|
+
assert.equal(cleared, 1)
|
|
41
|
+
spinner.resume()
|
|
42
|
+
spinner.stop('ok', 'done in 48s')
|
|
43
|
+
const length = output.length
|
|
44
|
+
spinner.resume()
|
|
45
|
+
assert.equal(output.length, length, 'stopped activity never restarts')
|
|
46
|
+
assert.match(statuses.join(''), /✅ done in 48s/)
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
test('raw-log toggles pause working output and resume it only after folding', () => {
|
|
50
|
+
const input = new EventEmitter()
|
|
51
|
+
Object.assign(input, { isTTY: true, isRaw: false, setRawMode() {}, resume() {}, pause() {} })
|
|
52
|
+
const events = []
|
|
53
|
+
const logs = createSetupLogs({ input, output: { isTTY: true, write() {} }, env: {} })
|
|
54
|
+
logs.start()
|
|
55
|
+
logs.setActivity({ pause: () => events.push('pause'), resume: () => events.push('resume'), stop: () => events.push('stop') })
|
|
56
|
+
input.emit('data', 'd')
|
|
57
|
+
logs.resumeActivity()
|
|
58
|
+
assert.deepEqual(events, ['resume', 'pause'], 'progress does not resume while raw logs are visible')
|
|
59
|
+
input.emit('data', 'd')
|
|
60
|
+
assert.deepEqual(events, ['resume', 'pause', 'resume'])
|
|
61
|
+
logs.stop()
|
|
62
|
+
assert.ok(events.includes('stop'))
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
test('stage activity stops on success, skip and failure and never starts over a prompt', async () => {
|
|
66
|
+
for (const mode of ['success', 'skip', 'failure', 'prompt']) {
|
|
67
|
+
const events = []
|
|
68
|
+
const logs = {
|
|
69
|
+
interactive: true, start() {}, stop() {}, suspend() {}, resume() {}, record() {}, log() {}, show() { events.push('reveal') },
|
|
70
|
+
setActivity(activity) { if (activity) { events.push('attach'); activity.resume() } }, resumeActivity() {},
|
|
71
|
+
}
|
|
72
|
+
const ctx = { flags: {}, logs, log: (line) => events.push(String(line)), createSpinnerImpl(label) {
|
|
73
|
+
assert.equal(label, '⚙️ working…')
|
|
74
|
+
events.push('create')
|
|
75
|
+
return { pause() { events.push('pause') }, resume() { events.push('resume') }, stop() { events.push('stop') } }
|
|
76
|
+
} }
|
|
77
|
+
await runSteps([{ id: mode, title: 'Stage', interactive: mode === 'prompt',
|
|
78
|
+
async check() { return { ok: mode === 'skip' } },
|
|
79
|
+
async apply() { if (mode === 'failure') throw new Error('failed') },
|
|
80
|
+
}], ctx)
|
|
81
|
+
if (mode === 'prompt') assert.ok(!events.includes('create'))
|
|
82
|
+
else {
|
|
83
|
+
assert.ok(events.includes('create'))
|
|
84
|
+
assert.ok(events.includes('stop'))
|
|
85
|
+
if (mode === 'failure') assert.ok(events.indexOf('stop') < events.indexOf('reveal'))
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
test('CI and redirected output use plain progress without a timer', () => {
|
|
92
|
+
for (const options of [{ output: { isTTY: false }, env: {} }, { output: { isTTY: true }, env: { CI: 'true' } }, { output: { isTTY: true }, env: { TERM: 'dumb' } }]) {
|
|
93
|
+
const lines = []
|
|
94
|
+
const spinner = createSpinner('working…', { ...options, log: (line) => lines.push(line), setIntervalImpl() { assert.fail('no animation in noninteractive output') } })
|
|
95
|
+
spinner.stop('ok', 'done in 1s')
|
|
96
|
+
assert.deepEqual(lines, [' ... working…', ' ✅ done in 1s'])
|
|
97
|
+
}
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
test('a log-file warning clears the working spinner before printing and then resumes', (t) => {
|
|
102
|
+
const repoRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'stage-warning-'))
|
|
103
|
+
t.after(() => fs.rmSync(repoRoot, { recursive: true, force: true }))
|
|
104
|
+
const input = new EventEmitter()
|
|
105
|
+
Object.assign(input, { isTTY: true, isRaw: false, setRawMode() {}, resume() {}, pause() {} })
|
|
106
|
+
const events = []
|
|
107
|
+
const logs = createSetupLogs({ repoRoot, input, env: {}, output: { isTTY: true, write(line) { if (String(line).includes('Could not save')) events.push('warning') } } })
|
|
108
|
+
logs.start()
|
|
109
|
+
logs.setActivity({ pause: () => events.push('pause'), resume: () => events.push('resume'), stop() {} })
|
|
110
|
+
events.length = 0
|
|
111
|
+
fs.unlinkSync(logs.logFile)
|
|
112
|
+
fs.mkdirSync(logs.logFile)
|
|
113
|
+
logs.log('compiler output')
|
|
114
|
+
assert.deepEqual(events, ['pause', 'warning', 'resume'])
|
|
115
|
+
logs.stop()
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
test('provider instructions, choices and input prompts share the stage content margin', async () => {
|
|
120
|
+
const source = fs.readFileSync(new URL('../providers.mjs', import.meta.url), 'utf8')
|
|
121
|
+
const fn = source.slice(source.indexOf('export async function ensureLlmProvider')).replace(/^export /, '')
|
|
122
|
+
const lines = [], questions = []
|
|
123
|
+
let closed = false
|
|
124
|
+
const result = vm.runInNewContext(`${fn}\nensureLlmProvider('/tmp/prompt-format-test')`, {
|
|
125
|
+
normalizeEnvTargets: () => ({ rootEnv: '/tmp/prompt-format-test' }), readEnvValue: () => null,
|
|
126
|
+
LLM_PROVIDERS: [{ label: 'Local', keyEnv: 'LOCAL_TEST_KEY' }],
|
|
127
|
+
process: { env: {}, stdin: { isTTY: true }, stdout: {} },
|
|
128
|
+
console: { log: (line) => lines.push(line), warn() {} },
|
|
129
|
+
readline: { createInterface: () => ({ question(question) { questions.push(question); throw new Error('stop at prompt') }, close() { closed = true } }) },
|
|
130
|
+
})
|
|
131
|
+
await assert.rejects(result, /stop at prompt/)
|
|
132
|
+
assert.ok(lines.filter(Boolean).every((line) => line.startsWith(' ')))
|
|
133
|
+
assert.ok(lines.some((line) => line === ' [ 1] Local'))
|
|
134
|
+
assert.equal(questions[0], ' Choose a provider [1-1]: ')
|
|
135
|
+
assert.equal(closed, true)
|
|
136
|
+
})
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
test('provider confirmations and synced values use the same margin as prompts', async (t) => {
|
|
140
|
+
const repoRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'provider-margin-'))
|
|
141
|
+
t.after(() => fs.rmSync(repoRoot, { recursive: true, force: true }))
|
|
142
|
+
fs.mkdirSync(path.join(repoRoot, 'apps', 'mercato'), { recursive: true })
|
|
143
|
+
fs.writeFileSync(path.join(repoRoot, '.env'), 'OM_AI_PROVIDER=openai\nOM_AI_MODEL=test-model\n')
|
|
144
|
+
fs.writeFileSync(path.join(repoRoot, 'apps', 'mercato', '.env'), '')
|
|
145
|
+
const lines = []
|
|
146
|
+
await llmProviderStep.apply({ repoRoot, flags: {}, log: (line) => lines.push(line) })
|
|
147
|
+
assert.ok(lines.some((line) => line.includes('synced')))
|
|
148
|
+
assert.ok(lines.every((line) => /^ {3}\S/.test(line)), lines.join('\n'))
|
|
149
|
+
})
|
package/src/cli.mjs
CHANGED
|
@@ -21,7 +21,7 @@ import fs from 'node:fs'
|
|
|
21
21
|
import path from 'node:path'
|
|
22
22
|
import readline from 'node:readline'
|
|
23
23
|
|
|
24
|
-
import { detectDocker, resolveRepoRoot, runCompose,
|
|
24
|
+
import { composeArgs, detectDocker, resolveRepoRoot, runCompose, runStreaming, spawnStreaming } from './compose.mjs'
|
|
25
25
|
import { readEnvValue } from './env-file.mjs'
|
|
26
26
|
import { FULLAPP_DEV_COMPOSE_FILE, STARTER_STATE_DIR, resolveStackPorts, stackUrls } from './constants.mjs'
|
|
27
27
|
import { loadCompanyConfig } from './company.mjs'
|
|
@@ -30,6 +30,7 @@ import { describeInfraProblem, devRuntimeArgs, infraDown, ensureMcpSharedDir, re
|
|
|
30
30
|
import { buildUpSteps, clearConvergenceState, createStepContext, ensureOpencodeImage, runSteps, yarnInvocation } from './steps.mjs'
|
|
31
31
|
import { collectStatus, printStatus, readRunState, isPidAlive, startDetached, stopDetached, tailLogs } from './supervise.mjs'
|
|
32
32
|
import { ensureWindowsUtf8Console } from './spawn.mjs'
|
|
33
|
+
import { createSetupLogs } from './setup-logs.mjs'
|
|
33
34
|
import { color, guideBox, printBanner, statusLine } from './ui.mjs'
|
|
34
35
|
import { waitForHealthyServices, waitForHttp } from './waits.mjs'
|
|
35
36
|
|
|
@@ -51,6 +52,7 @@ function parseArgs(argv) {
|
|
|
51
52
|
detach: false,
|
|
52
53
|
follow: false,
|
|
53
54
|
nonInteractive: false,
|
|
55
|
+
verbose: false,
|
|
54
56
|
skipLlmPrompt: false,
|
|
55
57
|
skipDb: false,
|
|
56
58
|
noInfra: false,
|
|
@@ -81,6 +83,9 @@ function parseArgs(argv) {
|
|
|
81
83
|
case '-f':
|
|
82
84
|
flags.follow = true
|
|
83
85
|
break
|
|
86
|
+
case '--verbose':
|
|
87
|
+
flags.verbose = true
|
|
88
|
+
break
|
|
84
89
|
case '--non-interactive':
|
|
85
90
|
flags.nonInteractive = true
|
|
86
91
|
break
|
|
@@ -218,36 +223,53 @@ async function commandUpDocker(ctx, flags) {
|
|
|
218
223
|
if (!outcome.ok) process.exit(2)
|
|
219
224
|
|
|
220
225
|
ensureMcpSharedDir(repoRoot)
|
|
221
|
-
ensureOpencodeImage(ctx)
|
|
222
226
|
const composeFile = FULLAPP_DEV_COMPOSE_FILE
|
|
223
227
|
const upArgs = ['up', '-d']
|
|
224
228
|
if (flags.rebuild) upArgs.push('--build')
|
|
225
229
|
console.log('')
|
|
226
230
|
console.log('── Starting the containerized stack (this builds the app image on the first run) ──')
|
|
227
|
-
const
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
+
const logs = ctx.logs
|
|
232
|
+
const log = (...args) => { console.log(...args); logs.record(...args) }
|
|
233
|
+
let up
|
|
234
|
+
logs.start()
|
|
235
|
+
ctx.log = (...args) => logs.log(...args)
|
|
236
|
+
try {
|
|
237
|
+
await ensureOpencodeImage(ctx)
|
|
238
|
+
up = await runStreaming('docker', composeArgs(repoRoot, upArgs, composeFile), { cwd: repoRoot, env: ctx.env, logs })
|
|
239
|
+
if (up !== 0) logs.show('Containerized stack failed')
|
|
240
|
+
} catch (error) {
|
|
241
|
+
logs.show('Containerized stack failed')
|
|
242
|
+
logs.record(error instanceof Error ? error.message : String(error))
|
|
243
|
+
throw error
|
|
244
|
+
} finally {
|
|
245
|
+
ctx.log = console.log
|
|
246
|
+
logs.stop()
|
|
247
|
+
}
|
|
248
|
+
if (up !== 0) {
|
|
249
|
+
log('❌ docker compose up failed — see above. TLS errors inside builds usually mean the corporate CA changed: re-run with --rebuild.')
|
|
250
|
+
process.exit(up)
|
|
231
251
|
}
|
|
232
252
|
|
|
233
253
|
const ports = resolveStackPorts(repoRoot)
|
|
234
254
|
const urls = stackUrls(ports)
|
|
235
|
-
|
|
236
|
-
const infraOk = await waitForHealthyServices(repoRoot, composeFile, ['postgres', 'redis', 'meilisearch'], { log
|
|
255
|
+
log(color.dim(' Startup order: infra healthy -> app serving -> MCP -> OpenCode -> end-to-end wiring check.'))
|
|
256
|
+
const infraOk = await waitForHealthyServices(repoRoot, composeFile, ['postgres', 'redis', 'meilisearch'], { log })
|
|
257
|
+
logs.record(`Infrastructure health: ${infraOk.ok ? 'ready' : infraOk.failed}`)
|
|
237
258
|
if (!infraOk.ok) process.exit(1)
|
|
238
|
-
|
|
239
|
-
if (!(await waitForHttp(urls.app, { label: `app ${urls.app}`, timeoutMs: 30 * 60 * 1000 }))) process.exit(1)
|
|
240
|
-
const mcpOk = await waitForHttp(urls.mcpHealth, { label: 'MCP /health' })
|
|
241
|
-
const opencodeOk = await waitForHttp(urls.opencodeHealth, { label: 'OpenCode /global/health' })
|
|
259
|
+
log(color.dim(' First boot runs migrations + seed inside the app container — expect several minutes.'))
|
|
260
|
+
if (!(await waitForHttp(urls.app, { label: `app ${urls.app}`, timeoutMs: 30 * 60 * 1000, log }))) process.exit(1)
|
|
261
|
+
const mcpOk = await waitForHttp(urls.mcpHealth, { label: 'MCP /health', log })
|
|
262
|
+
const opencodeOk = await waitForHttp(urls.opencodeHealth, { label: 'OpenCode /global/health', log })
|
|
242
263
|
if (mcpOk && opencodeOk) {
|
|
243
264
|
await waitForHttp(urls.opencodeMcpStatus, {
|
|
244
265
|
label: 'OpenCode <-> MCP wiring',
|
|
266
|
+
log,
|
|
245
267
|
timeoutMs: 2 * 60 * 1000,
|
|
246
268
|
validate: (body) => body.includes('connected'),
|
|
247
269
|
})
|
|
248
270
|
}
|
|
249
271
|
console.log('')
|
|
250
|
-
|
|
272
|
+
log(color.bold(color.green('Stack is up.')))
|
|
251
273
|
const superEmail = readEnvValue(path.join(repoRoot, '.env'), 'OM_INIT_SUPERADMIN_EMAIL')?.trim() || 'superadmin@acme.com'
|
|
252
274
|
const superPassword = readEnvValue(path.join(repoRoot, '.env'), 'OM_INIT_SUPERADMIN_PASSWORD')?.trim() || 'secret'
|
|
253
275
|
console.log(` App: ${color.cyan(urls.app)} ${color.dim(`(sign in: ${superEmail} / ${superPassword})`)}`)
|
|
@@ -331,38 +353,62 @@ async function commandReset(flags) {
|
|
|
331
353
|
}
|
|
332
354
|
|
|
333
355
|
async function commandInfra(flags) {
|
|
334
|
-
const
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
356
|
+
const logs = createSetupLogs({ repoRoot, name: 'infra', ...flags })
|
|
357
|
+
const log = (...args) => { console.log(...args); logs.record(...args) }
|
|
358
|
+
logs.start()
|
|
359
|
+
try {
|
|
360
|
+
const docker = detectDocker()
|
|
361
|
+
if (!docker.ok) {
|
|
362
|
+
printInfraProblem({ code: docker.code, detail: docker.reason }, log)
|
|
363
|
+
log(' Full environment audit: yarn om doctor')
|
|
364
|
+
process.exitCode = 2
|
|
365
|
+
return
|
|
344
366
|
}
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
367
|
+
if (flags.infraAction === 'down') {
|
|
368
|
+
if (flags.volumes && !flags.yes) {
|
|
369
|
+
log('❌ --volumes DELETES all database/search data. Re-run with --yes to confirm.')
|
|
370
|
+
process.exitCode = 1
|
|
371
|
+
return
|
|
372
|
+
}
|
|
373
|
+
statusLine('info', 'Stopping infrastructure containers', { log })
|
|
374
|
+
const status = await runStreaming('docker', composeArgs(repoRoot, ['down', ...(flags.volumes ? ['--volumes'] : [])]), { cwd: repoRoot, logs })
|
|
375
|
+
if (status !== 0) {
|
|
376
|
+
logs.show('Infrastructure shutdown failed')
|
|
377
|
+
statusLine('fail', `Infrastructure shutdown failed (exit ${status})`, { log })
|
|
378
|
+
} else statusLine('ok', flags.volumes ? 'Infra containers stopped and volumes deleted.' : 'Infra containers stopped (data preserved).', { log })
|
|
379
|
+
process.exitCode = status
|
|
380
|
+
return
|
|
381
|
+
}
|
|
382
|
+
statusLine('info', 'Starting infrastructure containers (first run may pull and build images)', { log })
|
|
383
|
+
const outcome = await startInfra(repoRoot, {
|
|
384
|
+
profiles: flags.profiles,
|
|
385
|
+
logs,
|
|
386
|
+
log: (...args) => logs.log(...args),
|
|
387
|
+
beforeUp: () => ensureOpencodeImage({ repoRoot, env: process.env, flags, logs, log: (...args) => logs.log(...args) }),
|
|
388
|
+
})
|
|
389
|
+
if (!outcome.ok) {
|
|
390
|
+
logs.show('Infrastructure startup failed')
|
|
391
|
+
printInfraProblem(outcome.problem, log)
|
|
392
|
+
process.exitCode = 2
|
|
393
|
+
return
|
|
394
|
+
}
|
|
395
|
+
const ports = resolveStackPorts(repoRoot)
|
|
396
|
+
log('')
|
|
397
|
+
log(`✅ Infra containers are up (opencode :${ports.opencode}, postgres :${ports.postgres}, redis :${ports.redis}, meilisearch :${ports.meilisearch}).`)
|
|
398
|
+
log(' Next: yarn dev (starts the app and the MCP server on this machine)')
|
|
399
|
+
} catch (error) {
|
|
400
|
+
logs.show('Infrastructure failed')
|
|
401
|
+
statusLine('fail', error instanceof Error ? error.message : String(error), { log })
|
|
402
|
+
process.exitCode = 1
|
|
403
|
+
} finally {
|
|
404
|
+
logs.stop()
|
|
354
405
|
}
|
|
355
|
-
const ports = resolveStackPorts(repoRoot)
|
|
356
|
-
console.log('')
|
|
357
|
-
console.log(`✅ Infra containers are up (opencode :${ports.opencode}, postgres :${ports.postgres}, redis :${ports.redis}, meilisearch :${ports.meilisearch}).`)
|
|
358
|
-
console.log(' Next: yarn dev (starts the app and the MCP server on this machine)')
|
|
359
|
-
process.exit(0)
|
|
360
406
|
}
|
|
361
407
|
|
|
362
|
-
function printInfraProblem(problem) {
|
|
408
|
+
function printInfraProblem(problem, log = console.error) {
|
|
363
409
|
const [title, ...rest] = describeInfraProblem(problem)
|
|
364
|
-
|
|
365
|
-
for (const line of rest)
|
|
410
|
+
log(`❌ ${title}`)
|
|
411
|
+
for (const line of rest) log(` ${line}`)
|
|
366
412
|
}
|
|
367
413
|
|
|
368
414
|
async function main() {
|
|
@@ -388,4 +434,7 @@ async function main() {
|
|
|
388
434
|
}
|
|
389
435
|
}
|
|
390
436
|
|
|
391
|
-
await main()
|
|
437
|
+
await main().catch((error) => {
|
|
438
|
+
console.error(`❌ ${error instanceof Error ? error.message : String(error)}`)
|
|
439
|
+
process.exitCode = 1
|
|
440
|
+
})
|
package/src/compose.mjs
CHANGED
|
@@ -114,3 +114,51 @@ export function runStreamingSync(command, commandArgs, { cwd, env } = {}) {
|
|
|
114
114
|
}
|
|
115
115
|
return result.status ?? 1
|
|
116
116
|
}
|
|
117
|
+
|
|
118
|
+
// Windows shell shims spawn a process tree; killing only cmd.exe leaves
|
|
119
|
+
// builds running. POSIX captured children have their own process group.
|
|
120
|
+
export function stopStreamingChild(child, signal, { platform = process.platform, grouped = true, spawnSyncImpl = spawnSync, killImpl = process.kill } = {}) {
|
|
121
|
+
if (platform === 'win32' && child.pid) {
|
|
122
|
+
const result = spawnSyncImpl('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true })
|
|
123
|
+
if (!result.error && result.status === 0) return
|
|
124
|
+
} else if (grouped && child.pid) {
|
|
125
|
+
try { killImpl(-child.pid, signal); return } catch { /* child may already have exited */ }
|
|
126
|
+
}
|
|
127
|
+
child.kill(signal)
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Async output capture keeps the setup log toggle responsive during long
|
|
131
|
+
// installs/builds. With no sink, preserve inherited stdio (CI / verbose).
|
|
132
|
+
export function runStreaming(command, commandArgs, { cwd, env, logs, spawnImpl = spawn } = {}) {
|
|
133
|
+
const resolved = resolveSpawnCommand(command, commandArgs)
|
|
134
|
+
return new Promise((resolve, reject) => {
|
|
135
|
+
const child = spawnImpl(resolved.command, resolved.args, {
|
|
136
|
+
cwd: cwd ?? process.cwd(),
|
|
137
|
+
env: env ?? process.env,
|
|
138
|
+
stdio: logs ? [logs.interactive ? 'ignore' : 'inherit', 'pipe', 'pipe'] : 'inherit',
|
|
139
|
+
// Give piped children their own group so Ctrl+C reaches yarn's workers
|
|
140
|
+
// as well as yarn itself. Windows does not support POSIX group signals.
|
|
141
|
+
detached: Boolean(logs) && process.platform !== 'win32',
|
|
142
|
+
...resolved.spawnOptions,
|
|
143
|
+
})
|
|
144
|
+
const interrupt = (signal) => {
|
|
145
|
+
logs?.stop()
|
|
146
|
+
stopStreamingChild(child, signal, { grouped: Boolean(logs) })
|
|
147
|
+
process.exit(signal === 'SIGINT' ? 130 : 143)
|
|
148
|
+
}
|
|
149
|
+
const onSigint = () => interrupt('SIGINT')
|
|
150
|
+
const onSigterm = () => interrupt('SIGTERM')
|
|
151
|
+
process.once('SIGINT', onSigint)
|
|
152
|
+
process.once('SIGTERM', onSigterm)
|
|
153
|
+
const cleanup = () => {
|
|
154
|
+
process.removeListener('SIGINT', onSigint)
|
|
155
|
+
process.removeListener('SIGTERM', onSigterm)
|
|
156
|
+
}
|
|
157
|
+
child.stdout?.setEncoding('utf8')
|
|
158
|
+
child.stderr?.setEncoding('utf8')
|
|
159
|
+
child.stdout?.on('data', (chunk) => logs?.raw(chunk))
|
|
160
|
+
child.stderr?.on('data', (chunk) => logs?.raw(chunk))
|
|
161
|
+
child.once('error', (error) => { cleanup(); reject(new Error(`${command} could not be executed: ${error.message}`)) })
|
|
162
|
+
child.once('close', (code) => { cleanup(); resolve(code ?? 1) })
|
|
163
|
+
})
|
|
164
|
+
}
|
package/src/infra-preflight.mjs
CHANGED
|
@@ -238,6 +238,7 @@ export async function startInfraServices({
|
|
|
238
238
|
beforeUp,
|
|
239
239
|
detect = detectDockerRuntime,
|
|
240
240
|
spawnSyncImpl = spawnSync,
|
|
241
|
+
runStreamingImpl,
|
|
241
242
|
portProbe = probeTcpPort,
|
|
242
243
|
log = console.log,
|
|
243
244
|
}) {
|
|
@@ -265,9 +266,9 @@ export async function startInfraServices({
|
|
|
265
266
|
|
|
266
267
|
const reused = required.filter((service) => running.has(service))
|
|
267
268
|
if (reused.length > 0) log(` reusing running containers: ${reused.join(', ')} (data preserved)`)
|
|
268
|
-
if (beforeUp) beforeUp()
|
|
269
|
+
if (beforeUp) await beforeUp()
|
|
269
270
|
|
|
270
|
-
const up = spawnSyncImpl('docker', composeArgs([...upArgs, 'up', '-d', '--wait']), { cwd, stdio: 'inherit', windowsHide: true })
|
|
271
|
+
const up = await (runStreamingImpl ?? spawnSyncImpl)('docker', composeArgs([...upArgs, 'up', '-d', '--wait']), { cwd, stdio: 'inherit', windowsHide: true })
|
|
271
272
|
if (up?.error) return { ok: false, problem: { code: 'compose-failed', detail: up.error.message } }
|
|
272
273
|
if ((up?.status ?? 1) === 0) return { ok: true, reused }
|
|
273
274
|
|
package/src/infra.mjs
CHANGED
|
@@ -7,7 +7,7 @@ import fs from 'node:fs'
|
|
|
7
7
|
import path from 'node:path'
|
|
8
8
|
import { fileURLToPath } from 'node:url'
|
|
9
9
|
|
|
10
|
-
import { composeArgs, detectDocker, resolveRepoRoot, runCompose, runCaptureSync } from './compose.mjs'
|
|
10
|
+
import { composeArgs, detectDocker, resolveRepoRoot, runCompose, runCaptureSync, runStreaming } from './compose.mjs'
|
|
11
11
|
import { resolveStackPorts } from './constants.mjs'
|
|
12
12
|
import { readEnvValue } from './env-file.mjs'
|
|
13
13
|
import { formatInfraProblem, startInfraServices } from './infra-preflight.mjs'
|
|
@@ -62,7 +62,7 @@ export function externalDatabaseHost(repoRoot, env = process.env) {
|
|
|
62
62
|
// infraUp plus the shared preflight: distinguishes missing CLI / compose,
|
|
63
63
|
// stopped daemon, port conflicts, and failed healthchecks instead of a bare
|
|
64
64
|
// non-zero compose exit. Returns { ok, problem? }; never touches volumes.
|
|
65
|
-
export async function startInfra(repoRoot, { profiles = [], env = process.env, log = console.log, beforeUp, startImpl = startInfraServices } = {}) {
|
|
65
|
+
export async function startInfra(repoRoot, { profiles = [], env = process.env, log = console.log, logs, beforeUp, startImpl = startInfraServices } = {}) {
|
|
66
66
|
ensureMcpSharedDir(repoRoot)
|
|
67
67
|
const externalHost = externalDatabaseHost(repoRoot, env)
|
|
68
68
|
if (externalHost) {
|
|
@@ -74,6 +74,7 @@ export async function startInfra(repoRoot, { profiles = [], env = process.env, l
|
|
|
74
74
|
upArgs: profiles.flatMap((profile) => ['--profile', profile]),
|
|
75
75
|
cwd: repoRoot,
|
|
76
76
|
beforeUp,
|
|
77
|
+
...(logs ? { runStreamingImpl: async (command, args, options) => ({ status: await runStreaming(command, args, { ...options, env, logs }) }) } : {}),
|
|
77
78
|
log,
|
|
78
79
|
})
|
|
79
80
|
}
|
package/src/providers.mjs
CHANGED
|
@@ -125,22 +125,23 @@ export async function ensureLlmProvider(rootEnvOrFiles, { skipPrompt = false, no
|
|
|
125
125
|
}
|
|
126
126
|
|
|
127
127
|
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
|
|
128
|
-
const ask = (question) => new Promise((resolve) => rl.question(question
|
|
128
|
+
const ask = (question) => new Promise((resolve) => rl.question(` ${question}`, resolve))
|
|
129
129
|
|
|
130
|
+
const print = (line) => console.log(line ? ` ${line}` : '')
|
|
130
131
|
try {
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
132
|
+
print('')
|
|
133
|
+
print('The AI assistant (OpenCode + MCP) needs one LLM provider to power the Cmd+K agent.')
|
|
134
|
+
print('Setup requires one to continue. (Ctrl+C aborts; re-run later with --skip-llm-prompt to configure it in .env yourself.)')
|
|
134
135
|
|
|
135
136
|
while (true) {
|
|
136
|
-
|
|
137
|
+
print('')
|
|
137
138
|
LLM_PROVIDERS.forEach((entry, index) => {
|
|
138
|
-
|
|
139
|
+
print(`[${String(index + 1).padStart(2)}] ${entry.label}`)
|
|
139
140
|
})
|
|
140
141
|
const choice = await ask(`Choose a provider [1-${LLM_PROVIDERS.length}]: `)
|
|
141
142
|
const index = Number.parseInt(choice, 10)
|
|
142
143
|
if (!Number.isInteger(index) || index < 1 || index > LLM_PROVIDERS.length) {
|
|
143
|
-
|
|
144
|
+
print(`Please enter a number between 1 and ${LLM_PROVIDERS.length}.`)
|
|
144
145
|
continue
|
|
145
146
|
}
|
|
146
147
|
const selected = LLM_PROVIDERS[index - 1]
|
|
@@ -149,7 +150,7 @@ export async function ensureLlmProvider(rootEnvOrFiles, { skipPrompt = false, no
|
|
|
149
150
|
if (selected.keyRequired) {
|
|
150
151
|
key = (await ask(`Paste your ${selected.label} API key: `)).trim()
|
|
151
152
|
if (!key) {
|
|
152
|
-
|
|
153
|
+
print('A key is required for this provider. Try again.')
|
|
153
154
|
continue
|
|
154
155
|
}
|
|
155
156
|
} else {
|
|
@@ -164,7 +165,7 @@ export async function ensureLlmProvider(rootEnvOrFiles, { skipPrompt = false, no
|
|
|
164
165
|
const entered = (await ask(promptText)).trim()
|
|
165
166
|
baseUrl = entered || selected.baseUrl
|
|
166
167
|
if (selected.baseUrlRequired && !baseUrl) {
|
|
167
|
-
|
|
168
|
+
print('This provider requires a base URL. Try again.')
|
|
168
169
|
continue
|
|
169
170
|
}
|
|
170
171
|
}
|
|
@@ -174,7 +175,7 @@ export async function ensureLlmProvider(rootEnvOrFiles, { skipPrompt = false, no
|
|
|
174
175
|
: `${selected.label} model (${selected.modelHint}) (optional — press Enter for the default): `
|
|
175
176
|
const model = (await ask(modelPrompt)).trim()
|
|
176
177
|
if (selected.modelRequired && !model) {
|
|
177
|
-
|
|
178
|
+
print('This provider needs a model/deployment id. Try again.')
|
|
178
179
|
continue
|
|
179
180
|
}
|
|
180
181
|
|