typeclaw 0.39.0 → 0.39.1

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 (36) hide show
  1. package/README.md +1 -0
  2. package/package.json +2 -2
  3. package/src/agent/attention-escalation.ts +154 -4
  4. package/src/agent/git-nudge.ts +7 -7
  5. package/src/agent/session-origin.ts +21 -0
  6. package/src/bundled-plugins/backup/index.ts +5 -2
  7. package/src/bundled-plugins/backup/runner.ts +55 -23
  8. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +7 -8
  9. package/src/bundled-plugins/memory/dreaming.ts +37 -24
  10. package/src/channels/adapters/kakaotalk-membership.ts +67 -0
  11. package/src/channels/adapters/kakaotalk.ts +8 -0
  12. package/src/channels/adapters/line-token.ts +55 -0
  13. package/src/channels/adapters/line.ts +74 -0
  14. package/src/channels/adapters/webex-bot-classify.ts +14 -1
  15. package/src/channels/adapters/webex-bot.ts +24 -1
  16. package/src/channels/adapters/webex-classify.ts +16 -1
  17. package/src/channels/adapters/webex.ts +27 -1
  18. package/src/channels/router.ts +55 -2
  19. package/src/cli/hostd.ts +40 -0
  20. package/src/config/config.ts +7 -5
  21. package/src/container/shared.ts +115 -14
  22. package/src/container/shell.ts +12 -2
  23. package/src/doctor/commit.ts +10 -10
  24. package/src/dreams/git.ts +20 -7
  25. package/src/dreams/index.ts +22 -7
  26. package/src/git/reconcile-ignored.ts +56 -27
  27. package/src/git/resolve-agent-git.ts +12 -0
  28. package/src/git/system-commit.ts +16 -10
  29. package/src/hostd/daemon.ts +16 -0
  30. package/src/hostd/webex-renewal-manager.ts +216 -0
  31. package/src/init/dockerfile.ts +13 -4
  32. package/src/init/gitignore.ts +4 -2
  33. package/src/secrets/schema.ts +1 -0
  34. package/src/secrets/webex-renewal.ts +215 -0
  35. package/src/server/index.ts +25 -3
  36. package/typeclaw.schema.json +6 -1
@@ -5,7 +5,7 @@ import type { AssistantMessage } from '@mariozechner/pi-ai'
5
5
  import { SessionManager } from '@mariozechner/pi-coding-agent'
6
6
 
7
7
  import { createSession, renderTurnRoleAnchor, renderTurnTimeAnchor, type AgentSession } from '@/agent'
8
- import { applyTurnThinkingLevel } from '@/agent/attention-escalation'
8
+ import { applyTurnThinkingLevel, getQuestionSignal, type QuestionSignal } from '@/agent/attention-escalation'
9
9
  import { forgetSharedLoopGuardTool } from '@/agent/plugin-tools'
10
10
  import { subscribeProviderErrors } from '@/agent/provider-error'
11
11
  import type { RestartHandoff } from '@/agent/restart-handoff'
