typeclaw 0.46.0 → 0.46.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.
- package/README.md +1 -1
- package/package.json +2 -2
- package/src/agent/multimodal/looker.ts +11 -1
- package/src/agent/network/safe-http.ts +17 -8
- package/src/agent/plugin-tools.ts +1 -3
- package/src/agent/tool-file-safety.ts +396 -136
- package/src/agent/tools/webfetch/fetch.ts +22 -2
- package/src/agent/tools-without-local-file-operands.ts +9 -6
- package/src/bundled-plugins/backup/README.md +23 -10
- package/src/bundled-plugins/backup/git-auth.ts +6 -4
- package/src/bundled-plugins/backup/index.ts +83 -43
- package/src/bundled-plugins/backup/runner.ts +83 -0
- package/src/bundled-plugins/github-cli-auth/git-askpass.ts +74 -26
- package/src/bundled-plugins/github-cli-auth/git-command.ts +224 -36
- package/src/bundled-plugins/github-cli-auth/graphql-auth-nudge.ts +9 -9
- package/src/bundled-plugins/github-cli-auth/index.ts +110 -31
- package/src/bundled-plugins/github-cli-auth/token-class.ts +4 -6
- package/src/bundled-plugins/memory/README.md +9 -0
- package/src/bundled-plugins/memory/vector/embed-threads.ts +36 -0
- package/src/bundled-plugins/memory/vector/embedder.ts +19 -1
- package/src/bundled-plugins/researcher/write-report.ts +3 -3
- package/src/bundled-plugins/security/policies/private-surface-read.ts +610 -50
- package/src/bundled-plugins/security/policies/ssrf.ts +119 -34
- package/src/channels/adapters/github/inbound.ts +11 -0
- package/src/channels/adapters/github/index.ts +48 -54
- package/src/channels/adapters/github/reconcile-cooldown-store.ts +178 -0
- package/src/channels/adapters/github/reconcile-open-prs.ts +31 -0
- package/src/channels/adapters/slack-bot-edit.ts +85 -20
- package/src/channels/adapters/slack-bot.ts +7 -2
- package/src/channels/adapters/slack-format.ts +245 -0
- package/src/channels/github-token-bridge.ts +2 -3
- package/src/container/docker-app.ts +42 -13
- package/src/container/start.ts +13 -0
- package/src/cron/bridge.ts +9 -2
- package/src/doctor/checks.ts +5 -2
- package/src/git/bound-gc-config.ts +82 -0
- package/src/hostd/spawn.ts +133 -47
- package/src/init/dockerfile.ts +13 -0
- package/src/inspect/replay.ts +21 -9
- package/src/inspect/session-list.ts +71 -33
- package/src/mcp/tools.ts +1 -0
- package/src/network/internal-destinations.ts +267 -0
- package/src/plugin/types.ts +3 -2
- package/src/sandbox/env-exposure.ts +18 -15
- package/src/sandbox/policy.ts +5 -3
- package/src/sandbox/privileged-runtime.ts +1 -0
- package/src/skills/typeclaw-config/SKILL.md +22 -6
- package/src/skills/typeclaw-permissions/SKILL.md +22 -9
- package/src/skills/typeclaw-plugins/SKILL.md +37 -0
- package/src/usage/scan.ts +11 -2
- package/typeclaw.schema.json +5 -0
- 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
|
-
|
|
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
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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
|
-
|
|
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
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
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):
|
|
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
|
-
|
|
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({
|
|
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
|
|
15
|
-
//
|
|
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
|
|
@@ -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,
|
|
11
|
-
// installed but not started" case on macOS
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
//
|
|
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
|
|
125
|
-
//
|
|
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
|
-
|
|
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 =
|
|
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 =
|
|
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
|
+
}
|
package/src/container/start.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { tmpdir } from 'node:os'
|
|
|
5
5
|
import { isAbsolute, join, relative, resolve } from 'node:path'
|
|
6
6
|
|
|
7
7
|
import { expandMountPath, loadConfigSync, withDefaultPlugins, type Config, type PortForward } from '@/config'
|
|
8
|
+
import { applyBoundGcConfig } from '@/git/bound-gc-config'
|
|
8
9
|
import { commitGitignoreWithUntracks, untrackTrulyIgnoredFiles } from '@/git/reconcile-ignored'
|
|
9
10
|
import { commitSystemFile as commitSystemFileShared } from '@/git/system-commit'
|
|
10
11
|
import { send as sendToDaemon } from '@/hostd/client'
|
|
@@ -238,6 +239,15 @@ export async function start({
|
|
|
238
239
|
// that would surprise a user invoking `compose start` against a partially-up
|
|
239
240
|
// tree.
|
|
240
241
|
const state = await inspectContainer(exec, containerName)
|
|
242
|
+
|
|
243
|
+
// Bound gc/repack memory even when start() is an already-running no-op below:
|
|
244
|
+
// the running agent's backup keeps committing, so it must not keep using the
|
|
245
|
+
// unbounded Git defaults until a full stop/restart. This is a machine-local
|
|
246
|
+
// `git config` write (never committed, no template/side effect), so unlike the
|
|
247
|
+
// Dockerfile/.gitignore/package.json refreshes it is safe before the running
|
|
248
|
+
// return — no surprise for `compose start` against a partially-up tree.
|
|
249
|
+
await applyBoundGcConfig(cwd)
|
|
250
|
+
|
|
241
251
|
if (state.exists && state.running) {
|
|
242
252
|
return await reportAlreadyRunning(exec, cwd, containerName)
|
|
243
253
|
}
|
|
@@ -262,6 +272,9 @@ export async function start({
|
|
|
262
272
|
// refreshGitignore call below reads typeclaw.json and will incidentally
|
|
263
273
|
// trigger the migration commit if the file was legacy.
|
|
264
274
|
await refreshGitignore(cwd)
|
|
275
|
+
// Machine-local `git config` that bounds gc/repack memory on the agent repo.
|
|
276
|
+
// Runs alongside the other managed-file refreshes; not committed (local scope).
|
|
277
|
+
await applyBoundGcConfig(cwd)
|
|
265
278
|
const pkgRefresh = await refreshPackageJson(cwd)
|
|
266
279
|
const { untracked } = await untrackTrulyIgnoredFiles(cwd, (await loadTypeclawConfig(cwd)).git.ignore.append)
|
|
267
280
|
if (untracked.length > 0) {
|
package/src/cron/bridge.ts
CHANGED
|
@@ -5,6 +5,12 @@ export type CronListBridgeOptions = {
|
|
|
5
5
|
cwd: string
|
|
6
6
|
url?: string
|
|
7
7
|
timeoutMs?: number
|
|
8
|
+
// Budget for the WS handshake only. Defaults to timeoutMs so production
|
|
9
|
+
// behavior is unchanged. Split out so the reply-timeout path can be tested
|
|
10
|
+
// with a tight reply budget while giving the connect phase enough slack to
|
|
11
|
+
// survive CPU contention under parallel tests — a slow handshake must not
|
|
12
|
+
// masquerade as a reply timeout (or, worse, surface as `unreachable`).
|
|
13
|
+
connectTimeoutMs?: number
|
|
8
14
|
// Injected for tests so the in-container short-circuit can be exercised
|
|
9
15
|
// without polluting process.env. Production callers omit this and the
|
|
10
16
|
// bridge reads from process.env directly.
|
|
@@ -35,6 +41,7 @@ type DialResult = { kind: 'ok'; ws: WebSocket; timeoutMs: number } | { kind: 'un
|
|
|
35
41
|
|
|
36
42
|
async function dial(opts: CronListBridgeOptions): Promise<DialResult> {
|
|
37
43
|
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
44
|
+
const connectTimeoutMs = opts.connectTimeoutMs ?? timeoutMs
|
|
38
45
|
let url = opts.url
|
|
39
46
|
if (url === undefined) {
|
|
40
47
|
try {
|
|
@@ -74,8 +81,8 @@ async function dial(opts: CronListBridgeOptions): Promise<DialResult> {
|
|
|
74
81
|
try {
|
|
75
82
|
ws.close()
|
|
76
83
|
} catch {}
|
|
77
|
-
reject(new Error(`timed out connecting to ${displayUrl} after ${
|
|
78
|
-
},
|
|
84
|
+
reject(new Error(`timed out connecting to ${displayUrl} after ${connectTimeoutMs}ms`))
|
|
85
|
+
}, connectTimeoutMs)
|
|
79
86
|
ws.addEventListener('open', onOpen, { once: true })
|
|
80
87
|
ws.addEventListener('error', onError, { once: true })
|
|
81
88
|
ws.addEventListener('close', onClose, { once: true })
|
package/src/doctor/checks.ts
CHANGED
|
@@ -61,12 +61,15 @@ function dockerDaemon(exec: DockerExec): DoctorCheck {
|
|
|
61
61
|
if (result.ok) return { status: 'ok', message: 'docker info responded' }
|
|
62
62
|
return {
|
|
63
63
|
status: 'error',
|
|
64
|
-
message: result.reason === 'binary-missing' ? 'docker binary missing on $PATH' : 'docker daemon
|
|
64
|
+
message: result.reason === 'binary-missing' ? 'docker binary missing on $PATH' : 'docker daemon not reachable',
|
|
65
65
|
details: [result.detail],
|
|
66
66
|
fix:
|
|
67
67
|
result.reason === 'binary-missing'
|
|
68
68
|
? { description: 'Install Docker (Docker Desktop, OrbStack, or docker-ce).' }
|
|
69
|
-
: {
|
|
69
|
+
: {
|
|
70
|
+
description:
|
|
71
|
+
'Start the Docker runtime (Docker Desktop, OrbStack, or `systemctl start docker`). If it is already running, check `docker context ls`, `DOCKER_CONTEXT`, and `DOCKER_HOST`.',
|
|
72
|
+
},
|
|
70
73
|
}
|
|
71
74
|
},
|
|
72
75
|
}
|