typeclaw 0.39.0 → 0.39.2

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 (43) 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 +112 -13
  19. package/src/cli/hostd.ts +40 -0
  20. package/src/compose/logs.ts +20 -6
  21. package/src/config/config.ts +7 -5
  22. package/src/container/logs.ts +19 -4
  23. package/src/container/shared.ts +222 -18
  24. package/src/container/shell.ts +12 -2
  25. package/src/container/start.ts +191 -30
  26. package/src/doctor/commit.ts +10 -10
  27. package/src/dreams/git.ts +20 -7
  28. package/src/dreams/index.ts +22 -7
  29. package/src/git/reconcile-ignored.ts +56 -27
  30. package/src/git/resolve-agent-git.ts +12 -0
  31. package/src/git/system-commit.ts +16 -10
  32. package/src/hostd/daemon.ts +16 -0
  33. package/src/hostd/webex-renewal-manager.ts +216 -0
  34. package/src/init/auto-upgrade.ts +38 -4
  35. package/src/init/cli-version.ts +30 -1
  36. package/src/init/dockerfile.ts +31 -9
  37. package/src/init/gitignore.ts +4 -2
  38. package/src/init/index.ts +47 -39
  39. package/src/init/windows-dev-link.ts +64 -0
  40. package/src/secrets/schema.ts +1 -0
  41. package/src/secrets/webex-renewal.ts +215 -0
  42. package/src/server/index.ts +25 -3
  43. 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
@@ -1163,6 +1179,10 @@ export type CreateChannelRouterOptions = {
1163
1179
  // resumes on the next boot; when absent (cold channel / native slash with no
1164
1180
  // session) it should just bounce the container with no handoff.
1165
1181
  onRestart?: (ctx?: RestartCommandContext) => Promise<string>
1182
+ // Test seam: override the sessions.json writer. Defaults to the disk-backed
1183
+ // saveChannelSessions (which swallows its own I/O errors). Tests inject a
1184
+ // throwing impl to exercise the persist-failure unwind in ensureLive.
1185
+ saveChannelSessions?: (agentDir: string, sessions: readonly ChannelSessionRecord[]) => Promise<void>
1166
1186
  }
1167
1187
 
1168
1188
  export type RestartCommandContext = {
@@ -1340,13 +1360,18 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1340
1360
  await loadOnce
1341
1361
  }
1342
1362
 
1363
+ const saveSessions = options.saveChannelSessions
1364
+ ? options.saveChannelSessions
1365
+ : (agentDir: string, sessions: readonly ChannelSessionRecord[]): Promise<void> =>
1366
+ saveChannelSessions(agentDir, sessions, logger)
1367
+
1343
1368
  const persist = async (): Promise<void> => {
1344
1369
  if (mappings === null || closing) return
1345
1370
  // Caller awaits `next` un-caught to observe write errors; the chain holds the
1346
1371
  // caught version so one rejection can't poison it or escape as unhandled.
1347
1372
  const next = persistChain.then(async () => {
1348
1373
  if (mappings === null) return
1349
- await saveChannelSessions(options.agentDir, mappings, logger)
1374
+ await saveSessions(options.agentDir, mappings)
1350
1375
  })
1351
1376
  persistChain = next.catch(() => {})
1352
1377
  await next
@@ -1592,10 +1617,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1592
1617
  logger.info(`[channels] ${keyId}: ensureLive begin (${phase})`)
1593
1618
  const participants = (resolvedRecord?.participants ?? []) as ChannelParticipant[]
1594
1619
  const membershipFetch = warmMembership(key)
1595
- const resolvedNames = await resolveChannelNames(key)
1596
- logger.info(`[channels] ${keyId}: ensureLive resolved-names`)
1597
- const membership = await membershipForPrompt(key, membershipFetch)
1598
- logger.info(`[channels] ${keyId}: ensureLive resolved-membership`)
1620
+ // Independent platform lookups — overlap so the chain pays max(), not sum().
1621
+ const [resolvedNames, membership] = await Promise.all([
1622
+ resolveChannelNames(key),
1623
+ membershipForPrompt(key, membershipFetch),
1624
+ ])
1625
+ logger.info(`[channels] ${keyId}: ensureLive resolved-names-and-membership`)
1599
1626
  // The session-creation origin is what the resource loader sees when it
1600
1627
  // renders the role/permissions block into the system prompt. It must
1601
1628
  // include the triggering author so author-scoped roles
@@ -1658,13 +1685,21 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1658
1685
  } else {
1659
1686
  mappings = [persistedRecord]
1660
1687
  }
