typeclaw 0.46.0 → 0.46.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 (75) hide show
  1. package/README.md +1 -1
  2. package/package.json +2 -2
  3. package/src/agent/multimodal/looker.ts +11 -1
  4. package/src/agent/network/safe-http.ts +17 -8
  5. package/src/agent/plugin-tools.ts +1 -3
  6. package/src/agent/tool-file-safety.ts +414 -145
  7. package/src/agent/tools/webfetch/fetch.ts +22 -2
  8. package/src/agent/tools/webfetch/strategies/jq.ts +1 -2
  9. package/src/agent/tools/webfetch/strategies/readability.ts +39 -16
  10. package/src/agent/tools/webfetch/strategies/selector.ts +4 -2
  11. package/src/agent/tools/webfetch/strategies/snapshot.ts +3 -2
  12. package/src/agent/tools/webfetch/tool.ts +3 -3
  13. package/src/agent/tools-without-local-file-operands.ts +9 -6
  14. package/src/bundled-plugins/backup/README.md +23 -10
  15. package/src/bundled-plugins/backup/git-auth.ts +6 -4
  16. package/src/bundled-plugins/backup/index.ts +104 -47
  17. package/src/bundled-plugins/backup/runner.ts +102 -5
  18. package/src/bundled-plugins/github-cli-auth/git-askpass.ts +74 -26
  19. package/src/bundled-plugins/github-cli-auth/git-command.ts +224 -36
  20. package/src/bundled-plugins/github-cli-auth/graphql-auth-nudge.ts +9 -9
  21. package/src/bundled-plugins/github-cli-auth/index.ts +110 -31
  22. package/src/bundled-plugins/github-cli-auth/token-class.ts +4 -6
  23. package/src/bundled-plugins/memory/README.md +9 -0
  24. package/src/bundled-plugins/memory/vector/embed-threads.ts +36 -0
  25. package/src/bundled-plugins/memory/vector/embedder.ts +19 -1
  26. package/src/bundled-plugins/memory/vector/hybrid.ts +10 -2
  27. package/src/bundled-plugins/memory/vector/store.ts +21 -9
  28. package/src/bundled-plugins/researcher/write-report.ts +3 -3
  29. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +8 -3
  30. package/src/bundled-plugins/security/policies/private-surface-read.ts +616 -50
  31. package/src/bundled-plugins/security/policies/ssrf.ts +119 -34
  32. package/src/channels/adapters/github/inbound.ts +11 -0
  33. package/src/channels/adapters/github/index.ts +48 -54
  34. package/src/channels/adapters/github/reconcile-cooldown-store.ts +178 -0
  35. package/src/channels/adapters/github/reconcile-open-prs.ts +31 -0
  36. package/src/channels/adapters/slack-bot-edit.ts +85 -20
  37. package/src/channels/adapters/slack-bot.ts +7 -2
  38. package/src/channels/adapters/slack-format.ts +245 -0
  39. package/src/channels/github-token-bridge.ts +2 -3
  40. package/src/cli/inspect.ts +16 -0
  41. package/src/container/docker-app.ts +42 -13
  42. package/src/container/shared.ts +19 -6
  43. package/src/container/start.ts +13 -0
  44. package/src/cron/bridge.ts +9 -2
  45. package/src/doctor/checks.ts +5 -2
  46. package/src/git/bound-gc-config.ts +82 -0
  47. package/src/hostd/spawn.ts +133 -47
  48. package/src/init/checkpoint.ts +4 -4
  49. package/src/init/dockerfile.ts +100 -88
  50. package/src/init/gitignore.ts +5 -6
  51. package/src/init/run-bun-install.ts +16 -2
  52. package/src/init/validate-api-key.ts +1 -0
  53. package/src/inspect/item-list.ts +12 -6
  54. package/src/inspect/replay.ts +21 -9
  55. package/src/inspect/session-list.ts +71 -33
  56. package/src/mcp/tools.ts +1 -0
  57. package/src/network/internal-destinations.ts +267 -0
  58. package/src/permissions/permissions.ts +93 -2
  59. package/src/plugin/types.ts +3 -2
  60. package/src/role-claim/code.ts +9 -5
  61. package/src/run/index.ts +45 -36
  62. package/src/sandbox/canonical-secrets.ts +6 -0
  63. package/src/sandbox/env-exposure.ts +18 -15
  64. package/src/sandbox/index.ts +1 -0
  65. package/src/sandbox/policy.ts +5 -3
  66. package/src/sandbox/privileged-runtime.ts +1 -0
  67. package/src/sandbox/symlinks.ts +1 -1
  68. package/src/secrets/export-claude-credentials-file.ts +13 -22
  69. package/src/secrets/export-codex-auth-file.ts +12 -28
  70. package/src/skills/typeclaw-config/SKILL.md +22 -6
  71. package/src/skills/typeclaw-permissions/SKILL.md +22 -9
  72. package/src/skills/typeclaw-plugins/SKILL.md +37 -0
  73. package/src/usage/scan.ts +11 -2
  74. package/typeclaw.schema.json +5 -0
  75. package/src/git/secret-history.ts +0 -371
