typeclaw 0.48.11 → 0.48.13

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 (94) hide show
  1. package/package.json +7 -4
  2. package/src/agent/attention-escalation.ts +8 -5
  3. package/src/agent/auth-reloadable.ts +2 -3
  4. package/src/agent/auth.ts +59 -79
  5. package/src/agent/compaction.ts +2 -2
  6. package/src/agent/index.ts +42 -16
  7. package/src/agent/llm-replay-sanitizer.ts +1 -1
  8. package/src/agent/model-overrides.ts +1 -1
  9. package/src/agent/multimodal/look-at.ts +3 -3
  10. package/src/agent/multimodal/read-redirect.ts +1 -1
  11. package/src/agent/plugin-tools.ts +26 -31
  12. package/src/agent/reload-tool.ts +1 -1
  13. package/src/agent/subagents.ts +1 -1
  14. package/src/agent/tool-error-remediation.ts +1 -1
  15. package/src/agent/tool-result-budget.ts +2 -2
  16. package/src/agent/tools/channel-disengage.ts +2 -2
  17. package/src/agent/tools/channel-edit.ts +2 -2
  18. package/src/agent/tools/channel-fetch-attachment.ts +2 -2
  19. package/src/agent/tools/channel-history.ts +2 -2
  20. package/src/agent/tools/channel-react.ts +2 -2
  21. package/src/agent/tools/channel-read.ts +2 -2
  22. package/src/agent/tools/channel-reply.ts +2 -2
  23. package/src/agent/tools/channel-send.ts +2 -2
  24. package/src/agent/tools/grant-role.ts +2 -2
  25. package/src/agent/tools/post-github-review.ts +2 -2
  26. package/src/agent/tools/restart.ts +2 -2
  27. package/src/agent/tools/skip-response.ts +2 -2
  28. package/src/agent/tools/spawn-subagent.ts +2 -2
  29. package/src/agent/tools/stream-snapshot.ts +2 -2
  30. package/src/agent/tools/subagent-cancel.ts +2 -2
  31. package/src/agent/tools/subagent-output.ts +2 -2
  32. package/src/agent/tools/todo/index.ts +2 -2
  33. package/src/agent/tools/webfetch/tool.ts +2 -2
  34. package/src/agent/tools/websearch.ts +2 -2
  35. package/src/bundled-plugins/github-cli-auth/gh-command.ts +7 -1
  36. package/src/bundled-plugins/github-cli-auth/index.ts +1 -1
  37. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -1
  38. package/src/bundled-plugins/memory/dreaming.ts +21 -6
  39. package/src/channels/adapters/kakaotalk-channel-resolver.ts +86 -16
  40. package/src/channels/adapters/kakaotalk.ts +7 -8
  41. package/src/channels/adapters/teams-classify.ts +21 -0
  42. package/src/channels/adapters/teams-edit.ts +2 -1
  43. package/src/channels/adapters/teams-format.ts +16 -0
  44. package/src/channels/adapters/teams.ts +12 -5
  45. package/src/channels/github-review-verdict-coordinator.ts +26 -3
  46. package/src/channels/router.ts +50 -25
  47. package/src/cli/compose.ts +3 -3
  48. package/src/cli/docker-preflight.ts +8 -4
  49. package/src/cli/model.ts +7 -5
  50. package/src/cli/oauth-callbacks.ts +38 -23
  51. package/src/cli/restart.ts +89 -23
  52. package/src/cli/start.ts +68 -16
  53. package/src/cli/status.ts +38 -6
  54. package/src/cli/stop.ts +5 -2
  55. package/src/compose/stop.ts +5 -4
  56. package/src/config/config.ts +62 -25
  57. package/src/config/providers.ts +272 -47
  58. package/src/container/build-cache.ts +807 -0
  59. package/src/container/compose-project.ts +4 -0
  60. package/src/container/docker-app.ts +74 -0
  61. package/src/container/log-archive.ts +33 -5
  62. package/src/container/memory-limit.ts +80 -0
  63. package/src/container/memory-oversubscription.ts +125 -0
  64. package/src/container/restart.ts +6 -1
  65. package/src/container/shared.ts +43 -16
  66. package/src/container/start.ts +280 -53
  67. package/src/container/stop.ts +19 -13
  68. package/src/container/verify-running.ts +12 -0
  69. package/src/cron/scheduler.ts +12 -4
  70. package/src/doctor/bounded-exec.ts +14 -0
  71. package/src/doctor/checks.ts +40 -15
  72. package/src/doctor/index.ts +14 -2
  73. package/src/doctor/plugin-bridge.ts +15 -3
  74. package/src/hostd/paths.ts +4 -0
  75. package/src/init/index.ts +4 -4
  76. package/src/init/oauth-login.ts +57 -17
  77. package/src/inspect/transcript-view.ts +6 -3
  78. package/src/run/channel-session-factory.ts +5 -4
  79. package/src/run/index.ts +27 -11
  80. package/src/run/resource-sample.ts +171 -0
  81. package/src/sandbox/index.ts +8 -1
  82. package/src/sandbox/session-tmp.ts +26 -1
  83. package/src/secrets/refresh-provider-oauth.ts +30 -76
  84. package/src/secrets/schema.ts +3 -4
  85. package/src/secrets/storage.ts +133 -234
  86. package/src/server/index.ts +1 -1
  87. package/src/sessions/index.ts +1 -1
  88. package/src/skills/typeclaw-config/SKILL.md +4 -4
  89. package/src/skills/typeclaw-plugins/SKILL.md +5 -5
  90. package/src/tui/index.ts +5 -3
  91. package/src/tui/theme.ts +1 -1
  92. package/typeclaw.schema.json +32 -1
  93. package/src/agent/adaptive-thinking-compat.ts +0 -79
  94. package/src/secrets/oauth-xai.ts +0 -348