1661
- await persist()
1688
+ // Kick off the mapping write now but don't block on it — the disk write is
1689
+ // independent of the synchronous `live` build below and the cold-start
1690
+ // network prefetch, so we overlap it. Every exit path below MUST settle
1691
+ // `persistPromise` (the immediate .catch is only an unhandled-rejection
1692
+ // guard; write errors are still surfaced by awaiting it later).
1693
+ const persistPromise = persist()
1694
+ void persistPromise.catch(() => {})
1662
1695
 
1663
1696
  const live: LiveSession = {
1664
1697
  key,
1665
1698
  keyId,
1666
1699
  session: created.session,
1667
1700
  turnThinkingDefault: created.session.thinkingLevel,
1701
+ lastQuestionSignal: null,
1702
+ pendingUserTurnSignal: null,
1668
1703
  sessionId: created.sessionId,
1669
1704
  dispose: created.dispose,
1670
1705
  hooks: created.hooks,
@@ -1722,6 +1757,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1722
1757
  skippedTurn: null,
1723
1758
  skipLockedSendTurn: null,
1724
1759
  disengagedTurn: null,
1760
+ emptyTurnFallbackTurn: null,
1725
1761
  pendingQuoteCandidate: null,
1726
1762
  recentEngagedPeerBotTurns: [],
1727
1763
  consecutiveEngagedPeerBotTurns: 0,
@@ -1772,16 +1808,38 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1772
1808
  `[channels] ${keyId}: discarding session created across a teardown (gen ${generation} → ${liveGeneration})`,
1773
1809
  )
1774
1810
  await tearDownLive(live)
1811
+ // Settle the in-flight mapping write before bailing — preserves the
1812
+ // pre-overlap contract that a persist failure fails ensureLive.
1813
+ await persistPromise
1775
1814
  throw new StaleLiveSessionError(keyId)
1776
1815
  }