@@ -3,6 +3,7 @@ import type { InboundMessage } from '@/channels/types'
3
3
 
4
4
  import type { GithubAuthContext } from './auth'
5
5
  import { GITHUB_API_BASE, githubJsonHeaders } from './auth-pat'
6
+ import { DEFAULT_RECONCILE_COOLDOWN_MS, type ReconcileCooldownStore } from './reconcile-cooldown-store'
6
7
  import type { TeamMembershipChecker } from './team-membership'
7
8
 
8
9
  // Catches up on review work that a live webhook delivery missed. The github
@@ -32,6 +33,12 @@ export type ReconcileOpenPrsOptions = {
32
33
  // tests that don't exercise team requests; treated as "not a member".
33
34
  isBotInTeam?: TeamMembershipChecker
34
35
  fetchImpl?: typeof fetch
36
+ // When provided, a PR that still needs review is replayed at most once per
37
+ // `cooldownMs`, keyed durably by `repo#prId` so restarts don't re-trigger it.
38
+ // Omitted in tests that assert the raw replay decision.
39
+ cooldownStore?: ReconcileCooldownStore
40
+ cooldownMs?: number
41
+ now?: () => number
35
42
  }
36
43
 
37
44
  export type ReconcileOutcome = { repo: string; scanned: number; replayed: number } | { repo: string; error: string }
@@ -79,13 +86,37 @@ async function reconcileRepo(
79
86
  const token = await options.token({ repoSlug: repo })
80
87
  const prs = await fetchOpenPrs(fetchImpl, token, target)
81
88
 
89
+ const cooldownStore = options.cooldownStore
90
+ const cooldownMs = options.cooldownMs ?? DEFAULT_RECONCILE_COOLDOWN_MS
91
+ const now = options.now ?? Date.now
92
+
82
93
  let replayed = 0
83
94
  for (const pr of prs) {
84
95
  const needs = await prNeedsReview({ pr, options, target, token, selfLogin, decoyLogin, fetchImpl })
85
96
  if (!needs) continue
97
+ if (cooldownStore !== undefined) {
98
+ if (cooldownStore.isCoolingDown(repo, pr.id, now(), cooldownMs)) continue
99
+ try {
100
+ // Persist the marker before routing: if the write fails the marker is
101
+ // rolled back and this throws, so we skip the route rather than replay a
102
+ // PR with no durable record (a restart would otherwise replay it again).
103
+ await cooldownStore.markReplayed(repo, pr.id, now())
104
+ } catch (err) {
105
+ options.logger.warn(
106
+ `[github] reconcile ${repo}: skipping PR #${pr.number} replay, cooldown persist failed: ${
107
+ err instanceof Error ? err.message : String(err)
108
+ }`,
109
+ )
110
+ continue
111
+ }
112
+ }
86
113
  options.route(buildSyntheticInbound(pr, target))
87
114
  replayed += 1
88
115
  }
116
+
117
+ if (cooldownStore !== undefined) {
118
+ await cooldownStore.prune(repo, new Set(prs.map((pr) => pr.id)), now())
119
+ }
89
120
  return { repo, scanned: prs.length, replayed }
90
121
  }
91
122
 
@@ -1,30 +1,92 @@
1
- import type { SlackBotClient } from 'agent-messenger/slackbot'
2
-
3
1
  import type { EditMessageCallback, EditMessageResult } from '@/channels/types'
4
2
 