@@ -1,8 +1,8 @@
1
1
  import { statSync } from 'node:fs'
2
2
  import { basename } from 'node:path'
3
3
 
4
- import { createAssistantMessageEventStream, type AssistantMessage, type ToolResultMessage } from '@mariozechner/pi-ai'
5
- import { type SessionEntry, SessionManager } from '@mariozechner/pi-coding-agent'
4
+ import { createAssistantMessageEventStream, type AssistantMessage, type ToolResultMessage } from '@earendil-works/pi-ai'
5
+ import { type SessionEntry, SessionManager } from '@earendil-works/pi-coding-agent'
6
6
 
7
7
  import { createSession, renderTurnRoleAnchor, renderTurnTimeAnchor, type AgentSession } from '@/agent'
8
8
  import { applyTurnThinkingLevel, getQuestionSignal, type QuestionSignal } from '@/agent/attention-escalation'
@@ -302,16 +302,17 @@ export function buildRestartResumeWakeReminder(interruptedSubagents?: readonly s
302
302
  // start alongside `turnSeq`.
303
303
  export const MAX_POLICY_DENIED_CHANNEL_SENDS_PER_TURN = 3
304
304
  // Per-request output-token cap for channel sessions, threaded into the agent's
305
- // stream options to override pi-ai's silent `Math.min(model.maxTokens, 32000)`
306
- // default (`buildBaseOptions` in @mariozechner/pi-ai). Without it, Fireworks'
305
+ // stream options to override pi-ai's model max-tokens default, which 0.87.1
306
+ // clamps to the remaining context window (`buildBaseOptions` in
307
+ // @earendil-works/pi-ai/dist/api/simple-options.js:10-18). Without it, Fireworks'
307
308
  // kimi-k2p6-turbo — which degenerates into single-token repetition on the
308
- // post-tool follow-up turn — runs the full 32000 tokens (~116s of garbage that
309
- // never produces a reply) before `stopReason: 'length'`. The terminal-reply
310
- // hook below removes the turn that triggers this; the cap bounds any other path
311
- // that still reaches a channel LLM call. 4096 fits a thinking block plus a
312
- // nontrivial reply (healthy channel turns observed at ~317 output tokens
313
- // including reasoning). Deliberately NOT lowered in `providers.ts`, where
314
- // `maxTokens` is the model's true capability that compaction math reads.
309
+ // post-tool follow-up turn — can run the model's full output capability
310
+ // (~116s of garbage) before `stopReason: 'length'`. The terminal-reply hook
311
+ // below removes the turn that triggers this; the cap bounds any other path that
312
+ // still reaches a channel LLM call. 4096 fits a thinking block plus a nontrivial
313
+ // reply (healthy channel turns observed at ~317 output tokens including
314
+ // reasoning). Deliberately NOT lowered in `providers.ts`, where `maxTokens` is
315
+ // the model's true capability that compaction math reads.
315
316
  export const CHANNEL_MAX_OUTPUT_TOKENS = 4096
316
317
  // Raised output-token budget threaded into the ONE re-prompt that follows a
317
318
  // `stopReason:'length'` empty turn. The default 4096 backstop bounds kimi's
@@ -320,8 +321,7 @@ export const CHANNEL_MAX_OUTPUT_TOKENS = 4096
320
321
  // prose — re-prompting under the identical cap reproduces the truncation. A
321
322
  // `length` truncation that the byte-identical loop guard did NOT catch is
322
323
  // evidence of genuine reasoning starved for room, not a repetition loop, so the
323
- // retry grants 4x headroom for thinking + a reply. Bounded (not 32000) so a
324
- // turn that IS looping still can't burn the full pi-ai default. Consumed
324
+ // turn that IS looping still can't burn the model's full output capability. Consumed
325
325
  // one-shot via `LiveSession.nextPromptMaxTokens`, then reset at the next real
326
326
  // user turn so the raised budget never leaks past the turn that needed it.
327
327
  export const CHANNEL_EMPTY_TURN_RETRY_MAX_OUTPUT_TOKENS = 16384
@@ -1155,7 +1155,7 @@ type LiveSession = {
1155
1155
  // turn can never trigger a nudge on a later one. `null` when no such reply
1156
1156
  // ended this turn.
1157
1157
  lastTerminalReplyCompletion: { turnSeq: number; text?: string; tokens: number } | null
1158
- // Armed after a successful terminal reply. pi-agent-core invokes streamFn
1158
+ // Armed after a successful terminal reply. pi-agent-core invokes streamFunction
1159
1159
  // again only after emitting every matching toolResult into its event queue;
1160
1160
  // the wrapper consumes this marker at that awaited provider boundary and
1161
1161
  // returns a local aborted response instead of calling the provider. Event
@@ -3289,18 +3289,25 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3289
3289
  }
3290
3290
  }