@@ -578,6 +578,16 @@ type LiveSession = {
578
578
  // turn moves `session.thinkingLevel` to `high`, so the live getter can't be the
579
579
  // reset target — this preserves the real default across the session's lifetime.
580
580
  turnThinkingDefault: AgentSession['thinkingLevel']
581
+ // Last COMPLETED real user turn's question shape, for cross-turn "Jeff Bezos"
582
+ // escalation. Read by the next turn; committed from pendingUserTurnSignal only
583
+ // when a logical turn finishes (no empty-turn retry queued).
584
+ lastQuestionSignal: QuestionSignal | null
585
+ // A real user turn's question shape captured at turn start but not yet
586
+ // committed: a `length`/`aborted` truncation spans the original batch plus
587
+ // reminder-only retry iterations, so the signal commits to lastQuestionSignal
588
+ // only when that whole logical turn completes (success or fallback), never
589
+ // from the truncated attempt and never leaving stale state across the turn.
590
+ pendingUserTurnSignal: { signal: QuestionSignal } | null
581
591
  sessionId: string
582
592
  dispose: () => Promise<void>
583
593
  hooks: HookBus | undefined
@@ -788,6 +798,12 @@ type LiveSession = {
788
798
  // shape as the skip lock. `null` when no disengage has been recorded.
789
799
  // Compared by `turnSeq` so a stale value can't leak across turns.
790
800
  disengagedTurn: number | null
801
+ // Stamped with the current `turnSeq` when validateChannelTurn posts the
802
+ // empty-turn fallback (retry exhaustion). Read by the cross-turn signal commit
803
+ // so a fallback turn — which produced no usable assistant reply — does not seed
804
+ // question escalation. Compared by `turnSeq` so a stale value can't leak across
805
+ // turns.
806
+ emptyTurnFallbackTurn: number | null
791
807
  // Captured by drain() at batch dequeue; read+cleared by send() on the
792
808
  // first tool-source send of the turn. The anchor decision (delay
793
809
  // threshold + intervening-observed check) is evaluated at SEND time
@@ -1665,6 +1681,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1665
1681
  keyId,
1666
1682
  session: created.session,
1667
1683
  turnThinkingDefault: created.session.thinkingLevel,
1684
+ lastQuestionSignal: null,
1685
+ pendingUserTurnSignal: null,
1668
1686
  sessionId: created.sessionId,
1669
1687
  dispose: created.dispose,
1670
1688
  hooks: created.hooks,
@@ -1722,6 +1740,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1722
1740
  skippedTurn: null,
1723
1741
  skipLockedSendTurn: null,
1724
1742
  disengagedTurn: null,
1743
+ emptyTurnFallbackTurn: null,
1725
1744
  pendingQuoteCandidate: null,
1726
1745
  recentEngagedPeerBotTurns: [],
1727
1746
  consecutiveEngagedPeerBotTurns: 0,
@@ -2398,24 +2417,57 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2398
2417
  live.successfulSendsAtTurnStart = successfulSendsBeforePrompt
2399
2418
  live.skipLockedSendTurn = null
2400
2419
  live.disengagedTurn = null
2420
+ live.emptyTurnFallbackTurn = null
2401
2421
  live.policyDeniedToolSendsThisTurn.clear()
2402
2422
  resetReviewTurn(live.sessionId)
2403
2423
  const isRealUserTurn = batch.length > 0
2404
2424
  const retrievalQuery = composeRetrievalQuery(batch)
2425
+ // A fresh real-user batch opens a new logical turn. Capture its question
2426
+ // shape as PENDING (committed only once the turn completes below). The
2427
+ // drain is serial and retries are reminder-only, so a prior pending must
2428
+ // already be resolved; a leftover here means a logical turn never
2429
+ // completed — fail closed by discarding it rather than misattributing.
2430
+ if (isRealUserTurn) {
2431
+ live.pendingUserTurnSignal = { signal: getQuestionSignal(retrievalQuery) }
2432
+ }
2405
2433
  const retrievalContext = await fireSessionTurnStart(live, retrievalQuery)
2406
2434
  const promptText = retrievalContext.results.length > 0 ? `${text}\n\n${retrievalContext.results}` : text
2407
- applyTurnThinkingLevel(live.session, retrievalQuery, live.turnThinkingDefault)
2435
+ applyTurnThinkingLevel(live.session, retrievalQuery, live.turnThinkingDefault, live.lastQuestionSignal)
2408
2436
  live.promptInFlight = true
2409
2437
  try {
2410
2438
  await live.session.prompt(promptText)
2411
2439
  await validateChannelTurn(live, successfulSendsBeforePrompt)
2412
2440
  live.consecutiveAborts = 0
2441
+ // Resolve the pending logical-turn signal on a binary rule: ONLY a
2442
+ // usable assistant reply (real model prose the user saw) seeds the next
2443
+ // turn's escalation. Every other terminal outcome CLEARS lastQuestionSignal
2444
+ // so an older question can't leak across the failed/silent turn:
2445
+ // - retry queued (`length`/`aborted`, budget left): turn still in
2446
+ // flight → leave both for the reminder-only iteration that ends it.
2447
+ // - usable reply → commit the pending signal.
2448
+ // - provider error / empty-turn fallback / NO_REPLY / skip (no usable
2449
+ // reply) → clear BOTH (pending and lastQuestionSignal).
2450
+ // A fallback sends via source:'system', which also bumps
2451
+ // successfulChannelSends, so it must be excluded explicitly.
2452
+ const retryQueuedThisTurn = live.emptyTurnRetries > emptyTurnRetriesBeforePrompt
2453
+ const providerErrorThisTurn = assistantLeafStopReason(live.session) === 'error'
2454
+ const fallbackPostedThisTurn = live.emptyTurnFallbackTurn === live.turnSeq
2455
+ const sentReplyThisTurn = live.successfulChannelSends > successfulSendsBeforePrompt
2456
+ const usableReplyThisTurn = sentReplyThisTurn && !fallbackPostedThisTurn && !providerErrorThisTurn
2457
+ if (live.pendingUserTurnSignal !== null && !retryQueuedThisTurn) {
2458
+ live.lastQuestionSignal = usableReplyThisTurn ? live.pendingUserTurnSignal.signal : null
2459
+ live.pendingUserTurnSignal = null
2460
+ }
2413
2461
  logger.info(`[channels] ${live.keyId} prompted elapsed_ms=${now() - promptStart}`)
2414
2462
  } catch (err) {
2415
2463
  logger.error(`[channels] ${live.keyId}: prompt threw: ${describe(err)}`)
2416
2464
  live.consecutiveSends.clear()
2417
2465
  live.lastSentText.clear()
2418
2466
  live.lastSendLeafId = null
2467
+ // A thrown prompt is a non-usable terminal outcome: drop pending AND
2468
+ // clear the prior signal so an older question can't leak across it.
2469
+ live.pendingUserTurnSignal = null
2470
+ live.lastQuestionSignal = null
2419
2471
  } finally {
2420
2472
  live.promptInFlight = false
2421
2473
  const sentReplyThisTurn = live.successfulChannelSends > successfulSendsBeforePrompt
@@ -3533,6 +3585,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3533
3585
  }
3534
3586
  const postEmptyTurnFallback = async (cause: string): Promise<void> => {
3535
3587
  logger.warn(`[channels] ${live.keyId} empty_turn_fallback cause=${cause}`)
3588
+ live.emptyTurnFallbackTurn = live.turnSeq
3536
3589
  const result = await send(
3537
3590
  {
3538
3591
  adapter: live.key.adapter,
package/src/cli/hostd.ts CHANGED
@@ -7,6 +7,7 @@ import { createKakaoRenewalManager } from '@/hostd/kakao-renewal-manager'
7
7
  import { createPortbrokerManager } from '@/hostd/portbroker-manager'
8
8
  import type { SupervisorLogEvent, SupervisorRestart } from '@/hostd/supervisor'
9
9
  import { computeSourceVersion, resolveSrcRoot, UNVERSIONED_SENTINEL } from '@/hostd/version'
10
+ import { createWebexRenewalManager } from '@/hostd/webex-renewal-manager'
10
11
  import { validateRestartDeps, type RestartDepsPreflightResult } from '@/init/restart-deps-preflight'
11
12
 
12
13
  export const hostdCommand = defineCommand({
@@ -37,6 +38,18 @@ export const hostdCommand = defineCommand({
37
38
  },
38
39
  shouldRenew: ({ cwd }) => kakaoChannelConfigured(cwd),
39
40
  })
41
+ const webexRenewal = createWebexRenewalManager({
42
+ onLog: (event) => writeLogLine(formatLog(event)),
43
+ onRenewalOk: async ({ containerName, cwd }) => {
44
+ // Restart so the in-memory WebexClient picks up the renewed token from
45
+ // secrets.json. Without this, the cron writes a fresh token but the
46
+ // running adapter keeps the old token in its getToken closure and still
47
+ // 401s on every outbound REST call + KMS key fetch.
48
+ const result = await hostdRestart({ containerName, cwd })
49
+ if (!result.ok) throw new Error(result.reason)
50
+ },
51
+ shouldRenew: ({ cwd }) => webexChannelConfigured(cwd),
52
+ })
40
53
 
41
54
  const daemon = await startDaemon({
42
55
  onLog: (e) => writeLogLine(formatLog(e)),
@@ -44,6 +57,7 @@ export const hostdCommand = defineCommand({
44
57
  onShutdown: () => process.exit(0),
45
58
  portbroker,
46
59
  kakaoRenewal,
60
+ webexRenewal,
47
61
  restartPreflight: buildHostdRestartPreflight(cliEntry, version, defaultPreflightDeps),
48
62
  restart: hostdRestart,
49
63
  })
@@ -53,6 +67,7 @@ export const hostdCommand = defineCommand({
53
67
  .stop()
54
68
  .then(() => portbroker.drain())
55
69
  .then(() => kakaoRenewal.drain())
70
+ .then(() => webexRenewal.drain())
56
71
  .then(() => process.exit(0))
57
72
  }
58
73
  process.on('SIGTERM', shutdown)
@@ -201,6 +216,22 @@ function formatLog(event: DaemonLogEvent | SupervisorLogEvent): string {
201
216
  return `[hostd] kakao renewal scheduled container restart for ${event.containerName} account=${event.accountId}`
202
217
  case 'kakao-renewal-restart-failed':
203
218
  return `[hostd] kakao renewal container restart FAILED for ${event.containerName} account=${event.accountId}: ${event.reason}`
219
+ case 'webex-renewal-tick-start':
220
+ return `[hostd] webex renewal tick started for ${event.containerName}`
221
+ case 'webex-renewal-tick-skipped':
222
+ return `[hostd] webex renewal skipped for ${event.containerName}: ${event.reason}${event.expiresInMs !== undefined ? ` (expires in ${Math.round(event.expiresInMs / 1000 / 60 / 60)}h)` : ''}`
223
+ case 'webex-renewal-tick-ok':
224
+ return `[hostd] webex renewal OK for ${event.containerName} account=${event.accountId} (new token expires ${new Date(event.nextExpiresAt).toISOString()})`
225
+ case 'webex-renewal-tick-reauth-required':
226
+ return `[hostd] webex renewal REAUTH REQUIRED for ${event.containerName} account=${event.accountId} reason=${event.reason} — ${event.message}`
227
+ case 'webex-renewal-tick-transient-failure':
228
+ return `[hostd] webex renewal transient failure for ${event.containerName} account=${event.accountId}: ${event.reason}`
229
+ case 'webex-renewal-tick-error':
230
+ return `[hostd] webex renewal ERROR for ${event.containerName}: ${event.error}`
231
+ case 'webex-renewal-restart-scheduled':
232
+ return `[hostd] webex renewal scheduled container restart for ${event.containerName} account=${event.accountId}`
233
+ case 'webex-renewal-restart-failed':
234
+ return `[hostd] webex renewal container restart FAILED for ${event.containerName} account=${event.accountId}: ${event.reason}`
204
235
  }
205
236
  }
206
237
 
@@ -219,6 +250,15 @@ function kakaoChannelConfigured(cwd: string): boolean {
219
250
  }
220
251
  }
221
252
 
253
+ function webexChannelConfigured(cwd: string): boolean {
254
+ try {
255
+ const cfg = loadConfigSync(cwd)
256
+ return cfg.channels?.webex !== undefined
257
+ } catch {
258
+ return false
259
+ }
260
+ }
261
+
222
262
  function formatPortForwardEvent(event: import('@/portbroker').PortForwardEvent): string {
223
263
  switch (event.kind) {
224
264
  case 'port-forward-opened':
@@ -481,15 +481,17 @@ export type SandboxConfig = z.infer<typeof sandboxSchema>
481
481
 
482
482
  // Host-stage `typeclaw compose` knobs. `exclude: true` skips this agent during
483
483
  // compose discovery (same effect as parking it under an `_`-prefixed dir, but
484
- // without renaming the folder). The container never reads this block — it's a
485
- // pure compose CLI hint, so omitting it keeps the agent in every compose
486
- // operation. Namespaced under `compose` so future compose-only settings have a
487
- // home without crowding the top level.
484
+ // without renaming the folder). `monorepo` is a host-stage scaffolding hint.
485
+ // The container never reads this block — it's a pure compose CLI hint, so
486
+ // omitting it keeps the agent in every compose operation. Namespaced under
487
+ // `compose` so future compose-only settings have a home without crowding the
488
+ // top level.
488
489
  export const composeSchema = z
489
490
  .object({
490
491
  exclude: z.boolean().default(false),
492
+ monorepo: z.boolean().default(false),
491
493
  })
492
- .default({ exclude: false })
494
+ .default({ exclude: false, monorepo: false })
493
495
 
494
496
  export type ComposeConfig = z.infer<typeof composeSchema>
495
497
 
@@ -1,5 +1,8 @@
1
1
  import { createHash } from 'node:crypto'
2
- import { basename, resolve } from 'node:path'
2
+ import { existsSync } from 'node:fs'
3
+ import { basename, resolve, win32 } from 'node:path'
4
+
5
+ import { isWindows } from '@/shared'
3
6
 
4
7
  export type DockerExecResult = { exitCode: number; stdout: string; stderr: string }
5
8
 
@@ -11,16 +14,27 @@ export type DockerExec = (
11
14
  export const defaultDockerExec: DockerExec = async (args, options) => {
12
15
  const bun = getBun()
13
16
  if (!bun) return { exitCode: -1, stdout: '', stderr: 'bun runtime not available' }
14
- // Bun.spawn throws synchronously with code 'ENOENT' when docker isn't on
15
- // $PATH (rather than returning a non-zero exit). Two overloads (pipe vs
16
- // inherit) so each spawn call site has the literal stdout/stderr type
17
- // attached — that's what lets `new Response(proc.stdout)` typecheck on
18
- // the piped path. `signal` is forwarded to Bun.spawn so callers can bound
19
- // long-running docker subcommands (e.g. `docker logs` on a stuck daemon).
17
+ // Resolve `docker` to an absolute path before spawning. Bun.spawn() resolves
18
+ // a bare command name through Bun.which() internally, but Windows PATH/PATHEXT
19
+ // resolution has a string of historical bugs (oven-sh/bun#16070, #11182,
20
+ // #29636) that make `cmd: ['docker', …]` throw ENOENT even when Docker
21
+ // Desktop is installed and docker.exe is on %PATH% — surfacing as the
22
+ // misleading "Docker is not installed." on a machine that has Docker.
23
+ // dockerCmd() goes through Bun.which(), which reliably honors PATHEXT and
24
+ // returns the full docker.exe path; it returns null only when docker is
25
+ // genuinely absent from PATH, which maps to the binary-missing sentinel.
26
+ const cmd = dockerCmd(args)
27
+ if (cmd === null) return { exitCode: -1, stdout: '', stderr: DOCKER_NOT_FOUND_STDERR }
28
+ // Two overloads (pipe vs inherit) so each spawn call site has the literal
29
+ // stdout/stderr type attached — that's what lets `new Response(proc.stdout)`
30
+ // typecheck on the piped path. `signal` is forwarded to Bun.spawn so callers
31
+ // can bound long-running docker subcommands (e.g. `docker logs` on a stuck
32
+ // daemon). The ENOENT catch stays as a safety net for the race where the
33
+ // binary disappears between resolution and spawn.
20
34
  if (options?.inheritStdio) {
21
35
  try {
22
36
  const proc = bun.spawn({
23
- cmd: ['docker', ...args],
37
+ cmd,
24
38
  cwd: options.cwd,
25
39
  stdout: 'inherit',
26
40
  stderr: 'inherit',
@@ -36,7 +50,7 @@ export const defaultDockerExec: DockerExec = async (args, options) => {
36
50
  }
37
51
  try {
38
52
  const proc = bun.spawn({
39
- cmd: ['docker', ...args],
53
+ cmd,
40
54
  cwd: options?.cwd,
41
55
  stdout: 'pipe',
42
56
  stderr: 'pipe',
@@ -54,11 +68,94 @@ export const defaultDockerExec: DockerExec = async (args, options) => {
54
68
  }
55
69
  }
56
70
 
57
- // Sentinel stderr from defaultDockerExec when Bun.spawn throws ENOENT.
71
+ // Sentinel stderr from defaultDockerExec when docker can't be resolved/spawned.
58
72
  // checkDockerAvailable matches on this exact string to distinguish
59
73
  // "binary missing" from "daemon down".
60
74
  export const DOCKER_NOT_FOUND_STDERR = 'docker: command not found in $PATH'
61
75
 
76
+ export type DockerBinaryProbes = {
77
+ which?: (command: string) => string | null
78
+ platform?: NodeJS.Platform
79
+ env?: NodeJS.ProcessEnv
80
+ exists?: (path: string) => boolean
81
+ }
82
+
83
+ // Resolves the `docker` binary to an absolute path. First via Bun.which(),
84
+ // which — unlike a bare `cmd: ['docker']` handed to Bun.spawn() — reliably
85
+ // honors Windows PATHEXT and returns e.g. C:\…\docker.exe. On POSIX the
86
+ // resolved path equals what the bare name would have found.
87
+ //
88
+ // When Bun.which() finds nothing on Windows we fall back to Docker Desktop's
89
+ // known install locations: its installer registers docker.exe on the SYSTEM
90
+ // PATH, so a shell/process started before the install (or with a customized
91
+ // PATH) inherits a stale PATH where Bun.which can't see docker even though the
92
+ // binary exists and the engine is running — the real-world "Docker is not
93
+ // installed" report on a machine with a working Docker. Probing these paths
94
+ // fixes detection without a reinstall or PATH edit. The MS-Store packaged
95
+ // build is deliberately NOT probed: its binary lives in ACL-locked
96
+ // WindowsApps and can't be executed by a child process anyway.
97
+ //
98
+ // Returns null when docker is genuinely absent, which callers translate into
99
+ // the binary-missing sentinel. Probes are injectable so tests stay
100
+ // deterministic without depending on a real docker install or host platform.
101
+ export function resolveDockerBinary(probes: DockerBinaryProbes = {}): string | null {
102
+ const which = probes.which ?? ((command: string) => getBun()?.which(command) ?? null)
103
+ const fromPath = which('docker')
104
+ if (fromPath !== null) return fromPath
105
+
106
+ const platform = probes.platform ?? process.platform
107
+ if (!isWindows(platform)) return null
108
+
109
+ const exists = probes.exists ?? existsSync
110
+ for (const candidate of windowsDockerCandidates(probes.env ?? process.env)) {
111
+ if (exists(candidate)) return candidate
112
+ }
113
+ return null
114
+ }
115
+
116
+ // Real, child-process-executable docker.exe locations across the common
117
+ // Windows install methods, most-canonical first. All are confirmed real
118
+ // binaries or executable shims (not ACL-locked WindowsApps Store stubs).
119
+ // Probe order prefers Docker Desktop, then package-manager Docker, then the
120
+ // standalone CLI, then the Rancher Desktop alternative runtime. An
121
+ // arbitrary `--installation-dir` install can't be enumerated and is left to
122
+ // Bun.which/PATH.
123
+ function windowsDockerCandidates(env: NodeJS.ProcessEnv): string[] {
124
+ const candidates: string[] = []
125
+ // win32.join (not the host-default join) so the probe builds backslash paths
126
+ // regardless of the host the resolver runs/tests on.
127
+ const add = (root: string | undefined, ...segments: string[]): void => {
128
+ if (root) candidates.push(win32.join(root, ...segments))
129
+ }
130
+ // ProgramW6432 covers a 32-bit Bun seeing the WOW64-redirected ProgramFiles.
131
+ const programFiles = env.ProgramW6432 ?? env.ProgramFiles ?? 'C:\\Program Files'
132
+ const programData = env.ProgramData ?? 'C:\\ProgramData'
133
+
134
+ // Docker Desktop: all-users, per-user, and the installer symlink dir.
135
+ add(programFiles, 'Docker', 'Docker', 'resources', 'bin', 'docker.exe')
136
+ add(env.LOCALAPPDATA, 'Programs', 'DockerDesktop', 'resources', 'bin', 'docker.exe')
137
+ add(programData, 'DockerDesktop', 'version-bin', 'docker.exe')
138
+ // Docker Desktop pre-3.3.1 layout (resources\docker.exe, no \bin).
139
+ add(programFiles, 'Docker', 'Docker', 'resources', 'docker.exe')
140
+ // Chocolatey and Scoop shims (executable redirectors, on PATH after install).
141
+ add(programData, 'chocolatey', 'bin', 'docker.exe')
142
+ add(env.USERPROFILE, 'scoop', 'shims', 'docker.exe')
143
+ // Standalone Docker CLI binary (Windows Server / manual `Expand-Archive`).
144
+ add(programFiles, 'Docker', 'docker.exe')
145
+ // Rancher Desktop's bundled Moby docker CLI (note the doubled `resources`).
146
+ add(programFiles, 'Rancher Desktop', 'resources', 'resources', 'win32', 'bin', 'docker.exe')
147
+ return candidates
148
+ }
149
+
150
+ // Builds the argv for a docker invocation with the binary resolved to an
151
+ // absolute path (see resolveDockerBinary). Returns null when docker is absent
152
+ // from PATH. The resolver is injectable so callers and tests stay deterministic
153
+ // without depending on a real docker install.
154
+ export function dockerCmd(args: string[], resolveBinary: () => string | null = resolveDockerBinary): string[] | null {
155
+ const binary = resolveBinary()
156
+ return binary === null ? null : [binary, ...args]
157
+ }
158
+
62
159
  // Collapse a multi-line `docker` CLI stderr into a single readable clause
63
160
  // suitable for inline `reason:` strings. The motivating case is `compose
64
161
  // restart`, which prints one row per agent — raw stderr from a failed
@@ -299,8 +396,10 @@ function sanitizeContainerName(name: string): string {
299
396
  export async function imageExists(tag: string): Promise<boolean> {
300
397
  const bun = getBun()
301
398
  if (!bun) return false
399
+ const cmd = dockerCmd(['image', 'inspect', tag])
400
+ if (cmd === null) return false
302
401
  const proc = bun.spawn({
303
- cmd: ['docker', 'image', 'inspect', tag],
402
+ cmd,
304
403
  stdout: 'pipe',
305
404
  stderr: 'pipe',
306
405
  })
@@ -323,8 +422,10 @@ export type ContainerState = { exists: false } | { exists: true; running: boolea
323
422
  export async function inspectContainer(name: string): Promise<ContainerState> {
324
423
  const bun = getBun()
325
424
  if (!bun) return { exists: false }
425
+ const cmd = dockerCmd(['inspect', '--format', '{{.State.Running}}', name])
426
+ if (cmd === null) return { exists: false }
326
427
  const proc = bun.spawn({
327
- cmd: ['docker', 'inspect', '--format', '{{.State.Running}}', name],
428
+ cmd,
328
429
  stdout: 'pipe',
329
430
  stderr: 'pipe',
330
431
  })
@@ -333,6 +434,6 @@ export async function inspectContainer(name: string): Promise<ContainerState> {
333
434
  return { exists: true, running: out === 'true' }
334
435
  }
335
436
 
336
- export function getBun(): { spawn: typeof Bun.spawn } | undefined {
337
- return (globalThis as { Bun?: { spawn: typeof Bun.spawn } }).Bun
437
+ export function getBun(): { spawn: typeof Bun.spawn; which: typeof Bun.which } | undefined {
438
+ return (globalThis as { Bun?: { spawn: typeof Bun.spawn; which: typeof Bun.which } }).Bun
338
439
  }
@@ -1,4 +1,4 @@
1
- import { containerNameFromCwd, getBun, inspectContainer, type ContainerState } from './shared'
1
+ import { containerNameFromCwd, dockerCmd, getBun, inspectContainer, type ContainerState } from './shared'
2
2
 
3
3
  export type ShellPlan = {
4
4
  containerName: string
@@ -10,6 +10,7 @@ export type ShellResult = { ok: true; containerName: string; exitCode: number }
10
10
  type ShellDeps = {
11
11
  inspect?: (name: string) => Promise<ContainerState>
12
12
  spawn?: InteractiveSpawn
13
+ resolveDocker?: () => string | null
13
14
  }
14
15
 
15
16
  type InteractiveSpawn = (options: {
@@ -30,6 +31,15 @@ export async function shell(
30
31
 
31
32
  const { containerName, shell: plannedShell } = planShell(cwd, { shell: shellPath })
32
33
 
34
+ // Resolve docker before inspecting: inspectContainer collapses a missing
35
+ // docker binary into { exists: false }, so deferring this check would
36
+ // surface the misleading "Container … not found" instead of the real
37
+ // "Docker is not installed" on a host without docker on PATH.
38
+ const cmd = dockerCmd(['exec', '-it', containerName, plannedShell], deps.resolveDocker)
39
+ if (cmd === null) {
40
+ return { ok: false, reason: 'Docker is not installed (docker not found on PATH).' }
41
+ }
42
+
33
43
  try {
34
44
  const state = await (deps.inspect ?? inspectContainer)(containerName)
35
45
  if (!state.exists) {
@@ -40,7 +50,7 @@ export async function shell(
40
50
  }
41
51
 
42
52
  const proc = spawn({
43
- cmd: ['docker', 'exec', '-it', containerName, plannedShell],
53
+ cmd,
44
54
  cwd,
45
55
  stdin: 'inherit',
46
56
  stdout: 'inherit',
@@ -1,5 +1,4 @@
1
- import { existsSync } from 'node:fs'
2
- import { join } from 'node:path'
1
+ import { resolveAgentGit } from '@/git/resolve-agent-git'
3
2
 
4
3
  import type { CommitOutcome, FixAttempt } from './types'
5
4
 
@@ -23,13 +22,15 @@ export async function commitAutoFixes(opts: CommitOptions): Promise<CommitOutcom
23
22
  return { kind: 'skipped', reason: 'auto-fixes reported no changed paths' }
24
23
  }
25
24
 
26
- if (!existsSync(join(opts.cwd, '.git'))) {
25
+ const repo = resolveAgentGit(opts.cwd)
26
+ if (!repo) {
27
27
  return { kind: 'skipped', reason: 'agent folder is not a git repo (.git missing)' }
28
28
  }
29
29
 
30
30
  const spawnGit = opts.spawnGit ?? defaultSpawnGit
31
+ const git = (args: string[]): Promise<GitResult> => spawnGit([...repo.gitArgs, ...args], opts.cwd)
31
32
 
32
- const filter = await filterCommittable(spawnGit, opts.cwd, requested)
33
+ const filter = await filterCommittable(git, requested)
33
34
  if (filter.kind === 'failed') return filter
34
35
  const pathsStaged = filter.paths
35
36
  if (pathsStaged.length === 0) {
@@ -39,18 +40,18 @@ export async function commitAutoFixes(opts: CommitOptions): Promise<CommitOutcom
39
40
  }
40
41
  }
41
42
 
42
- const add = await spawnGit(['add', '--', ...pathsStaged], opts.cwd)
43
+ const add = await git(['add', '--', ...pathsStaged])
43
44
  if (add.exitCode !== 0) {
44
45
  return { kind: 'failed', reason: `git add failed: ${add.stderr.trim() || `exit ${add.exitCode}`}` }
45
46
  }
46
47
 
47
48
  const message = buildCommitMessage(opts.attempts)
48
- const commit = await spawnGit(['commit', '-m', message, '--only', '--', ...pathsStaged], opts.cwd)
49
+ const commit = await git(['commit', '-m', message, '--only', '--', ...pathsStaged])
49
50
  if (commit.exitCode !== 0) {
50
51
  return { kind: 'failed', reason: `git commit failed: ${commit.stderr.trim() || `exit ${commit.exitCode}`}` }
51
52
  }
52
53
 
53
- const sha = await spawnGit(['rev-parse', 'HEAD'], opts.cwd)
54
+ const sha = await git(['rev-parse', 'HEAD'])
54
55
  const commitSha = sha.exitCode === 0 ? sha.stdout.trim() : ''
55
56
  return { kind: 'committed', commitSha, pathsStaged }
56
57
  }
@@ -68,13 +69,12 @@ export async function commitAutoFixes(opts: CommitOptions): Promise<CommitOutcom
68
69
  // Surface that as { kind: 'failed' } so the user sees the real cause instead
69
70
  // of a misleading 'all paths are gitignored' message.
70
71
  async function filterCommittable(
71
- spawnGit: SpawnGit,
72
- cwd: string,
72
+ spawnGit: (args: string[]) => Promise<GitResult>,
73
73
  paths: string[],
74
74
  ): Promise<{ kind: 'ok'; paths: string[] } | { kind: 'failed'; reason: string }> {
75
75
  const out: string[] = []
76
76
  for (const p of paths) {
77
- const status = await spawnGit(['status', '--porcelain', '--', p], cwd)
77
+ const status = await spawnGit(['status', '--porcelain', '--', p])
78
78
  if (status.exitCode !== 0) {
79
79
  return {
80
80
  kind: 'failed',
package/src/dreams/git.ts CHANGED
@@ -1,5 +1,7 @@
1
+ import { resolveAgentGit } from '@/git/resolve-agent-git'
2
+
1
3
  export type GitResult = { exitCode: number; stdout: string; stderr: string }
2
- export type SpawnGit = (args: string[], cwd: string) => Promise<GitResult>
4
+ export type SpawnGit = (args: readonly string[], cwd: string) => Promise<GitResult>
3
5
 
4
6
  export type RawCommit = {
5
7
  sha: string
@@ -8,16 +10,22 @@ export type RawCommit = {
8
10
  subject: string
9
11
  }
10
12
 
11
- export type ResolveRepoResult = { ok: true; root: string } | { ok: false; reason: 'not-a-repo' | 'git-failed' }
13
+ export type ResolveRepoResult =
14
+ | { ok: true; root: string; gitArgs: readonly string[] }
15
+ | { ok: false; reason: 'not-a-repo' | 'git-failed' }
12
16
 
13
17
  const FIELD_SEP = '\x1f'
14
18
  const RECORD_SEP = '\x1e'
15
19
 
16
20
  export async function resolveGitRepo(cwd: string, spawnGit: SpawnGit = defaultSpawnGit): Promise<ResolveRepoResult> {
17
- const res = await spawnGit(['rev-parse', '--show-toplevel'], cwd)
21
+ const repo = resolveAgentGit(cwd)
22
+ if (!repo) return { ok: false, reason: 'not-a-repo' }
23
+ if (repo.kind === 'gitstore') return { ok: true, root: cwd, gitArgs: repo.gitArgs }
24
+
25
+ const res = await spawnGit([...repo.gitArgs, 'rev-parse', '--show-toplevel'], cwd)
18
26
  if (res.exitCode === 0) {
19
27
  const root = res.stdout.trim()
20
- if (root.length > 0) return { ok: true, root }
28
+ if (root.length > 0) return { ok: true, root, gitArgs: repo.gitArgs }
21
29
  return { ok: false, reason: 'git-failed' }
22
30
  }
23
31
  if (/not a git repository/i.test(res.stderr)) return { ok: false, reason: 'not-a-repo' }
@@ -30,6 +38,7 @@ export async function readDreamCommitLog(
30
38
  root: string,
31
39
  opts: { limit?: number } = {},
32
40
  spawnGit: SpawnGit = defaultSpawnGit,
41
+ gitArgs: readonly string[] = [],
33
42
  ): Promise<RawCommit[]> {
34
43
  // --grep is only a cheap pre-filter: it matches ANY line of the commit
35
44
  // message, so a non-dream commit with a `dream: ...` body line slips
@@ -39,7 +48,7 @@ export async function readDreamCommitLog(
39
48
  // result below the requested count.
40
49
  const args = ['log', '--grep=^dream: ', `--format=%H${FIELD_SEP}%h${FIELD_SEP}%cI${FIELD_SEP}%s${RECORD_SEP}`]
41
50
 
42
- const res = await spawnGit(args, root)
51
+ const res = await spawnGit([...gitArgs, ...args], root)
43
52
  if (res.exitCode !== 0) return []
44
53
  const dreams = parseLogOutput(res.stdout).filter((c) => c.subject.startsWith(DREAM_SUBJECT_PREFIX))
45
54
  if (opts.limit !== undefined && opts.limit > 0) return dreams.slice(0, opts.limit)
@@ -62,10 +71,14 @@ export async function readDreamCommitShow(
62
71
  root: string,
63
72
  sha: string,
64
73
  spawnGit: SpawnGit = defaultSpawnGit,
74
+ gitArgs: readonly string[] = [],
65
75
  ): Promise<{ nameStatus: string; patch: string } | null> {
66
- const nameStatus = await spawnGit(['show', '--no-color', '--find-renames', '--format=', '--name-status', sha], root)
76
+ const nameStatus = await spawnGit(
77
+ [...gitArgs, 'show', '--no-color', '--find-renames', '--format=', '--name-status', sha],
78
+ root,
79
+ )
67
80
  if (nameStatus.exitCode !== 0) return null
68
- const patch = await spawnGit(['show', '--no-color', '--format=', '--unified=0', sha], root)
81
+ const patch = await spawnGit([...gitArgs, 'show', '--no-color', '--format=', '--unified=0', sha], root)
69
82
  if (patch.exitCode !== 0) return null
70
83
  return { nameStatus: nameStatus.stdout, patch: patch.stdout }
71
84
  }
@@ -39,7 +39,12 @@ export async function listDreams(
39
39
  ): Promise<DreamEntry[]> {
40
40
  const repo = await resolveGitRepo(agentDir, spawnGit)
41
41
  if (!repo.ok) return []
42
- const commits = await readDreamCommitLog(repo.root, opts.limit !== undefined ? { limit: opts.limit } : {}, spawnGit)
42
+ const commits = await readDreamCommitLog(
43
+ repo.root,
44
+ opts.limit !== undefined ? { limit: opts.limit } : {},
45
+ spawnGit,
46
+ repo.gitArgs,
47
+ )
43
48
  return commits.map((commit) => {
44
49
  const subject = parseDreamSubject(commit.subject)
45
50
  return {
@@ -58,7 +63,7 @@ export async function listDreams(
58
63
  export async function hydrateDream(agentDir: string, entry: DreamEntry, spawnGit?: SpawnGit): Promise<DreamEntry> {
59
64
  const repo = await resolveGitRepo(agentDir, spawnGit)
60
65
  if (!repo.ok) return entry
61
- const show = await readDreamCommitShow(repo.root, entry.sha, spawnGit)
66
+ const show = await readDreamCommitShow(repo.root, entry.sha, spawnGit, repo.gitArgs)
62
67
  if (show === null) return entry
63
68
  return { ...entry, detail: parseDreamDetail(show.nameStatus, show.patch) }
64
69
  }
@@ -80,7 +85,7 @@ export async function runDreams(opts: RunDreamsOptions): Promise<RunDreamsResult
80
85
  const entries = await listDreams(opts.agentDir, opts.limit !== undefined ? { limit: opts.limit } : {}, opts.spawnGit)
81
86
  const renderOpts: RenderOptions = { color: opts.color }
82
87
 
83
- if (opts.json) return runJson(opts, repo.root, entries)
88
+ if (opts.json) return runJson(opts, repo.root, repo.gitArgs, entries)
84
89
 
85
90
  if (entries.length === 0) {
86
91
  opts.stdout('No dreams yet. The dreaming subagent commits here after it consolidates memory.')
@@ -115,16 +120,26 @@ async function runInteractiveLoop(
115
120
  }
116
121
  }
117
122
 
118
- async function runJson(opts: RunDreamsOptions, root: string, entries: DreamEntry[]): Promise<RunDreamsResult> {
123
+ async function runJson(
124
+ opts: RunDreamsOptions,
125
+ root: string,
126
+ gitArgs: readonly string[],
127
+ entries: DreamEntry[],
128
+ ): Promise<RunDreamsResult> {
119
129
  for (const entry of entries) {
120
- const final = opts.details ? await hydrateEntryFromRoot(root, entry, opts.spawnGit) : entry
130
+ const final = opts.details ? await hydrateEntryFromRoot(root, gitArgs, entry, opts.spawnGit) : entry
121
131
  opts.stdout(JSON.stringify(toJsonShape(final)))
122
132
  }
123
133
  return { ok: true, exitCode: 0 }
124
134
  }
125
135
 
126
- async function hydrateEntryFromRoot(root: string, entry: DreamEntry, spawnGit?: SpawnGit): Promise<DreamEntry> {
127
- const show = await readDreamCommitShow(root, entry.sha, spawnGit)
136
+ async function hydrateEntryFromRoot(
137
+ root: string,
138
+ gitArgs: readonly string[],
139
+ entry: DreamEntry,
140
+ spawnGit?: SpawnGit,
141
+ ): Promise<DreamEntry> {
142
+ const show = await readDreamCommitShow(root, entry.sha, spawnGit, gitArgs)
128
143
  if (show === null) return entry
129
144
  return { ...entry, detail: parseDreamDetail(show.nameStatus, show.patch) }
130
145
  }