3
+ import { describeError } from './describe-error'
4
+
5
+ const SLACK_API_BASE = 'https://slack.com/api'
6
+
7
+ // Mirrors the agent-messenger SlackBotClient.withRetry budget (3 retries on
8
+ // `ratelimited`), which this direct chat.update call replaces. Without it, a
9
+ // transient 429 during a burst would surface as a hard edit failure.
10
+ const MAX_RATE_LIMIT_RETRIES = 3
11
+ const DEFAULT_RETRY_AFTER_SECONDS = 1
12
+
13
+ type EditErrorCode = NonNullable<(EditMessageResult & { ok: false })['code']>
14
+
15
+ // The agent emits GitHub-Flavored Markdown. Slack's `chat.update` accepts a
16
+ // native `markdown_text` field that renders GFM correctly (bold `**` -> `*`,
17
+ // headings, tables), so edits reuse Slack's own renderer with no lossy
18
+ // hand-conversion — mirroring the `markdown` block used on the post path.
19
+ // `markdown_text` must not be combined with `text`/`blocks` or Slack returns
20
+ // `markdown_text_conflict`. The `agent-messenger` SDK's updateMessage only
21
+ // forwards `text`, so we call chat.update directly with the adapter token —
22
+ // and re-implement the SDK's rate-limit retry here (see MAX_RATE_LIMIT_RETRIES).
5
23
  export function createSlackEditMessageCallback(deps: {
6
- client: Pick<SlackBotClient, 'updateMessage'>
24
+ token: string
25
+ fetchImpl?: typeof fetch
26
+ sleep?: (ms: number) => Promise<void>
7
27
  }): EditMessageCallback {
28
+ const fetchFn = deps.fetchImpl ?? fetch
29
+ const sleep = deps.sleep ?? ((ms) => new Promise<void>((resolve) => setTimeout(resolve, ms)))
8
30
  return async (req): Promise<EditMessageResult> => {
9
31
  if (req.adapter !== 'slack-bot') {
10
32
  return { ok: false, error: `unknown adapter: ${req.adapter}`, code: 'not-supported' }
11
33
  }
12
- try {
13
- await deps.client.updateMessage(req.chat, req.messageId, req.text)
14
- } catch (err) {
15
- const code = slackErrorCode(err)
16
- return { ok: false, error: withScopeHint(code, describe(err)), code: classifyEditError(code) }
34
+ const body = new URLSearchParams({
35
+ channel: req.chat,
36
+ ts: req.messageId,
37
+ markdown_text: req.text,
38
+ }).toString()
39
+
40
+ for (let attempt = 0; attempt <= MAX_RATE_LIMIT_RETRIES; attempt++) {
41
+ let response: Response
42
+ try {
43
+ response = await fetchFn(`${SLACK_API_BASE}/chat.update`, {
44
+ method: 'POST',
45
+ headers: {
46
+ Authorization: `Bearer ${deps.token}`,
47
+ 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
48
+ },
49
+ body,
50
+ })
51
+ } catch (err) {
52
+ // Network throw is transient, not a missing target — surface as
53
+ // adapter-unavailable so the caller can distinguish it from a 404.
54
+ return { ok: false, error: describeError(err), code: 'adapter-unavailable' }
55
+ }
56
+
57
+ const raw = (await response.json().catch(() => ({}))) as { ok?: boolean; error?: string }
58
+ if (raw.ok === true) return { ok: true }
59
+ const code = raw.error ?? null
60
+
61
+ // Slack signals throttling with HTTP 429 (+ Retry-After header) and/or a
62
+ // `ratelimited` body error. Retry within budget honoring Retry-After;
63
+ // once exhausted, surface as transient (adapter-unavailable), never 404.
64
+ if (response.status === 429 || code === 'ratelimited') {
65
+ if (attempt < MAX_RATE_LIMIT_RETRIES) {
66
+ await sleep(retryAfterMs(response, attempt))
67
+ continue
68
+ }
69
+ return {
70
+ ok: false,
71
+ error: `Slack rate-limited chat.update after ${MAX_RATE_LIMIT_RETRIES} retries (ratelimited)`,
72
+ code: 'adapter-unavailable',
73
+ }
74
+ }
75
+
76
+ return { ok: false, error: withScopeHint(code, code ?? 'unknown slack error'), code: classifyEditError(code) }
17
77
  }
18
- return { ok: true }
78
+ // Unreachable: the loop returns on every path, but TS needs a terminal.
79
+ return { ok: false, error: 'unreachable', code: 'adapter-unavailable' }
19
80
  }
20
81
  }
21
82
 
22
- function slackErrorCode(err: unknown): string | null {
23
- if (typeof err === 'object' && err !== null && 'code' in err) {
24
- const code = (err as { code: unknown }).code
25
- if (typeof code === 'string') return code
26
- }
27
- return null
83
+ // Retry-After is in seconds per Slack's docs; fall back to a 1s base and grow
84
+ // it linearly per attempt (matching the SDK's `retryAfter * (attempt+1)`).
85
+ function retryAfterMs(response: Response, attempt: number): number {
86
+ const header = response.headers.get('retry-after')
87
+ const seconds = header !== null && header !== '' ? Number.parseInt(header, 10) : DEFAULT_RETRY_AFTER_SECONDS
88
+ const base = Number.isFinite(seconds) && seconds > 0 ? seconds : DEFAULT_RETRY_AFTER_SECONDS
89
+ return base * 1000 * (attempt + 1)
28
90
  }
29
91
 
30
92
  // `chat:write` is the scope the bot token needs to edit its own messages;
@@ -35,7 +97,7 @@ function withScopeHint(code: string | null, error: string): string {
35
97
  return `${error} (Slack bot token needs the \`chat:write\` scope; reinstall/reauthorize the app with that scope.)`
36
98
  }
37
99
 
38
- function classifyEditError(code: string | null): NonNullable<(EditMessageResult & { ok: false })['code']> {
100
+ function classifyEditError(code: string | null): EditErrorCode {
39
101
  switch (code) {
40
102
  case 'message_not_found':
41
103
  case 'channel_not_found':
@@ -48,11 +110,14 @@ function classifyEditError(code: string | null): NonNullable<(EditMessageResult
48
110
  case 'not_authed':
49
111
  case 'invalid_auth':
50
112
  return 'permission-denied'
113
+ // Transient Slack-side failures the agent should treat as retryable, not
114
+ // as a missing/forbidden target.
115
+ case 'ratelimited':
116
+ case 'service_unavailable':
117
+ case 'fatal_error':
118
+ case 'internal_error':
119
+ return 'adapter-unavailable'
51
120
  default:
52
121
  return 'not-found'
53
122
  }
54
123
  }
55
-
56
- function describe(err: unknown): string {
57
- return err instanceof Error ? err.message : String(err)
58
- }
@@ -67,6 +67,7 @@ import {
67
67
  type ThreadCommandInput,
68
68
  } from './slack-bot-slash-commands'
69
69
  import { slackTsToMillis } from './slack-bot-time'
70
+ import { toSlackMrkdwn } from './slack-format'
70
71
 
71
72
  // One slash command per logical agent gesture. Mirrors the discord-bot
72
73
  // SLASH_COMMANDS constant so the cross-platform set stays consistent — when
@@ -1027,7 +1028,11 @@ export function createOutboundCallback(deps: {
1027
1028
  const isFirst = index === 0
1028
1029
  const uploadOptions: { thread_ts?: string; initial_comment?: string } = {}
1029
1030
  if (threadTs !== undefined) uploadOptions.thread_ts = threadTs
1030
- if (isFirst && text !== '') uploadOptions.initial_comment = text
1031
+ // A file caption cannot carry a `markdown` block (files.uploadV2 has no
1032
+ // `blocks` param), so it is parsed as Slack mrkdwn. Convert the agent's
1033
+ // GFM (`**bold**`) to mrkdwn (`*bold*`) here — the text-only path above
1034
+ // relies on the native markdown block and needs no conversion.
1035
+ if (isFirst && text !== '') uploadOptions.initial_comment = toSlackMrkdwn(text)
1031
1036
  try {
1032
1037
  const file = await client.uploadFile(msg.chat, buffer, filename, uploadOptions)
1033
1038
  logger.info(`[slack-bot] uploaded id=${file.id} filename=${file.name} size=${file.size} ${tag}`)
@@ -1199,7 +1204,7 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
1199
1204
 
1200
1205
  const reactionCallback = createSlackReactionCallback({ client })
1201
1206
  const removeReactionCallback = createSlackRemoveReactionCallback({ client })
1202
- const editMessageCallback = createSlackEditMessageCallback({ client })
1207
+ const editMessageCallback = createSlackEditMessageCallback({ token: options.token, fetchImpl })
1203
1208
 
1204
1209
  const dedupe = createSlackDedupe()
1205
1210
 
@@ -0,0 +1,245 @@
1
+ // Convert the model's common-Markdown (GFM) output to Slack mrkdwn.
2
+ //
3
+ // Why this exists: the agent writes GitHub-Flavored Markdown the way a
4
+ // human types it (`**bold**`, `## heading`, `[text](url)`, tables). For a
5
+ // normal chat post the slack-bot adapter wraps that GFM in a Slack
6
+ // `markdown` block and Slack renders it natively — so no conversion is
7
+ // needed there. But two outbound fields cannot carry a `markdown` block:
8
+ // a file upload's `initial_comment` (files.uploadV2 has no `blocks`
9
+ // param). That field is parsed as Slack *mrkdwn*, where bold is a SINGLE
10
+ // `*`, so raw GFM `**bold**` renders as literal double asterisks. This
11
+ // converter bridges GFM -> mrkdwn for exactly those constrained fields.
12
+ //
13
+ // Slack mrkdwn is forgiving (unlike Telegram MarkdownV2, there is no
14
+ // escaping that can crash the parser), so this is a best-effort semantic
15
+ // translation, not a safety escape. Constructs mrkdwn cannot represent
16
+ // (headings, tables) degrade to the closest readable form.
17
+ //
18
+ // Slack mrkdwn spec (https://docs.slack.dev/messaging/formatting-message-text):
19
+ // - bold: *text*
20
+ // - italic: _text_
21
+ // - strike: ~text~
22
+ // - link: <url|label>
23
+ // - code: `code`, ```block```
24
+ // - quote: > line
25
+ // No native heading or table syntax exists.
26
+
27
+ export function toSlackMrkdwn(input: string): string {
28
+ if (input === '') return ''
29
+ const lines = input.split('\n')
30
+ const out: string[] = []
31
+ let i = 0
32
+ while (i < lines.length) {
33
+ const line = lines[i]!
34
+
35
+ if (isFenceOpen(line)) {
36
+ // Emit the fence and its body verbatim — a `*` inside a code block is
37
+ // literal, never italic. Scan to the closing fence (or EOF).
38
+ out.push(line)
39
+ i++
40
+ while (i < lines.length && !isFenceClose(lines[i]!)) {
41
+ out.push(lines[i]!)
42
+ i++
43
+ }
44
+ if (i < lines.length) {
45
+ out.push(lines[i]!)
46
+ i++
47
+ }
48
+ continue
49
+ }
50
+
51
+ if (isTableSeparatorRow(line) && out.length > 0 && isTableRow(lines[i - 1])) {
52
+ // GFM alignment row (`| --- | :--: |`) has no mrkdwn equivalent; drop
53
+ // it. The header row above and the data rows below stay as plain
54
+ // pipe-separated text, which reads fine in monospace-free mrkdwn.
55
+ i++
56
+ continue
57
+ }
58
+
59
+ out.push(renderLine(line))
60
+ i++
61
+ }
62
+ return out.join('\n')
63
+ }
64
+
65
+ function isFenceOpen(line: string): boolean {
66
+ return /^\s*```/.test(line)
67
+ }
68
+
69
+ function isFenceClose(line: string): boolean {
70
+ return /^\s*```\s*$/.test(line)
71
+ }
72
+
73
+ function isTableRow(line: string | undefined): boolean {
74
+ if (line === undefined) return false
75
+ return /^\s*\|.*\|\s*$/.test(line)
76
+ }
77
+
78
+ function isTableSeparatorRow(line: string): boolean {
79
+ return /^\s*\|(\s*:?-+:?\s*\|)+\s*$/.test(line)
80
+ }
81
+
82
+ // A heading line (`#`..`######` then space) has no mrkdwn equivalent, so
83
+ // render its inline-converted text as a bold line. A `#` that is not at the
84
+ // line start (e.g. `issue #42`) is not a heading and falls through. Inner
85
+ // bold is flattened to plain (`flattenBold`) because mrkdwn has no
86
+ // bold-inside-bold — the whole heading line is already bold, so a nested
87
+ // `*..*` would just emit a stray unbalanced `*`. Flattening happens INSIDE
88
+ // the tokenizer so code spans stay protected: a global post-pass regex
89
+ // would corrupt a `*` that lives inside a heading's inline code.
90
+ const HEADING = /^(#{1,6})\s+(.*)$/
91
+
92
+ function renderLine(line: string): string {
93
+ const heading = HEADING.exec(line)
94
+ if (heading !== null) {
95
+ const body = renderInline(heading[2]!, { flattenBold: true })
96
+ return body === '' ? '' : `*${body}*`
97
+ }
98
+ return renderInline(line)
99
+ }
100
+
101
+ type InlineOptions = { flattenBold: boolean }
102
+
103
+ // Inline tokenizer. Recognizes, in priority order:
104
+ // 1. inline code: `code`
105
+ // 2. link: [label](url) -> <url|label>
106
+ // 3. bold: **text** / __text__ -> *text* (or plain when flattenBold)
107
+ // 4. strike: ~~text~~ -> ~text~
108
+ // 5. italic: *text* / _text_ -> _text_
109
+ //
110
+ // Italic is last so `**` is consumed as bold, not two italics. Everything
111
+ // unrecognized is emitted verbatim — Slack mrkdwn needs no escaping.
112
+ function renderInline(text: string, options: InlineOptions = { flattenBold: false }): string {
113
+ const out: string[] = []
114
+ let i = 0
115
+ while (i < text.length) {
116
+ const ch = text[i]!
117
+
118
+ if (ch === '`') {
119
+ const close = text.indexOf('`', i + 1)
120
+ if (close !== -1) {
121
+ out.push(text.slice(i, close + 1))
122
+ i = close + 1
123
+ continue
124
+ }
125
+ }
126
+
127
+ if (ch === '[') {
128
+ const link = parseLink(text, i)
129
+ if (link !== null) {
130
+ out.push(`<${link.url}|${renderInline(link.label, options)}>`)
131
+ i = link.end
132
+ continue
133
+ }
134
+ }
135
+
136
+ if (ch === '*' && text[i + 1] === '*') {
137
+ const close = findClose(text, i + 2, '**')
138
+ if (close > i + 2) {
139
+ const inner = renderInline(text.slice(i + 2, close), options)
140
+ out.push(options.flattenBold ? inner : `*${inner}*`)
141
+ i = close + 2
142
+ continue
143
+ }
144
+ }
145
+
146
+ // `__bold__` only when not adjacent to a word char on either side, so a
147
+ // snake_case identifier the model wrote (`my__var__name`) is left alone.
148
+ if (ch === '_' && text[i + 1] === '_' && !isWordChar(text[i - 1])) {
149
+ const close = findClose(text, i + 2, '__')
150
+ if (close > i + 2 && !isWordChar(text[close + 2])) {
151
+ const inner = renderInline(text.slice(i + 2, close), options)
152
+ out.push(options.flattenBold ? inner : `*${inner}*`)
153
+ i = close + 2
154
+ continue
155
+ }
156
+ }
157
+
158
+ if (ch === '~' && text[i + 1] === '~') {
159
+ const close = findClose(text, i + 2, '~~')
160
+ if (close > i + 2) {
161
+ out.push(`~${renderInline(text.slice(i + 2, close), options)}~`)
162
+ i = close + 2
163
+ continue
164
+ }
165
+ }
166
+
167
+ // Italic: word-boundary guard on both sides so `a*b*c` and identifiers
168
+ // don't italicize. The guards are ASCII word chars by design — they
169
+ // gate on the model's Latin identifier/math usage; CJK/Korean text has
170
+ // no such tokens, so bold/italic markers around Korean still convert.
171
+ if (ch === '*' && !isWordChar(text[i - 1])) {
172
+ const close = findInlineClose(text, i + 1, '*')
173
+ if (close !== -1 && !isWordChar(text[close + 1])) {
174
+ const inner = text.slice(i + 1, close)
175
+ if (inner !== '' && !/^\s|\s$/.test(inner)) {
176
+ out.push(`_${renderInline(inner, options)}_`)
177
+ i = close + 1
178
+ continue
179
+ }
180
+ }
181
+ }
182
+ if (ch === '_' && !isWordChar(text[i - 1])) {
183
+ const close = findInlineClose(text, i + 1, '_')
184
+ if (close !== -1 && !isWordChar(text[close + 1])) {
185
+ const inner = text.slice(i + 1, close)
186
+ if (inner !== '' && !/^\s|\s$/.test(inner)) {
187
+ out.push(`_${renderInline(inner, options)}_`)
188
+ i = close + 1
189
+ continue
190
+ }
191
+ }
192
+ }
193
+
194
+ out.push(ch)
195
+ i++
196
+ }
197
+ return out.join('')
198
+ }
199
+
200
+ function findClose(text: string, from: number, marker: string): number {
201
+ let i = from
202
+ while (i <= text.length - marker.length) {
203
+ if (text.slice(i, i + marker.length) === marker) return i
204
+ i++
205
+ }
206
+ return -1
207
+ }
208
+
209
+ function findInlineClose(text: string, from: number, marker: string): number {
210
+ let i = from
211
+ while (i < text.length) {
212
+ if (text[i] === '\n') return -1
213
+ if (text[i] === marker) return i
214
+ i++
215
+ }
216
+ return -1
217
+ }
218
+
219
+ function parseLink(text: string, start: number): { label: string; url: string; end: number } | null {
220
+ let i = start + 1
221
+ const labelStart = i
222
+ while (i < text.length) {
223
+ const c = text[i]!
224
+ if (c === ']') break
225
+ if (c === '\n') return null
226
+ i++
227
+ }
228
+ if (text[i] !== ']' || text[i + 1] !== '(') return null
229
+ const label = text.slice(labelStart, i)
230
+ const urlStart = i + 2
231
+ let j = urlStart
232
+ while (j < text.length) {
233
+ const c = text[j]!
234
+ if (c === ')') break
235
+ if (c === '(' || c === '\n') return null
236
+ j++
237
+ }
238
+ if (text[j] !== ')') return null
239
+ return { label, url: text.slice(urlStart, j), end: j + 1 }
240
+ }
241
+
242
+ function isWordChar(ch: string | undefined): boolean {
243
+ if (ch === undefined) return false
244
+ return /[A-Za-z0-9_]/.test(ch)
245
+ }
@@ -11,9 +11,8 @@ export type GithubTokenBridge = {
11
11
  resolveTokenForRepo: ResolveGithubTokenForRepo
12
12
  // True when a per-repo App-token minter is registered (only the GitHub App
13
13
  // adapter registers one). This is the non-secret "App auth with per-repo
14
- // minting is available" signal: it stays true for multi-owner / no-repos App
15
- // configs where the process-wide GH_TOKEN is intentionally NOT seeded, so the
16
- // git/gh mint paths can no longer rely on GH_TOKEN's prefix to detect App auth.
14
+ // minting is available" signal. App credentials are never seeded into the
15
+ // process-wide GH_TOKEN, so brokered gh paths cannot rely on its prefix.
17
16
  hasAppTokenResolver: () => boolean
18
17
  getAppSelfLogin: () => string | null
19
18
  registerResolver: (resolver: (repoSlug: string) => Promise<string>, selfLogin?: () => string | null) => () => void
@@ -150,6 +150,19 @@ export async function runInspectViewer(opts: RunInspectViewerOptions): Promise<n
150
150
  }
151
151
 
152
152
  const interactive = Boolean(process.stdin.isTTY)
153
+
154
+ // Without a TTY, clack's picker keypress loop busy-spins kevent64 at 100% CPU
155
+ // forever instead of resolving (e.g. `typeclaw inspect | head`, a daemon
156
+ // spawn). A resolved session arg auto-opens without the picker, so only the
157
+ // picker-mandatory case is refused — mirroring --json's explicit-id rule.
158
+ if (!interactive && preselectKey === undefined) {
159
+ process.stderr.write(`${errorLine('typeclaw inspect needs an interactive terminal to pick a session.')}\n`)
160
+ process.stderr.write(
161
+ 'Pass an explicit session id (`typeclaw inspect <id>`) or use `--json <id>` for a scriptable stream.\n',
162
+ )
163
+ return 2
164
+ }
165
+
153
166
  const liveHint = interactive ? escHintLine(color) : undefined
154
167
  const inspectUrl = containerRunning ? await resolveInspectUrl(cwd) : undefined
155
168
  const liveSource = inspectUrl !== undefined ? buildLiveSource(inspectUrl) : undefined
@@ -181,6 +194,9 @@ export async function runInspectViewer(opts: RunInspectViewerOptions): Promise<n
181
194
  const listOpts: Parameters<typeof listViewerItems>[0] = {
182
195
  sessionsDir,
183
196
  containerRunning,
197
+ // listViewerItems also gates writable promotion on `interactive`, so a
198
+ // non-TTY explicit id can't auto-open a TUI it cannot drive.
199
+ interactive,
184
200
  // Compose the CLI-level permission (false on tui detach handoff) with
185
201
  // the loop-level one (false after returning to the picker from a viewer).
186
202
  allowWritable: cliAllowWritable && loopAllowWritable,
@@ -1,18 +1,22 @@
1
1
  import { existsSync } from 'node:fs'
2
2
 
3
- import { getBun } from './shared'
3
+ import { getBun, sanitizeDockerStderr } from './shared'
4
4
  import type { DockerAvailability } from './shared'
5
5
 
6
6
  // Detection + friendly guidance for "Docker is not reachable".
7
7
  //
8
8
  // `checkDockerAvailable` (in ./shared) already tells us WHETHER docker works and
9
9
  // discriminates `binary-missing` (no `docker` on PATH) from `daemon-down` (CLI
10
- // present, daemon refused the connection — the common "Docker Desktop / OrbStack
11
- // installed but not started" case on macOS). What it does NOT do is tell the
12
- // user WHICH runtime to nudge. This module fills that gap: it classifies the
13
- // likely runtime and renders a short, copy-pasteable instruction instead of
14
- // leaking the raw daemon error (which on OrbStack embeds a per-user socket path
15
- // under the user's home dir — noise the user can't act on).
10
+ // present, the selected Docker endpoint refused the connection). That covers the
11
+ // common "Docker Desktop / OrbStack installed but not started" case on macOS —
12
+ // but `docker info` failing proves only that the CONFIGURED ENDPOINT is
13
+ // unreachable, NOT that the runtime process is stopped: a running OrbStack whose
14
+ // CLI is pointed at a stale `desktop-linux` context (or an SSH session missing
15
+ // the interactive shell's DOCKER_HOST) produces the exact same connection error.
16
+ // So this module must not assert the app is "not started" — it nudges the likely
17
+ // runtime to start AND surfaces the context/endpoint recovery path plus the raw
18
+ // (sanitized) Docker error, so a user who knows the runtime is already up isn't
19
+ // sent into a dead-end "start it" loop.
16
20
  //
17
21
  // Classification priority (most → least authoritative):
18
22
  // 1. The configured socket: `DOCKER_HOST` or the socket path inside the raw
@@ -121,8 +125,8 @@ export function detectInstalledDockerApps(probes: DockerAppProbes = {}): DockerA
121
125
  // Docker Desktop's GUI launcher (`Docker Desktop.exe`) across the MSI, 32-bit,
122
126
  // and per-user install layouts confirmed by the Docker Desktop installer and
123
127
  // PowerShell's own probing scripts. Probing the exe (not just `docker` on PATH)
124
- // is what lets us say "Docker Desktop is installed but not started" when the
125
- // daemon is down — a stale PATH can hide the CLI even when Desktop is present.
128
+ // is what lets us name Docker Desktop as the runtime to nudge when the daemon is
129
+ // unreachable — a stale PATH can hide the CLI even when Desktop is present.
126
130
  function windowsDockerDesktopInstalled(env: NodeJS.ProcessEnv, exists: (path: string) => boolean): boolean {
127
131
  const programFiles = env.ProgramW6432 ?? env.ProgramFiles ?? 'C:\\Program Files'
128
132
  const programFilesX86 = env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)'
@@ -231,23 +235,48 @@ export function renderDockerUnavailableGuidance(
231
235
  return { summary: 'Docker is not installed.', lines }
232
236
  }
233
237
 
234
- // daemon-down
238
+ // daemon-down: the configured Docker endpoint refused the connection. We can
239
+ // nudge the likely runtime to start, but must NOT claim it's stopped — the
240
+ // same error fires when the runtime is up and the CLI is on the wrong context.
235
241
  const lines: string[] = []
236
242
  let summary: string
237
243
  if (nudge !== null) {
238
- summary = `Docker is not running. ${dockerAppLabel(nudge)} is installed but not started.`
244
+ const label = dockerAppLabel(nudge)
245
+ summary = `Docker daemon is not reachable. Start ${label}, or check its connection if it's already running.`
239
246
  lines.push(...startInstructions(nudge, platform))
240
247
  } else if (installed.length > 1) {
241
248
  const names = installed.map(dockerAppLabel).join(', ')
242
- summary = 'Docker is not running.'
249
+ summary = `Docker daemon is not reachable. Start ${names}, or check your docker connection if it's already running.`
243
250
  lines.push(`Detected: ${names}. Start whichever one you use, then retry.`)
244
251
  } else {
245
- summary = 'Docker is installed but the daemon is not reachable.'
252
+ summary =
253
+ "Docker daemon is not reachable. Start your Docker runtime, or check your docker connection if it's already running."
246
254
  lines.push(...genericStartInstructions(platform))
247
255
  }
248
256
 
257
+ lines.push('', ...alreadyRunningRecovery(availability.detail))
258
+
249
259
  if (retryHint) {
250
260
  lines.push('', retryHint)
251
261
  }
252
262
  return { summary, lines }
253
263
  }
264
+
265
+ // The recovery path for the case the start-instructions can't fix: the runtime
266
+ // is already running but `docker info` still fails because the CLI is pointed at
267
+ // an unreachable endpoint (stale `docker context`, a leftover `DOCKER_HOST`, or
268
+ // a non-interactive/SSH shell missing the interactive env). We surface the
269
+ // configuration knobs to check plus the sanitized Docker error so the endpoint
270
+ // stays visible instead of being hidden as "noise".
271
+ function alreadyRunningRecovery(detail: string): string[] {
272
+ const lines = [
273
+ 'If it is already running, your docker CLI may be pointed at the wrong endpoint',
274
+ '(common over SSH or in non-interactive shells).',
275
+ 'Check `docker context ls`, `DOCKER_CONTEXT`, and `DOCKER_HOST`.',
276
+ ]
277
+ const reported = sanitizeDockerStderr(detail)
278
+ if (reported !== '') {
279
+ lines.push(`Docker reported: ${reported}`)
280
+ }
281
+ return lines
282
+ }
@@ -92,7 +92,7 @@ export const defaultDockerExec: DockerExec = async (args, options) => {
92
92
  // needs both: the user watches the build, and start() inspects the captured
93
93
  // stderr to detect a missing credential helper and retry under a sanitized
94
94
  // DOCKER_CONFIG.
95
- async function spawnInheritTeeStderr(
95
+ export async function spawnInheritTeeStderr(
96
96
  bun: NonNullable<ReturnType<typeof getBun>>,
97
97
  cmd: string[],
98
98
  cwd: string | undefined,
@@ -102,11 +102,24 @@ async function spawnInheritTeeStderr(
102
102
  const proc = bun.spawn({ cmd, cwd, stdout: 'inherit', stderr: 'pipe', signal, env })
103
103
  const chunks: Uint8Array[] = []
104
104
  const reader = proc.stderr.getReader()
105
- for (;;) {
106
- const { done, value } = await reader.read()
107
- if (done) break
108
- process.stderr.write(value)
109
- chunks.push(value)
105
+ try {
106
+ for (;;) {
107
+ const { done, value } = await reader.read()
108
+ if (done) break
109
+ process.stderr.write(value)
110
+ chunks.push(value)
111
+ }
112
+ } catch (err) {
113
+ // A read/write throw skips the normal drain: cancel (not just releaseLock,
114
+ // which leaves the pipe live per the Streams contract), kill the child, and
115
+ // await its exit so neither the stderr pipe nor the docker subprocess is
116
+ // orphaned. releaseLock is handled in `finally` for both paths.
117
+ await reader.cancel().catch(() => {})
118
+ proc.kill()
119
+ await proc.exited.catch(() => {})
120
+ throw err
121
+ } finally {
122
+ reader.releaseLock()
110
123
  }
111
124
  const exitCode = await proc.exited
112
125
  return { exitCode, stdout: '', stderr: Buffer.concat(chunks).toString('utf8') }