3291
3291
 
3292
- // Override pi-ai's hidden `Math.min(model.maxTokens, 32000)` output cap for
3293
- // channel sessions by threading an explicit `maxTokens` into every stream
3294
- // call. See CHANNEL_MAX_OUTPUT_TOKENS for why. Composes the existing streamFn
3295
- // (pi's default `streamSimple` unless a proxy was installed). Precedence:
3296
- // an explicit per-call `maxTokens` always wins; otherwise a one-shot
3297
- // `live.nextPromptMaxTokens` (set by the empty-turn length-retry) is consumed
3298
- // and cleared so the raised budget applies to exactly one stream call;
3299
- // otherwise the default backstop.
3292
+ // Override pi-ai's model max-tokens default for channel sessions by threading an
3293
+ // explicit `maxTokens` into every stream call. pi-ai 0.87.1 clamps the requested
3294
+ // value to remaining context (`buildBaseOptions`, simple-options.js:10-18), rather
3295
+ // than applying the removed 32k cap. See CHANNEL_MAX_OUTPUT_TOKENS for why.
3296
+ // Composes the existing streamFunction (pi's default `Models.streamSimple` unless a
3297
+ // proxy was installed). Compaction and branch-summary calls are excluded: pi 0.87.1
3298
+ // invokes `agent.streamFunction` for compaction (pi-coding-agent
3299
+ // dist/core/agent-session.js:1844) while `isCompacting` remains true
3300
+ // (agent-session.js:927-932). They must retain pi's own stream options and cannot
3301
+ // consume a channel turn's pending terminal stop or one-shot retry budget.
3302
+ // Precedence for channel assistant calls: an explicit per-call `maxTokens` always
3303
+ // wins; otherwise a one-shot `live.nextPromptMaxTokens` (set by the empty-turn
3304
+ // length-retry) is consumed and cleared so the raised budget applies to exactly one
3305
+ // stream call; otherwise the default backstop.
3300
3306
  const installChannelOutputCap = (live: LiveSession): void => {
3301
3307
  const { agent } = live.session
3302
- const inner = agent.streamFn
3303
- agent.streamFn = async (model, context, streamOptions) => {
3308
+ const inner = agent.streamFunction
3309
+ agent.streamFunction = async (model, context, streamOptions) => {
3310
+ if (live.session.isCompacting) return await inner(model, context, streamOptions)
3304
3311
  const pendingTerminalStop = live.pendingTerminalReplyStop
3305
3312
  if (pendingTerminalStop?.turnSeq === live.turnSeq && live.userStoppedTurnSeq !== pendingTerminalStop.turnSeq) {
3306
3313
  live.pendingTerminalReplyStop = null
@@ -3546,6 +3553,16 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3546
3553
  )
3547
3554
  return
3548
3555
  }
3556
+ // A queued re-prompt (typically the completion of a reviewer this turn
3557
+ // spawned) is the model's next chance to close the thread with real
3558
+ // content. Posting the canned fallback now strands the verdict that turn is
3559
+ // about to deliver, so re-evaluate at the end of that turn instead.
3560
+ if (live.pendingSystemReminders.length > 0 || live.promptQueue.length > 0) {
3561
+ logger.info(
3562
+ `[channels] ${live.keyId} github_thread_closeout_deferred pr=${closeout.prNumber} root=${closeout.rootCommentId} reason=reprompt_queued`,
3563
+ )
3564
+ return
3565
+ }
3549
3566
  if (live.skippedTurn?.turnSeq === live.turnSeq) live.skippedTurn = null
3550
3567
  if (closeout.correctionAttempts === 0) {
3551
3568
  closeout.correctionAttempts++
@@ -3731,6 +3748,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3731
3748
  ) {
3732
3749
  sibling.githubReviewRound = promoted
3733
3750
  persistGithubReviewRound(sibling, promoted)
3751
+ // Tools read the round off originRef, which is otherwise rebuilt only
3752
+ // at turn start. A sibling promoted mid-turn would keep seeing the old
3753
+ // carrier and have its own reviewer spawn / verdict denied.
3754
+ const origin = sibling.originRef.current
3755
+ if (origin?.kind === 'channel') sibling.originRef.current = { ...origin, githubReviewRound: promoted }
3734
3756
  }
3735
3757
  }
3736
3758
  waiter.pendingSystemReminders.push(
@@ -8631,7 +8653,10 @@ function repairDanglingToolUseBranch(session: AgentSession, timestamp: number):
8631
8653
  timestamp,
8632
8654
  }))
8633
8655
  for (const message of repairedMessages) session.sessionManager.appendMessage(message)
8634
- session.agent.state.messages = [...session.agent.state.messages, ...repairedMessages]
8656
+ // SessionManager is canonical in pi 0.87: assigning agent.state.messages no longer
8657
+ // changes provider history. Refresh after appending so the next prompt sees the
8658
+ // persisted interruption results (pi-coding-agent 0.87.0 CHANGELOG:39-45).
8659
+ session.refreshContext()
8635
8660
  return missing.map((toolCall) => toolCall.name)