1777
- liveSessions.set(keyId, live)
1778
-
1779
1816
  if (isColdStart) {
1817
+ // Install before the slow prefetch so a concurrent teardown/shutdown can
1818
+ // see and dispose this session during the network fetch.
1819
+ liveSessions.set(keyId, live)
1780
1820
  const adapterConfig = options.configForAdapter(key.adapter)
1781
- if (adapterConfig) {
1782
- await prefetchChannelContext(live, adapterConfig, triggeringMessageId)
1783
- logger.info(`[channels] ${keyId}: ensureLive prefetched-context`)
1821
+ // Overlap the disk mapping-write with the network history prefetch —
1822
+ // they are independent. allSettled lets a persist failure take priority
1823
+ // (and unwind the install) even if prefetch also rejects.
1824
+ const prefetchPromise = adapterConfig
1825
+ ? prefetchChannelContext(live, adapterConfig, triggeringMessageId)
1826
+ : Promise.resolve()
1827
+ const [persistResult, prefetchResult] = await Promise.allSettled([persistPromise, prefetchPromise])
1828
+ if (persistResult.status === 'rejected') {
1829
+ await unwindInstalledLive(keyId, live)
1830
+ throw persistResult.reason
1784
1831
  }
1832
+ if (prefetchResult.status === 'rejected') {
1833
+ await unwindInstalledLive(keyId, live)
1834
+ throw prefetchResult.reason
1835
+ }
1836
+ if (adapterConfig) logger.info(`[channels] ${keyId}: ensureLive prefetched-context`)
1837
+ } else {
1838
+ // Rehydrate has no prefetch to overlap, so settle the mapping write
1839
+ // before installing — a failed persist must fail ensureLive without
1840
+ // leaving a warm session behind for later inbounds to reuse.
1841
+ await persistPromise
1842
+ liveSessions.set(keyId, live)
1785
1843
  }
1786
1844
 
1787
1845
  // Snapshot the rendered base context size now, after prefetch and before
@@ -2398,24 +2456,57 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2398
2456
  live.successfulSendsAtTurnStart = successfulSendsBeforePrompt
2399
2457
  live.skipLockedSendTurn = null
2400
2458
  live.disengagedTurn = null
2459
+ live.emptyTurnFallbackTurn = null
2401
2460
  live.policyDeniedToolSendsThisTurn.clear()
2402
2461
  resetReviewTurn(live.sessionId)
2403
2462
  const isRealUserTurn = batch.length > 0
2404
2463
  const retrievalQuery = composeRetrievalQuery(batch)
2464
+ // A fresh real-user batch opens a new logical turn. Capture its question
2465
+ // shape as PENDING (committed only once the turn completes below). The
2466
+ // drain is serial and retries are reminder-only, so a prior pending must
2467
+ // already be resolved; a leftover here means a logical turn never
2468
+ // completed — fail closed by discarding it rather than misattributing.
2469
+ if (isRealUserTurn) {
2470
+ live.pendingUserTurnSignal = { signal: getQuestionSignal(retrievalQuery) }
2471
+ }
2405
2472
  const retrievalContext = await fireSessionTurnStart(live, retrievalQuery)
2406
2473
  const promptText = retrievalContext.results.length > 0 ? `${text}\n\n${retrievalContext.results}` : text
2407
- applyTurnThinkingLevel(live.session, retrievalQuery, live.turnThinkingDefault)
2474
+ applyTurnThinkingLevel(live.session, retrievalQuery, live.turnThinkingDefault, live.lastQuestionSignal)
2408
2475
  live.promptInFlight = true
2409
2476
  try {
2410
2477
  await live.session.prompt(promptText)
2411
2478
  await validateChannelTurn(live, successfulSendsBeforePrompt)
2412
2479
  live.consecutiveAborts = 0
2480
+ // Resolve the pending logical-turn signal on a binary rule: ONLY a
2481
+ // usable assistant reply (real model prose the user saw) seeds the next
2482
+ // turn's escalation. Every other terminal outcome CLEARS lastQuestionSignal
2483
+ // so an older question can't leak across the failed/silent turn:
2484
+ // - retry queued (`length`/`aborted`, budget left): turn still in
2485
+ // flight → leave both for the reminder-only iteration that ends it.
2486
+ // - usable reply → commit the pending signal.
2487
+ // - provider error / empty-turn fallback / NO_REPLY / skip (no usable
2488
+ // reply) → clear BOTH (pending and lastQuestionSignal).
2489
+ // A fallback sends via source:'system', which also bumps
2490
+ // successfulChannelSends, so it must be excluded explicitly.
2491
+ const retryQueuedThisTurn = live.emptyTurnRetries > emptyTurnRetriesBeforePrompt
2492
+ const providerErrorThisTurn = assistantLeafStopReason(live.session) === 'error'
2493
+ const fallbackPostedThisTurn = live.emptyTurnFallbackTurn === live.turnSeq
2494
+ const sentReplyThisTurn = live.successfulChannelSends > successfulSendsBeforePrompt
2495
+ const usableReplyThisTurn = sentReplyThisTurn && !fallbackPostedThisTurn && !providerErrorThisTurn
2496
+ if (live.pendingUserTurnSignal !== null && !retryQueuedThisTurn) {
2497
+ live.lastQuestionSignal = usableReplyThisTurn ? live.pendingUserTurnSignal.signal : null
2498
+ live.pendingUserTurnSignal = null
2499
+ }
2413
2500
  logger.info(`[channels] ${live.keyId} prompted elapsed_ms=${now() - promptStart}`)
2414
2501
  } catch (err) {
2415
2502
  logger.error(`[channels] ${live.keyId}: prompt threw: ${describe(err)}`)
2416
2503
  live.consecutiveSends.clear()
2417
2504
  live.lastSentText.clear()
2418
2505
  live.lastSendLeafId = null
2506
+ // A thrown prompt is a non-usable terminal outcome: drop pending AND
2507
+ // clear the prior signal so an older question can't leak across it.
2508
+ live.pendingUserTurnSignal = null
2509
+ live.lastQuestionSignal = null
2419
2510
  } finally {
2420
2511
  live.promptInFlight = false
2421
2512
  const sentReplyThisTurn = live.successfulChannelSends > successfulSendsBeforePrompt
@@ -3533,6 +3624,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3533
3624
  }
3534
3625
  const postEmptyTurnFallback = async (cause: string): Promise<void> => {
3535
3626
  logger.warn(`[channels] ${live.keyId} empty_turn_fallback cause=${cause}`)
3627
+ live.emptyTurnFallbackTurn = live.turnSeq
3536
3628
  const result = await send(
3537
3629
  {
3538
3630
  adapter: live.key.adapter,
@@ -3998,6 +4090,13 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3998
4090
  }
3999
4091
  }
4000
4092
 
4093
+ // Roll back an install when a post-install step (persist/prefetch) fails, so a
4094
+ // rejected ensureLive never leaves a warm session behind for later inbounds.
4095
+ const unwindInstalledLive = async (keyId: string, live: LiveSession): Promise<void> => {
4096
+ if (liveSessions.get(keyId) === live) liveSessions.delete(keyId)
4097
+ if (!live.destroyed) await tearDownLive(live)
4098
+ }
4099
+
4001
4100
  const runIdleGc = async (): Promise<void> => {
4002
4101
  const t = now()
4003
4102
  const victims: LiveSession[] = []
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':
@@ -1,7 +1,7 @@
1
1
  import { buildDockerLogsCmd, containerExists } from '@/container'
2
2
  import { supportsColor } from '@/container/log-colors'
3
3
  import { makeLogTimestampReformatter, type TimestampReformatter } from '@/container/log-timestamps'
4
- import { getBun } from '@/container/shared'
4
+ import { getBun, resolveDockerBinary } from '@/container/shared'
5
5
 
6
6
  import { discoverAgents, type AgentEntry } from './discover'
7
7
 
@@ -74,6 +74,17 @@ export async function composeLogs({
74
74
  }: ComposeLogsOptions): Promise<ComposeLogsResult> {
75
75
  const agents = discoverAgents(rootCwd)
76
76
 
77
+ // Resolve docker BEFORE probing containers: containerExists collapses a
78
+ // missing docker binary into `false`, so every agent would be classified
79
+ // "container not running" and the empty-attached early return would exit 0 —
80
+ // masking the real "docker not on PATH" cause (the stale-Windows-PATH case
81
+ // #1007 covers for start/init). Resolving first surfaces it correctly.
82
+ const dockerBinary = resolveDockerBinary()
83
+ if (dockerBinary === null) {
84
+ err.write('compose: docker not found on PATH\n')
85
+ return { agents, attached: [], missing: agents, exitCode: 1 }
86
+ }
87
+
77
88
  const liveness = await Promise.all(
78
89
  agents.map(async (a) => ({ agent: a, exists: await containerExists(a.containerName) })),
79
90
  )
@@ -95,11 +106,14 @@ export async function composeLogs({
95
106
  const useColor = supportsColor(out)
96
107
 
97
108
  const procs = attached.map((agent) => {
98
- const cmd = buildDockerLogsCmd({
99
- containerName: agent.containerName,
100
- follow,
101
- ...(tail !== undefined ? { tail } : {}),
102
- })
109
+ const cmd = buildDockerLogsCmd(
110
+ {
111
+ containerName: agent.containerName,
112
+ follow,
113
+ ...(tail !== undefined ? { tail } : {}),
114
+ },
115
+ dockerBinary,
116
+ )
103
117
  const proc = bun.spawn({ cmd, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' })
104
118
  return { agent, proc }
105
119
  })
@@ -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,6 +1,6 @@
1
1
  import { supportsColor } from './log-colors'
2
2
  import { makeLogTimestampReformatter, type TimestampReformatter } from './log-timestamps'
3
- import { containerExists, containerNameFromCwd, getBun } from './shared'
3
+ import { containerExists, containerNameFromCwd, getBun, resolveDockerBinary } from './shared'
4
4
 
5
5
  export type LogsPlan = {
6
6
  containerName: string
@@ -39,6 +39,17 @@ export async function logs({
39
39
 
40
40
  const plan = planLogs(cwd, { follow, tail })
41
41
 
42
+ // Resolve docker before inspecting: containerExists collapses a missing
43
+ // docker binary into `false`, so deferring this would surface the misleading
44
+ // "Container … not found" instead of the real "Docker is not installed" on a
45
+ // host where docker isn't on PATH (cf. shell.ts). resolveDockerBinary also
46
+ // recovers the stale-Windows-PATH case where Bun.which misses (#1007).
47
+ const dockerBinary = resolveDockerBinary()
48
+ if (dockerBinary === null) {
49
+ return { ok: false, reason: 'Docker is not installed (docker not found on PATH).' }
50
+ }
51
+ const cmd = buildDockerLogsCmd(plan, dockerBinary)
52
+
42
53
  try {
43
54
  if (!(await containerExists(plan.containerName))) {
44
55
  return { ok: false, reason: `Container ${plan.containerName} not found. Run \`typeclaw start\` first.` }
@@ -47,7 +58,7 @@ export async function logs({
47
58
  // stdin:'ignore' — `docker logs` never reads stdin, and letting the child
48
59
  // hold the TTY breaks the viewer's raw-mode keypress listener (esc/q/ctrl-c
49
60
  // stop reaching it, freezing the logs view with no way out).
50
- const proc = bun.spawn({ cmd: buildDockerLogsCmd(plan), cwd, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' })
61
+ const proc = bun.spawn({ cmd, cwd, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' })
51
62
 
52
63
  // `docker logs -f` never exits on its own; aborting the signal must kill it
53
64
  // so the pumps' stream readers end. Escalate to SIGKILL if SIGTERM is
@@ -112,8 +123,12 @@ export function parseTailValue(raw: string): { ok: true; value: string } | { ok:
112
123
  }
113
124
 
114
125
  // Exported so `compose/logs.ts` builds the exact same `docker logs` argv shape.
115
- export function buildDockerLogsCmd(plan: LogsPlan): string[] {
116
- const cmd = ['docker', 'logs', '--timestamps']
126
+ // Takes the already-resolved docker binary path (from resolveDockerBinary) as
127
+ // the argv head so a stale Windows PATH still spawns — passing a bare 'docker'
128
+ // throws ENOENT on the #1007 case. Callers resolve the binary and handle the
129
+ // missing-docker error before getting here.
130
+ export function buildDockerLogsCmd(plan: LogsPlan, dockerBinary: string): string[] {
131
+ const cmd = [dockerBinary, 'logs', '--timestamps']
117
132
  if (plan.tail !== undefined) cmd.push('--tail', plan.tail)
118
133
  if (plan.follow) cmd.push('-f')
119
134
  cmd.push(plan.containerName)