8636
8661
  }
8637
8662
 
@@ -366,9 +366,9 @@ function formatStartDone<T extends { alreadyRunning?: boolean; hostPort: number
366
366
  }
367
367
 
368
368
  function formatStopDone<T extends { running: boolean }>(result: AgentResult<T>): string {
369
- if (!result.ok) return `${c.red('✖')} ${c.red('failed:')} ${result.reason}`
370
- if (result.data.running) return `${c.green('✔')} stopped`
371
- return `${c.dim('○')} ${c.dim('not running')}`
369
+ if (!result.ok) return appendWarnings(`${c.red('✖')} ${c.red('failed:')} ${result.reason}`, result.warnings)
370
+ const head = result.data.running ? `${c.green('✔')} stopped` : `${c.dim('○')} ${c.dim('not running')}`
371
+ return appendWarnings(head, result.warnings)
372
372
  }
373
373
 
374
374
  function formatRestartDone<T extends { start: { hostPort: number } }>(result: AgentResult<T>): string {
@@ -3,6 +3,7 @@ import {
3
3
  detectInstalledDockerApps,
4
4
  pickRuntimeToNudge,
5
5
  renderDockerUnavailableGuidance,
6
+ type DockerAppProbes,
6
7
  type DockerExec,
7
8
  } from '@/container'
8
9
 
@@ -16,15 +17,18 @@ export type DockerPreflightResult = { ok: true } | { ok: false; summary: string;
16
17
  // then hands the friendly, runtime-specific guidance back to the caller so each
17
18
  // command renders it in its own style (spinner vs console) — no process.exit
18
19
  // here, that belongs to the command.
19
- export async function preflightDocker(exec?: DockerExec): Promise<DockerPreflightResult> {
20
+ export async function preflightDocker(exec?: DockerExec, probes?: DockerAppProbes): Promise<DockerPreflightResult> {
20
21
  const availability = exec ? await checkDockerAvailable(exec) : await checkDockerAvailable()
21
22
  if (availability.ok) return { ok: true }
22
23
 
23
24
  const detail = availability.reason === 'daemon-down' ? availability.detail : undefined
24
- const installed = detectInstalledDockerApps()
25
- const nudge = pickRuntimeToNudge(process.env, detail, installed)
25
+ // Probes are injectable so tests do not depend on which Docker runtimes
26
+ // happen to be installed on the machine running them.
27
+ const installed = detectInstalledDockerApps(probes)
28
+ const env = probes?.env ?? process.env
29
+ const nudge = pickRuntimeToNudge(env, detail, installed)
26
30
  const { summary, lines } = renderDockerUnavailableGuidance(availability, {
27
- platform: process.platform,
31
+ platform: probes?.platform ?? process.platform,
28
32
  nudge,
29
33
  installed,
30
34
  })
package/src/cli/model.ts CHANGED
@@ -4,7 +4,7 @@ import { join } from 'node:path'
4
4
  import { autocomplete, cancel, intro, isCancel, log, select } from '@clack/prompts'
5
5
  import { defineCommand } from 'citty'
6
6
 
7
- import type { CustomModelMeta, ThinkingLevel } from '@/config'
7
+ import { type CustomModelMeta, type ThinkingLevel, thinkingLevelSchema } from '@/config'
8
8
  import {
9
9
  addProfile,
10
10
  listModelProfiles,
@@ -59,7 +59,7 @@ const setSub = defineCommand({
59
59
  thinking: {
60
60
  type: 'string',
61
61
  description:
62
- "reasoning effort for THIS profile (off|minimal|low|medium|high|xhigh|default); the `default` profile's level is the de-facto global default",
62
+ "reasoning effort for THIS profile (off|minimal|low|medium|high|xhigh|max|default); the `default` profile's level is the de-facto global default",
63
63
  required: false,
64
64
  },
65
65
  },
@@ -117,7 +117,7 @@ const thinkingSub = defineCommand({
117
117
  level: {
118
118
  type: 'positional',
119
119
  description:
120
- 'reasoning effort (off|minimal|low|medium|high|xhigh); or "default" to clear and defer to the SDK default',
120
+ 'reasoning effort (off|minimal|low|medium|high|xhigh|max); or "default" to clear and defer to the SDK default',
121
121
  required: false,
122
122
  },
123
123
  },
@@ -318,7 +318,9 @@ async function pickProfileName(): Promise<string> {
318
318
  return choice
319
319
  }
320
320
 
321
- const THINKING_LEVELS: ThinkingLevel[] = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh']
321
+ // The config schema is the single source of truth, so `--thinking` and the
322
+ // picker accept exactly the levels typeclaw.json accepts (including `max`).
323
+ const THINKING_LEVELS: readonly ThinkingLevel[] = thinkingLevelSchema.options
322
324
  const KEEP_THINKING_SENTINEL = '__keep__'
323
325
 
324
326
  export type ParsedThinkingArg = { ok: true; level: ThinkingLevel | undefined } | { ok: false; reason: string }
@@ -326,7 +328,7 @@ export type ParsedThinkingArg = { ok: true; level: ThinkingLevel | undefined } |
326
328
  export function parseThinkingArg(raw: string): ParsedThinkingArg {
327
329
  const value = raw.trim().toLowerCase()
328
330
  if (value === 'default' || value === 'unset' || value === 'none') return { ok: true, level: undefined }
329
- if ((THINKING_LEVELS as string[]).includes(value)) return { ok: true, level: value as ThinkingLevel }
331
+ if ((THINKING_LEVELS as readonly string[]).includes(value)) return { ok: true, level: value as ThinkingLevel }
330
332
  return {
331
333
  ok: false,
332
334
  reason: `Invalid --thinking "${raw}". Use one of: ${THINKING_LEVELS.join(', ')}, or "default" to clear.`,
@@ -1,29 +1,23 @@
1
- import { isCancel, log, note, text } from '@clack/prompts'
1
+ import { isCancel, log, note, password, select, text } from '@clack/prompts'
2
2
 
3
3
  import type { OAuthCallbacks } from '@/init/oauth-login'
4
4
 
5
5
  // Shared between `typeclaw init` (src/cli/init.ts) and `typeclaw provider
6
6
  // add/set` (src/cli/provider.ts). Both call into the same OAuth runner, so
7
7
  // they need to render the same UX: a note() box with the URL + cross-device
8
- // guidance, a `text()` prompt for the post-callback manual fallback, and a
9
- // concurrent `onManualCodeInput` prompt for users whose browser is on a
10
- // different host than the CLI. See src/init/oauth-login.ts for the contract
11
- // on each callback and why onManualCodeInput is required for cross-device.
8
+ // guidance, a select() prompt for provider-defined choices, a text() prompt
9
+ // for the post-callback manual fallback, and a concurrent onManualCodeInput
10
+ // prompt for users whose browser is on a different host than the CLI. See
11
+ // src/init/oauth-login.ts for the contract on each callback and why
12
+ // onManualCodeInput is required for cross-device.
12
13
  //
13
- // Returns `{ callbacks, dispose }` rather than bare callbacks because of a
14
- // pi-ai contract gap: pi-ai races `onManualCodeInput()` against the local
15
- // callback server (packages/ai/src/utils/oauth/anthropic.ts:210-253). When
16
- // the browser wins the race, pi-ai sets `result.code` and falls through to
17
- // token exchange WITHOUT calling `server.cancelWait()` on the manual side —
18
- // the manual `text()` prompt is left dangling in clack's render pipeline,
19
- // re-appearing after every subsequent log line. Without the dispose hook,
20
- // the user sees "Logged in to {Provider}" immediately followed by the stale
21
- // "paste the redirect URL here" prompt that's now meaningless. Each call
22
- // site (init/provider) MUST call `dispose()` in a finally after the OAuth
23
- // runner returns so the orphaned prompt aborts cleanly; clack honors the
24
- // signal by resolving the prompt with cancel state, the cancel branch
25
- // throws inside our callback, and pi-ai's outer `.catch()` swallows it
26
- // (since it stops awaiting the manual promise on the winning-browser path).
14
+ // Returns `{ callbacks, dispose }` rather than bare callbacks because pi-ai
15
+ // races `onManualCodeInput()` against the local callback server. Pi 0.87 aborts
16
+ // the losing manual prompt through its prompt signal (pi-ai
17
+ // dist/auth/oauth/anthropic.js:216-221,266); dispose remains a fallback for
18
+ // callers that end OAuth before pi reaches that race. Each call site
19
+ // (init/provider) MUST call `dispose()` in a finally after the OAuth runner
20
+ // returns so any still-live clack prompt is cancelled cleanly.
27
21
  export type OAuthCallbackHandle = {
28
22
  callbacks: OAuthCallbacks
29
23
  dispose: () => void
@@ -32,6 +26,8 @@ export type OAuthCallbackHandle = {
32
26
  export function buildOAuthCallbacks(providerName: string): OAuthCallbackHandle {
33
27
  const controller = new AbortController()
34
28
  const { signal } = controller
29
+ const promptSignal = (upstream?: AbortSignal): AbortSignal =>
30
+ upstream === undefined ? signal : AbortSignal.any([signal, upstream])
35
31
  return {
36
32
  dispose: () => controller.abort(),
37
33
  callbacks: {
@@ -56,21 +52,40 @@ export function buildOAuthCallbacks(providerName: string): OAuthCallbackHandle {
56
52
  onProgress: (message) => {
57
53
  log.info(message)
58
54
  },
59
- onPrompt: async (message, placeholder) => {
55
+ onPrompt: async (message, placeholder, upstreamSignal) => {
60
56
  const value = await text({
61
57
  message,
62
- signal,
58
+ signal: promptSignal(upstreamSignal),
63
59
  ...(placeholder !== undefined ? { placeholder } : {}),
64
60
  })
65
61
  if (isCancel(value)) return null
66
62
  return value
67
63
  },
68
- onManualCodeInput: async () => {
64
+ // clack's password() has no placeholder option (PasswordOptions).
65
+ onSecret: async (message, _placeholder, upstreamSignal) => {
66
+ const value = await password({ message, signal: promptSignal(upstreamSignal) })
67
+ if (isCancel(value)) return null
68
+ return value
69
+ },
70
+ onSelect: async (message, options, upstreamSignal) => {
71
+ const value = await select({
72
+ message,
73
+ options: options.map((option) => ({
74
+ value: option.id,
75
+ label: option.label,
76
+ hint: option.description,
77
+ })),
78
+ signal: promptSignal(upstreamSignal),
79
+ })
80
+ if (isCancel(value)) return null
81
+ return value
82
+ },
83
+ onManualCodeInput: async (upstreamSignal) => {
69
84
  const value = await text({
70
85
  message:
71
86
  'After signing in, paste the code shown on the page (some providers offer a copy button), or the full redirect address from the top of the browser:',
72
87
  placeholder: 'code, or http://localhost:1455/auth/callback?code=...&state=...',
73
- signal,
88
+ signal: promptSignal(upstreamSignal),
74
89
  })
75
90
  if (isCancel(value)) throw new Error('Login cancelled by user')
76
91
  return value
@@ -2,13 +2,60 @@ import { confirm, isCancel } from '@clack/prompts'
2
2
  import { defineCommand } from 'citty'
3
3
 
4
4
  import { config, validateConfig } from '@/config'
5
- import { resolveController } from '@/container'
5
+ import { type Controller, resolveController } from '@/container'
6
6
  import { findAgentDir, isInitialized } from '@/init'
7
7
 
8
8
  import { preflightDocker, printDockerGuidance } from './docker-preflight'
9
9
  import { guardIncompleteInit } from './incomplete-init'
10
10
  import { c, errorLine, renderStartSuccess, reportConfigWarnings, spinner } from './ui'
11
11
 
12
+ export type RestartCommandEvent =
13
+ | { kind: 'stop-spinner-start'; message: string }
14
+ | { kind: 'stop-spinner-stop'; message: string }
15
+ | { kind: 'stop-spinner-error'; message: string }
16
+ | { kind: 'start-spinner-start'; message: string }
17
+ | { kind: 'start-spinner-stop'; message: string }
18
+ | { kind: 'start-spinner-error'; message: string }
19
+ | { kind: 'warnings'; warnings: string[] }
20
+ | { kind: 'success'; output: string }
21
+
22
+ export type RestartCommandDeps = {
23
+ restart: Controller['restart']
24
+ onEvent: (event: RestartCommandEvent) => void
25
+ }
26
+
27
+ export async function runRestartCommand(
28
+ options: { cwd: string; preferredHostPort: number; forceBuild: boolean; cliEntry?: string },
29
+ deps: RestartCommandDeps,
30
+ ): Promise<{ ok: boolean }> {
31
+ deps.onEvent({ kind: 'stop-spinner-start', message: 'Stopping container...' })
32
+ let stopped = false
33
+ const warnings: string[] = []
34
+ const result = await deps.restart({
35
+ ...options,
36
+ onWarning: (warning) => warnings.push(warning),
37
+ onStopped: (stopResult) => {
38
+ stopped = true
39
+ deps.onEvent({
40
+ kind: 'stop-spinner-stop',
41
+ message: stopResult.running ? `Stopped ${c.cyan(stopResult.containerName)}.` : 'Already stopped.',
42
+ })
43
+ deps.onEvent({ kind: 'start-spinner-start', message: 'Starting container...' })
44
+ },
45
+ })
46
+ if (!result.ok) {
47
+ deps.onEvent({ kind: stopped ? 'start-spinner-error' : 'stop-spinner-error', message: result.reason })
48
+ deps.onEvent({ kind: 'warnings', warnings })
49
+ return { ok: false }
50
+ }
51
+
52
+ deps.onEvent({ kind: 'start-spinner-stop', message: 'Started.' })
53
+ deps.onEvent({ kind: 'warnings', warnings })
54
+ deps.onEvent({ kind: 'warnings', warnings: result.start.dockerfileWarnings })
55
+ deps.onEvent({ kind: 'success', output: renderStartSuccess(result.start) })
56
+ return { ok: true }
57
+ }
58
+
12
59
  export const restartCommand = defineCommand({
13
60
  meta: {
14
61
  name: 'restart',
@@ -70,30 +117,49 @@ export const restartCommand = defineCommand({
70
117
  process.exit(1)
71
118
  }
72
119
 
73
- const controller = resolveController()
74
-
75
120
  const stopSpin = spinner()
76
- stopSpin.start('Stopping container...')
121
+ const controller = resolveController()
77
122
  let startSpin: ReturnType<typeof spinner> | undefined
78
- const restarted = await controller.restart({
79
- cwd,
80
- preferredHostPort: Number(args.port),
81
- forceBuild: args.build,
82
- cliEntry: process.argv[1],
83
- onStopped: (stopped) => {
84
- stopSpin.stop(stopped.running ? `Stopped ${c.cyan(stopped.containerName)}.` : 'Already stopped.')
85
- startSpin = spinner()
86
- startSpin.start('Starting container...')
123
+ const result = await runRestartCommand(
124
+ {
125
+ cwd,
126
+ preferredHostPort: Number(args.port),
127
+ forceBuild: args.build,
128
+ cliEntry: process.argv[1],
87
129
  },
88
- })
89
- if (!restarted.ok) {
90
- if (startSpin === undefined) stopSpin.error(restarted.reason)
91
- else startSpin.error(restarted.reason)
92
- process.exit(1)
93
- }
94
- startSpin?.stop('Started.')
95
-
96
- reportConfigWarnings(restarted.start.dockerfileWarnings)
97
- console.log(renderStartSuccess(restarted.start))
130
+ {
131
+ restart: (restartOptions) => controller.restart(restartOptions),
132
+ onEvent: (event) => {
133
+ switch (event.kind) {
134
+ case 'stop-spinner-start':
135
+ stopSpin.start(event.message)
136
+ break
137
+ case 'stop-spinner-stop':
138
+ stopSpin.stop(event.message)
139
+ break
140
+ case 'stop-spinner-error':
141
+ stopSpin.error(event.message)
142
+ break
143
+ case 'start-spinner-start':
144
+ startSpin = spinner()
145
+ startSpin.start(event.message)
146
+ break
147
+ case 'start-spinner-stop':
148
+ startSpin?.stop(event.message)
149
+ break
150
+ case 'start-spinner-error':
151
+ startSpin?.error(event.message)
152
+ break
153
+ case 'warnings':
154
+ reportConfigWarnings(event.warnings)
155
+ break
156
+ case 'success':
157
+ console.log(event.output)
158
+ break
159
+ }
160
+ },
161
+ },
162
+ )
163
+ if (!result.ok) process.exit(1)
98
164
  },
99
165
  })
package/src/cli/start.ts CHANGED
@@ -2,13 +2,48 @@ import { confirm, isCancel } from '@clack/prompts'
2
2
  import { defineCommand } from 'citty'
3
3
 
4
4
  import { config, validateConfig } from '@/config'
5
- import { resolveController } from '@/container'
5
+ import { type Controller, resolveController } from '@/container'
6
6
  import { findAgentDir, isInitialized } from '@/init'
7
7
 
8
8
  import { preflightDocker, printDockerGuidance } from './docker-preflight'
9
9
  import { guardIncompleteInit } from './incomplete-init'
10
10
  import { errorLine, renderStartSuccess, reportConfigWarnings, spinner } from './ui'
11
11
 
12
+ export type StartCommandEvent =
13
+ | { kind: 'spinner-start'; message: string }
14
+ | { kind: 'spinner-stop'; message: string }
15
+ | { kind: 'spinner-error'; message: string }
16
+ | { kind: 'warnings'; warnings: string[] }
17
+ | { kind: 'success'; output: string }
18
+
19
+ export type StartCommandDeps = {
20
+ start: Controller['start']
21
+ onEvent: (event: StartCommandEvent) => void
22
+ }
23
+
24
+ export async function runStartCommand(
25
+ options: { cwd: string; preferredHostPort: number; forceBuild: boolean; cliEntry?: string },
26
+ deps: StartCommandDeps,
27
+ ): Promise<{ ok: boolean }> {
28
+ deps.onEvent({ kind: 'spinner-start', message: 'Starting container...' })
29
+ const warnings: string[] = []
30
+ const result = await deps.start({
31
+ ...options,
32
+ onWarning: (warning) => warnings.push(warning),
33
+ })
34
+ if (!result.ok) {
35
+ deps.onEvent({ kind: 'spinner-error', message: result.reason })
36
+ deps.onEvent({ kind: 'warnings', warnings })
37
+ return { ok: false }
38
+ }
39
+
40
+ deps.onEvent({ kind: 'spinner-stop', message: result.alreadyRunning ? 'Already running.' : 'Started.' })
41
+ deps.onEvent({ kind: 'warnings', warnings })
42
+ deps.onEvent({ kind: 'warnings', warnings: result.dockerfileWarnings })
43
+ deps.onEvent({ kind: 'success', output: renderStartSuccess(result) })
44
+ return { ok: true }
45
+ }
46
+
12
47
  export const startCommand = defineCommand({
13
48
  meta: {
14
49
  name: 'start',
@@ -71,20 +106,37 @@ export const startCommand = defineCommand({
71
106
  }
72
107
 
73
108
  const s = spinner()
74
- s.start('Starting container...')
75
- const result = await resolveController().start({
76
- cwd,
77
- preferredHostPort: Number(args.port),
78
- forceBuild: args.build,
79
- cliEntry: process.argv[1],
80
- })
81
- if (!result.ok) {
82
- s.error(result.reason)
83
- process.exit(1)
84
- }
85
- s.stop(result.alreadyRunning ? 'Already running.' : 'Started.')
86
-
87
- reportConfigWarnings(result.dockerfileWarnings)
88
- console.log(renderStartSuccess(result))
109
+ const controller = resolveController()
110
+ const result = await runStartCommand(
111
+ {
112
+ cwd,
113
+ preferredHostPort: Number(args.port),
114
+ forceBuild: args.build,
115
+ cliEntry: process.argv[1],
116
+ },
117
+ {
118
+ start: (startOptions) => controller.start(startOptions),
119
+ onEvent: (event) => {
120
+ switch (event.kind) {
121
+ case 'spinner-start':
122
+ s.start(event.message)
123
+ break
124
+ case 'spinner-stop':
125
+ s.stop(event.message)
126
+ break
127
+ case 'spinner-error':
128
+ s.error(event.message)
129
+ break
130
+ case 'warnings':
131
+ reportConfigWarnings(event.warnings)
132
+ break
133
+ case 'success':
134
+ console.log(event.output)
135
+ break
136
+ }
137
+ },
138
+ },
139
+ )
140
+ if (!result.ok) process.exit(1)
89
141
  },
90
142
  })
package/src/cli/status.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { defineCommand } from 'citty'
2
2
 
3
- import { type ContainerStatus, type DockerExec, resolveController } from '@/container'
3
+ import { containerNameFromCwd, type ContainerStatus, type DockerExec, resolveController } from '@/container'
4
4
  import { isDaemonReachable, send } from '@/hostd'
5
5
  import type { StatusResult } from '@/hostd'
6
6
  import { findAgentDir } from '@/init'
@@ -13,9 +13,16 @@ export type HostdStatus =
13
13
  | { kind: 'not-registered'; reason: string }
14
14
  | { kind: 'registered'; cwd: string; forwardedPorts: number[] }
15
15
 
16
+ // `docker-unavailable` is not a container state — it is the absence of an
17
+ // answer. It exists so `status` can still report everything that does NOT
18
+ // depend on Docker (agent dir, container name, host daemon, forwarded ports)
19
+ // when the daemon is wedged. A diagnostic command that reports nothing at all
20
+ // because the thing it diagnoses is broken is the least useful moment to lose.
21
+ export type DockerUnavailableStatus = { kind: 'docker-unavailable'; containerName: string; summary: string }
22
+
16
23
  export type StatusReport = {
17
24
  cwd: string
18
- container: ContainerStatus
25
+ container: ContainerStatus | DockerUnavailableStatus
19
26
  hostd: HostdStatus
20
27
  }
21
28
 
@@ -46,7 +53,22 @@ export async function runStatus(deps: RunStatusDeps = {}): Promise<void> {
46
53
  const cwd = deps.cwd ?? findAgentDir(process.cwd()) ?? process.cwd()
47
54
 
48
55
  const preflight = await (deps.preflight ?? preflightDocker)()
56
+ const useColor = Boolean(process.stdout.isTTY) && process.env.NO_COLOR === undefined
57
+ const write = deps.write ?? ((text: string) => process.stdout.write(text))
58
+
59
+ // Docker is unreachable: report what we can still learn without it rather
60
+ // than dying on the guidance alone. hostd is a separate process reached over
61
+ // its own socket, so its registration and forwarded ports stay readable — and
62
+ // during a wedged-daemon incident that is exactly the state worth seeing.
49
63
  if (!preflight.ok) {
64
+ const containerName = containerNameFromCwd(cwd)
65
+ const hostd = await (deps.fetchHostd ?? fetchHostdStatus)(containerName)
66
+ const container: DockerUnavailableStatus = {
67
+ kind: 'docker-unavailable',
68
+ containerName,
69
+ summary: preflight.summary,
70
+ }
71
+ write(`${formatStatus({ cwd, container, hostd }, { useColor })}\n`)
50
72
  ;(deps.onDockerUnavailable ?? defaultOnDockerUnavailable)(preflight)
51
73
  return
52
74
  }
@@ -54,14 +76,17 @@ export async function runStatus(deps: RunStatusDeps = {}): Promise<void> {
54
76
  const container = await resolveController().status({ cwd, exec: deps.exec })
55
77
  const hostd = await (deps.fetchHostd ?? fetchHostdStatus)(container.containerName)
56
78
 
57
- const useColor = Boolean(process.stdout.isTTY) && process.env.NO_COLOR === undefined
58
- const write = deps.write ?? ((text: string) => process.stdout.write(text))
59
79
  write(`${formatStatus({ cwd, container, hostd }, { useColor })}\n`)
60
80
  }
61
81
 
62
- function defaultOnDockerUnavailable(failure: Extract<DockerPreflightResult, { ok: false }>): never {
82
+ // Sets `process.exitCode` instead of calling `process.exit()`: the degraded
83
+ // report is written immediately before this, and an immediate exit can
84
+ // terminate the process before a redirected or piped stdout has drained —
85
+ // truncating the very output this path exists to produce. Letting runStatus
86
+ // return lets the runtime flush and still exit non-zero.
87
+ function defaultOnDockerUnavailable(failure: Extract<DockerPreflightResult, { ok: false }>): void {
63
88
  printDockerGuidance(failure)
64
- process.exit(1)
89
+ process.exitCode = 1
65
90
  }
66
91
 
67
92
  async function fetchHostdStatus(containerName: string): Promise<HostdStatus> {
@@ -138,6 +163,13 @@ function appendContainerSection(lines: string[], report: StatusReport, p: Palett
138
163
  const container = report.container
139
164
  lines.push(`${p.bold('Container')} ${container.containerName}`)
140
165
  lines.push(row('cwd', report.cwd))
166
+
167
+ if (container.kind === 'docker-unavailable') {
168
+ lines.push(row('state', p.red('unknown')))
169
+ lines.push(` ${p.dim(container.summary)}`)
170
+ return
171
+ }
172
+
141
173
  lines.push(row('image', container.imageTag))
142
174
 
143
175
  if (container.kind === 'missing') {