typeclaw 0.45.1 → 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 +3 -2
- package/src/agent/git-nudge.ts +2 -1
- package/src/agent/index.ts +44 -30
- package/src/agent/live-subagents.ts +18 -0
- package/src/agent/multimodal/index.ts +1 -1
- package/src/agent/multimodal/look-at.ts +78 -44
- package/src/agent/multimodal/looker.ts +161 -39
- package/src/agent/network/response-body.ts +26 -0
- package/src/agent/network/safe-http.ts +207 -0
- package/src/agent/plugin-tools.ts +377 -157
- package/src/agent/provider-error.ts +52 -1
- package/src/agent/restart/index.ts +61 -40
- package/src/agent/restart-handoff/index.ts +73 -4
- package/src/agent/reviewer-bash-policy.ts +42 -1
- package/src/agent/session-origin.ts +2 -0
- package/src/agent/subagent-drain.ts +117 -7
- package/src/agent/subagents.ts +49 -16
- package/src/agent/throttle-circuit.ts +25 -5
- package/src/agent/tool-error-remediation.ts +72 -0
- package/src/agent/tool-file-safety.ts +1310 -0
- package/src/agent/tools/channel-fetch-attachment.ts +10 -3
- package/src/agent/tools/ddg.ts +16 -2
- package/src/agent/tools/post-github-review.ts +199 -0
- package/src/agent/tools/spawn-subagent.ts +21 -18
- package/src/agent/tools/webfetch/fetch.ts +163 -183
- package/src/agent/tools/webfetch/tool.ts +2 -3
- package/src/agent/tools/websearch.ts +23 -2
- package/src/agent/tools-without-local-file-operands.ts +30 -0
- package/src/agent/turn-runner.ts +86 -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 +85 -44
- package/src/bundled-plugins/backup/runner.ts +85 -1
- package/src/bundled-plugins/doc-render/render.ts +93 -12
- package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
- package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
- package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
- 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 +207 -132
- package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
- package/src/bundled-plugins/github-cli-auth/token-class.ts +4 -6
- package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
- package/src/bundled-plugins/memory/README.md +32 -11
- package/src/bundled-plugins/memory/append-tool.ts +15 -8
- package/src/bundled-plugins/memory/citations.ts +22 -9
- package/src/bundled-plugins/memory/dreaming.ts +13 -8
- package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
- package/src/bundled-plugins/memory/index.ts +0 -4
- package/src/bundled-plugins/memory/load-memory.ts +8 -3
- package/src/bundled-plugins/memory/provenance-index.ts +717 -0
- package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
- package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
- package/src/bundled-plugins/memory/search-tool.ts +163 -60
- package/src/bundled-plugins/memory/stream-events.ts +2 -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/memory/vector/hybrid.ts +126 -13
- package/src/bundled-plugins/researcher/write-report.ts +8 -5
- package/src/bundled-plugins/reviewer/index.ts +2 -2
- package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
- package/src/bundled-plugins/reviewer/skills/code-review.ts +19 -9
- package/src/bundled-plugins/scout/scout.ts +8 -0
- package/src/bundled-plugins/security/index.ts +4 -4
- package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
- package/src/bundled-plugins/security/policies/private-surface-read.ts +787 -36
- package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
- package/src/bundled-plugins/security/policies/ssrf.ts +147 -42
- package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
- package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
- package/src/channels/adapters/discord-bot.ts +66 -6
- package/src/channels/adapters/discord-channel-resolver.ts +91 -23
- package/src/channels/adapters/discord-id.ts +4 -0
- package/src/channels/adapters/discord-resolver-cache.ts +41 -0
- package/src/channels/adapters/discord.ts +57 -7
- package/src/channels/adapters/github/auth-app.ts +41 -12
- package/src/channels/adapters/github/inbound.ts +11 -0
- package/src/channels/adapters/github/index.ts +71 -65
- 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/github/review-submitter.ts +302 -0
- package/src/channels/adapters/kakaotalk-channel-resolver.ts +5 -3
- package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
- package/src/channels/adapters/kakaotalk-typing.ts +17 -15
- package/src/channels/adapters/slack-attachment-download.ts +71 -0
- package/src/channels/adapters/slack-bot-edit.ts +85 -20
- package/src/channels/adapters/slack-bot.ts +26 -10
- package/src/channels/adapters/slack-classify.ts +21 -2
- package/src/channels/adapters/slack-format.ts +245 -0
- package/src/channels/adapters/slack.ts +59 -7
- package/src/channels/adapters/telegram-bot.ts +18 -5
- package/src/channels/adapters/webex-bot.ts +8 -3
- package/src/channels/adapters/webex.ts +8 -3
- package/src/channels/fetch-attachment.ts +43 -0
- package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
- package/src/channels/github-token-bridge.ts +12 -6
- package/src/channels/manager.ts +9 -0
- package/src/channels/router.ts +248 -6
- package/src/channels/types.ts +28 -1
- package/src/cli/channel.ts +1 -1
- package/src/cli/init.ts +1 -1
- package/src/cli/model.ts +57 -7
- package/src/compose/stop.ts +17 -5
- package/src/config/config.ts +6 -6
- package/src/config/models-mutation.ts +13 -1
- package/src/config/providers.ts +176 -0
- package/src/container/docker-app.ts +42 -13
- package/src/container/start.ts +62 -10
- package/src/cron/bridge.ts +9 -2
- package/src/doctor/checks.ts +8 -3
- package/src/doctor/commit.ts +2 -1
- package/src/doctor/file-ownership.ts +52 -0
- package/src/dreams/git.ts +2 -1
- package/src/git/bound-gc-config.ts +82 -0
- package/src/git/hookless.ts +5 -0
- package/src/git/reconcile-ignored.ts +18 -5
- package/src/git/system-commit.ts +12 -6
- package/src/hostd/spawn.ts +133 -47
- package/src/init/dockerfile.ts +99 -5
- package/src/init/index.ts +17 -5
- package/src/init/models-dev.ts +4 -0
- package/src/init/validate-api-key.ts +2 -0
- package/src/inspect/replay.ts +21 -9
- package/src/inspect/session-list.ts +71 -33
- package/src/mcp/tools.ts +17 -3
- package/src/network/internal-destinations.ts +267 -0
- package/src/permissions/builtins.ts +3 -1
- package/src/plugin/context.ts +2 -0
- package/src/plugin/index.ts +1 -0
- package/src/plugin/manager.ts +4 -0
- package/src/plugin/types.ts +22 -0
- package/src/run/index.ts +40 -0
- package/src/run/llm-fetch-observer.ts +41 -4
- package/src/sandbox/build.ts +37 -15
- package/src/sandbox/canonical-secrets.ts +18 -0
- package/src/sandbox/env-exposure.ts +83 -0
- package/src/sandbox/errors.ts +13 -6
- package/src/sandbox/hidden-paths.ts +102 -44
- package/src/sandbox/index.ts +22 -4
- package/src/sandbox/package-install.ts +3 -27
- package/src/sandbox/policy.ts +16 -28
- package/src/sandbox/privileged-runtime.ts +256 -0
- package/src/sandbox/session-tmp.ts +8 -2
- package/src/sandbox/writable-zones.ts +204 -140
- package/src/secrets/index.ts +8 -0
- package/src/secrets/refresh-provider-oauth.ts +128 -0
- package/src/server/command-runner.ts +48 -4
- package/src/server/index.ts +4 -0
- package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
- package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
- package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
- package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
- package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
- package/src/skills/typeclaw-config/SKILL.md +27 -11
- package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
- package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
- package/src/skills/typeclaw-memory/SKILL.md +9 -3
- package/src/skills/typeclaw-permissions/SKILL.md +36 -19
- package/src/skills/typeclaw-plugins/SKILL.md +37 -0
- package/src/usage/scan.ts +11 -2
- package/typeclaw.schema.json +25 -0
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ReviewFinding,
|
|
3
|
+
ReviewSubmitter,
|
|
4
|
+
SubmitReviewErrorCode,
|
|
5
|
+
SubmitReviewRequest,
|
|
6
|
+
SubmitReviewResult,
|
|
7
|
+
} from '@/channels/types'
|
|
8
|
+
|
|
9
|
+
import type { GithubAuthContext } from './auth'
|
|
10
|
+
import { GITHUB_API_BASE, githubJsonHeaders } from './auth-pat'
|
|
11
|
+
|
|
12
|
+
const MAX_HEAD_STABILITY_ATTEMPTS = 3
|
|
13
|
+
|
|
14
|
+
export function createGithubReviewSubmitter(deps: {
|
|
15
|
+
token: (context?: GithubAuthContext) => Promise<string>
|
|
16
|
+
allowApprove: () => boolean
|
|
17
|
+
fetchImpl?: typeof fetch
|
|
18
|
+
}): ReviewSubmitter {
|
|
19
|
+
const fetchImpl = deps.fetchImpl ?? fetch
|
|
20
|
+
return async (req): Promise<SubmitReviewResult> => {
|
|
21
|
+
if (req.adapter !== 'github') return { ok: false, error: `unknown adapter: ${req.adapter}`, code: 'unsupported' }
|
|
22
|
+
const target = parseTarget(req)
|
|
23
|
+
if (target === null) {
|
|
24
|
+
return {
|
|
25
|
+
ok: false,
|
|
26
|
+
error: `unparseable github review target (workspace=${req.workspace}, chat=${req.chat})`,
|
|
27
|
+
code: 'transient',
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const token = await deps.token({ repoSlug: `${target.owner}/${target.repo}` })
|
|
32
|
+
const stable = await fetchStableAnchors(fetchImpl, token, target)
|
|
33
|
+
if (!stable.ok) return stable
|
|
34
|
+
|
|
35
|
+
const { inline, reanchored } = partitionComments(req.comments, stable.anchors)
|
|
36
|
+
const downgraded = req.event === 'APPROVE' && !deps.allowApprove()
|
|
37
|
+
const event = downgraded ? 'COMMENT' : req.event
|
|
38
|
+
const posted = await postReview(fetchImpl, token, target, {
|
|
39
|
+
event,
|
|
40
|
+
body: appendReanchored(req.body, reanchored),
|
|
41
|
+
commitId: stable.headSha,
|
|
42
|
+
comments: inline,
|
|
43
|
+
})
|
|
44
|
+
if (!posted.ok) return posted
|
|
45
|
+
const verified = await verifyReview(fetchImpl, token, target, posted.reviewId, event)
|
|
46
|
+
if (!verified.ok) return { ...verified, submitted: true }
|
|
47
|
+
return {
|
|
48
|
+
ok: true,
|
|
49
|
+
reviewId: verified.reviewId,
|
|
50
|
+
state: verified.state,
|
|
51
|
+
...(downgraded ? { downgraded: true } : {}),
|
|
52
|
+
...(reanchored.length > 0 ? { reanchored } : {}),
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function fetchStableAnchors(
|
|
58
|
+
fetchImpl: typeof fetch,
|
|
59
|
+
token: string,
|
|
60
|
+
target: ReviewTarget,
|
|
61
|
+
): Promise<{ ok: true; headSha: string; anchors: Set<string> } | (SubmitReviewResult & { ok: false })> {
|
|
62
|
+
for (let attempt = 0; attempt < MAX_HEAD_STABILITY_ATTEMPTS; attempt++) {
|
|
63
|
+
const before = await fetchPull(fetchImpl, token, target)
|
|
64
|
+
if (!before.ok) return before
|
|
65
|
+
const anchors = await fetchAnchors(fetchImpl, token, target)
|
|
66
|
+
if (!anchors.ok) return anchors
|
|
67
|
+
const after = await fetchPull(fetchImpl, token, target)
|
|
68
|
+
if (!after.ok) return after
|
|
69
|
+
if (before.headSha === after.headSha) return { ok: true, headSha: before.headSha, anchors: anchors.anchors }
|
|
70
|
+
}
|
|
71
|
+
return { ok: false, error: 'GitHub pull request head changed during anchor collection', code: 'transient' }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
type ReviewTarget = { owner: string; repo: string; prNumber: number }
|
|
75
|
+
|
|
76
|
+
function parseTarget(req: SubmitReviewRequest): ReviewTarget | null {
|
|
77
|
+
const [owner, repo, ...rest] = req.workspace.split('/')
|
|
78
|
+
const match = /^pr:(\d+)$/.exec(req.chat)
|
|
79
|
+
const prNumber = match === null ? null : parseDecimalId(match[1])
|
|
80
|
+
if (!owner || !repo || rest.length > 0 || prNumber === null) return null
|
|
81
|
+
return { owner, repo, prNumber }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function parseDecimalId(value: string | undefined): number | null {
|
|
85
|
+
if (value === undefined || !/^\d+$/.test(value)) return null
|
|
86
|
+
const parsed = Number(value)
|
|
87
|
+
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function fetchPull(
|
|
91
|
+
fetchImpl: typeof fetch,
|
|
92
|
+
token: string,
|
|
93
|
+
target: ReviewTarget,
|
|
94
|
+
): Promise<{ ok: true; headSha: string } | (SubmitReviewResult & { ok: false })> {
|
|
95
|
+
const response = await githubFetch(fetchImpl, token, pullUrl(target))
|
|
96
|
+
if (!response.ok) return responseError(response, 'GitHub pull request fetch')
|
|
97
|
+
const body = await readJson<PullResponse>(response)
|
|
98
|
+
if (typeof body?.head?.sha !== 'string' || body.head.sha === '') {
|
|
99
|
+
return { ok: false, error: 'GitHub pull request response missing head.sha', code: 'transient' }
|
|
100
|
+
}
|
|
101
|
+
return { ok: true, headSha: body.head.sha }
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function fetchAnchors(
|
|
105
|
+
fetchImpl: typeof fetch,
|
|
106
|
+
token: string,
|
|
107
|
+
target: ReviewTarget,
|
|
108
|
+
): Promise<{ ok: true; anchors: Set<string> } | (SubmitReviewResult & { ok: false })> {
|
|
109
|
+
const anchors = new Set<string>()
|
|
110
|
+
let url: string | null = `${pullUrl(target)}/files?per_page=100`
|
|
111
|
+
while (url !== null) {
|
|
112
|
+
const response = await githubFetch(fetchImpl, token, url)
|
|
113
|
+
if (!response.ok) return responseError(response, 'GitHub pull request files fetch')
|
|
114
|
+
const body = await readJson<PullFilesResponse>(response)
|
|
115
|
+
if (!Array.isArray(body)) {
|
|
116
|
+
return { ok: false, error: 'GitHub pull request files response was not an array', code: 'transient' }
|
|
117
|
+
}
|
|
118
|
+
for (const file of body) {
|
|
119
|
+
if (typeof file.filename === 'string' && typeof file.patch === 'string') {
|
|
120
|
+
addPatchAnchors(anchors, file.filename, file.patch)
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
url = nextLink(response.headers.get('link'))
|
|
124
|
+
}
|
|
125
|
+
return { ok: true, anchors }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function addPatchAnchors(anchors: Set<string>, path: string, patch: string): void {
|
|
129
|
+
let left = 0
|
|
130
|
+
let right = 0
|
|
131
|
+
for (const raw of patch.split('\n')) {
|
|
132
|
+
const hunk = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(raw)
|
|
133
|
+
if (hunk !== null) {
|
|
134
|
+
left = Number(hunk[1])
|
|
135
|
+
right = Number(hunk[2])
|
|
136
|
+
continue
|
|
137
|
+
}
|
|
138
|
+
if (raw.startsWith('+++') || raw.startsWith('---')) continue
|
|
139
|
+
if (raw.startsWith('+')) {
|
|
140
|
+
anchors.add(anchorKey(path, right, 'RIGHT'))
|
|
141
|
+
right += 1
|
|
142
|
+
} else if (raw.startsWith('-')) {
|
|
143
|
+
anchors.add(anchorKey(path, left, 'LEFT'))
|
|
144
|
+
left += 1
|
|
145
|
+
} else if (raw.startsWith(' ')) {
|
|
146
|
+
anchors.add(anchorKey(path, right, 'RIGHT'))
|
|
147
|
+
left += 1
|
|
148
|
+
right += 1
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function partitionComments(
|
|
154
|
+
comments: readonly ReviewFinding[],
|
|
155
|
+
anchors: ReadonlySet<string>,
|
|
156
|
+
): { inline: ReviewFinding[]; reanchored: ReviewFinding[] } {
|
|
157
|
+
const inline: ReviewFinding[] = []
|
|
158
|
+
const reanchored: ReviewFinding[] = []
|
|
159
|
+
for (const comment of comments) {
|
|
160
|
+
const side = comment.side ?? 'RIGHT'
|
|
161
|
+
const lineOk = anchors.has(anchorKey(comment.path, comment.line, side))
|
|
162
|
+
const startSide = comment.startSide ?? side
|
|
163
|
+
const rangePaired = (comment.startLine === undefined) === (comment.startSide === undefined)
|
|
164
|
+
const startOk =
|
|
165
|
+
rangePaired &&
|
|
166
|
+
(comment.startLine === undefined ||
|
|
167
|
+
(startSide === side &&
|
|
168
|
+
comment.startLine <= comment.line &&
|
|
169
|
+
anchors.has(anchorKey(comment.path, comment.startLine, startSide))))
|
|
170
|
+
;(lineOk && startOk ? inline : reanchored).push(comment)
|
|
171
|
+
}
|
|
172
|
+
return { inline, reanchored }
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function appendReanchored(body: string, reanchored: readonly ReviewFinding[]): string {
|
|
176
|
+
if (reanchored.length === 0) return body
|
|
177
|
+
const findings = reanchored
|
|
178
|
+
.map((finding) => `- ${finding.path}:${finding.line} (${finding.side ?? 'RIGHT'}): ${finding.body}`)
|
|
179
|
+
.join('\n')
|
|
180
|
+
return `${body}\n\nOut-of-diff findings moved from inline comments:\n${findings}`
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
async function postReview(
|
|
184
|
+
fetchImpl: typeof fetch,
|
|
185
|
+
token: string,
|
|
186
|
+
target: ReviewTarget,
|
|
187
|
+
review: { event: SubmitReviewRequest['event']; body: string; commitId: string; comments: ReviewFinding[] },
|
|
188
|
+
): Promise<{ ok: true; reviewId: number } | (SubmitReviewResult & { ok: false })> {
|
|
189
|
+
const response = await githubFetch(fetchImpl, token, `${pullUrl(target)}/reviews`, {
|
|
190
|
+
method: 'POST',
|
|
191
|
+
body: JSON.stringify({
|
|
192
|
+
event: review.event,
|
|
193
|
+
body: review.body,
|
|
194
|
+
commit_id: review.commitId,
|
|
195
|
+
comments: review.comments.map(toGithubComment),
|
|
196
|
+
}),
|
|
197
|
+
})
|
|
198
|
+
if (!response.ok) return responseError(response, 'GitHub review submit')
|
|
199
|
+
const posted = await readJson<{ id?: unknown }>(response)
|
|
200
|
+
if (typeof posted?.id !== 'number') {
|
|
201
|
+
return { ok: false, error: 'GitHub review submit response missing review id', code: 'transient' }
|
|
202
|
+
}
|
|
203
|
+
return { ok: true, reviewId: posted.id }
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function toGithubComment(comment: ReviewFinding): Record<string, unknown> {
|
|
207
|
+
return {
|
|
208
|
+
path: comment.path,
|
|
209
|
+
line: comment.line,
|
|
210
|
+
side: comment.side ?? 'RIGHT',
|
|
211
|
+
body: comment.body,
|
|
212
|
+
...(comment.startLine !== undefined && comment.startSide !== undefined
|
|
213
|
+
? { start_line: comment.startLine, start_side: comment.startSide }
|
|
214
|
+
: {}),
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
async function verifyReview(
|
|
219
|
+
fetchImpl: typeof fetch,
|
|
220
|
+
token: string,
|
|
221
|
+
target: ReviewTarget,
|
|
222
|
+
reviewId: number,
|
|
223
|
+
event: SubmitReviewRequest['event'],
|
|
224
|
+
): Promise<{ ok: true; reviewId: number; state: string } | (SubmitReviewResult & { ok: false })> {
|
|
225
|
+
const response = await githubFetch(fetchImpl, token, `${pullUrl(target)}/reviews/${reviewId}`)
|
|
226
|
+
if (!response.ok) return responseError(response, 'GitHub review verify')
|
|
227
|
+
const body = await readJson<{ id?: unknown; state?: unknown }>(response)
|
|
228
|
+
const expectedState =
|
|
229
|
+
event === 'APPROVE' ? 'APPROVED' : event === 'REQUEST_CHANGES' ? 'CHANGES_REQUESTED' : 'COMMENTED'
|
|
230
|
+
if (body?.id !== reviewId || body.state !== expectedState) {
|
|
231
|
+
return {
|
|
232
|
+
ok: false,
|
|
233
|
+
error: 'GitHub review verification response did not match the posted review',
|
|
234
|
+
code: 'transient',
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return { ok: true, reviewId, state: expectedState }
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async function githubFetch(
|
|
241
|
+
fetchImpl: typeof fetch,
|
|
242
|
+
token: string,
|
|
243
|
+
url: string,
|
|
244
|
+
init: RequestInit = {},
|
|
245
|
+
): Promise<Response> {
|
|
246
|
+
try {
|
|
247
|
+
return await fetchImpl(url, { ...init, headers: { ...githubJsonHeaders(token), ...headersRecord(init.headers) } })
|
|
248
|
+
} catch (error) {
|
|
249
|
+
return new Response(error instanceof Error ? error.message : String(error), { status: 599 })
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
async function readJson<T>(response: Response): Promise<T | null> {
|
|
254
|
+
try {
|
|
255
|
+
return (await response.json()) as T
|
|
256
|
+
} catch (error) {
|
|
257
|
+
void error
|
|
258
|
+
return null
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function headersRecord(headers: HeadersInit | undefined): Record<string, string> {
|
|
263
|
+
if (headers === undefined) return {}
|
|
264
|
+
if (headers instanceof Headers) return Object.fromEntries(headers.entries())
|
|
265
|
+
if (Array.isArray(headers)) return Object.fromEntries(headers)
|
|
266
|
+
return headers
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async function responseError(response: Response, label: string): Promise<SubmitReviewResult & { ok: false }> {
|
|
270
|
+
const text = await response.text()
|
|
271
|
+
return {
|
|
272
|
+
ok: false,
|
|
273
|
+
error: `${label} ${response.status}${text !== '' ? `: ${text}` : ''}`,
|
|
274
|
+
code: response.status === 422 ? 'bad-anchor' : classifyStatus(response.status),
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function classifyStatus(status: number): SubmitReviewErrorCode {
|
|
279
|
+
if (status === 401 || status === 403) return 'permission-denied'
|
|
280
|
+
if (status === 404) return 'not-found'
|
|
281
|
+
return 'transient'
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function nextLink(header: string | null): string | null {
|
|
285
|
+
if (header === null) return null
|
|
286
|
+
for (const part of header.split(',')) {
|
|
287
|
+
const match = /<([^>]+)>;\s*rel="next"/.exec(part)
|
|
288
|
+
if (match !== null) return match[1] ?? null
|
|
289
|
+
}
|
|
290
|
+
return null
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function pullUrl(target: ReviewTarget): string {
|
|
294
|
+
return `${GITHUB_API_BASE}/repos/${target.owner}/${target.repo}/pulls/${target.prNumber}`
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function anchorKey(path: string, line: number, side: 'LEFT' | 'RIGHT'): string {
|
|
298
|
+
return `${path}\0${side}\0${line}`
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
type PullResponse = { head?: { sha?: unknown } }
|
|
302
|
+
type PullFilesResponse = Array<{ filename?: unknown; patch?: unknown }>
|
|
@@ -17,9 +17,11 @@ export type KakaoChatLookupValue = {
|
|
|
17
17
|
isDm: boolean
|
|
18
18
|
// True while the entry is a placeholder from `ingestProvisional` (a chat seen
|
|
19
19
|
// on an inbound push but not yet surfaced by getChats). Its `workspace` is a
|
|
20
|
-
// strict-bucket guess (@kakao-group), NOT the authoritative kind
|
|
21
|
-
//
|
|
22
|
-
//
|
|
20
|
+
// strict-bucket guess (@kakao-group), NOT the authoritative kind. Callers that
|
|
21
|
+
// must know the real type decide per-feature: typing sends for provisional
|
|
22
|
+
// entries (the @kakao-group guess is never @kakao-open, and a mis-guessed
|
|
23
|
+
// OpenChat's linkless ACTION fails soft), while allow-rule enforcement keeps
|
|
24
|
+
// treating the strict bucket as authoritative until a real refresh upgrades it.
|
|
23
25
|
provisional: boolean
|
|
24
26
|
}
|
|
25
27
|
|
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_ATTACHMENT_MAX_BYTES,
|
|
3
|
+
readAttachmentErrorSnippet,
|
|
4
|
+
readAttachmentResponse,
|
|
5
|
+
} from '@/channels/fetch-attachment'
|
|
1
6
|
import type { FetchAttachmentCallback } from '@/channels/types'
|
|
2
7
|
|
|
3
8
|
import type { KakaotalkAdapterLogger } from './kakaotalk'
|
|
@@ -21,7 +26,7 @@ export function createFetchAttachmentCallback(deps: {
|
|
|
21
26
|
}): FetchAttachmentCallback {
|
|
22
27
|
const { logger } = deps
|
|
23
28
|
const fetchImpl = deps.fetchImpl ?? fetch
|
|
24
|
-
return async ({ ref, filename }) => {
|
|
29
|
+
return async ({ ref, filename, maxBytes = DEFAULT_ATTACHMENT_MAX_BYTES }) => {
|
|
25
30
|
let url: URL
|
|
26
31
|
try {
|
|
27
32
|
url = new URL(ref)
|
|
@@ -37,7 +42,7 @@ export function createFetchAttachmentCallback(deps: {
|
|
|
37
42
|
try {
|
|
38
43
|
const res = await fetchImpl(url.toString())
|
|
39
44
|
if (!res.ok) {
|
|
40
|
-
const body = await res
|
|
45
|
+
const body = await readAttachmentErrorSnippet(res)
|
|
41
46
|
// 403 from kakaocdn almost always means the pre-signed URL expired
|
|
42
47
|
// (the `expires=` query param has a fixed TTL — empirically ~3
|
|
43
48
|
// days from the push event). Surfacing that distinction lets the
|
|
@@ -49,8 +54,7 @@ export function createFetchAttachmentCallback(deps: {
|
|
|
49
54
|
logger.error(`[kakaotalk] fetchAttachment failed for ${url.toString()}: ${message}`)
|
|
50
55
|
return { ok: false, error: message }
|
|
51
56
|
}
|
|
52
|
-
const
|
|
53
|
-
const buffer = Buffer.from(arrayBuffer)
|
|
57
|
+
const buffer = await readAttachmentResponse(res, maxBytes)
|
|
54
58
|
const inferredFilename = filename ?? deriveFilename(url) ?? 'attachment'
|
|
55
59
|
const contentType = res.headers.get('content-type') ?? undefined
|
|
56
60
|
logger.info(
|
|
@@ -30,23 +30,24 @@ export type KakaoTypingCallbackHandle = {
|
|
|
30
30
|
// expiry even with scheduler/network jitter (a 5000ms interval has no margin).
|
|
31
31
|
export const KAKAO_TYPING_HEARTBEAT_MS = 4000
|
|
32
32
|
|
|
33
|
-
// Per-chat send decision, resolved live at each tick
|
|
34
|
-
//
|
|
35
|
-
//
|
|
36
|
-
//
|
|
37
|
-
//
|
|
38
|
-
//
|
|
39
|
-
//
|
|
40
|
-
//
|
|
41
|
-
//
|
|
42
|
-
//
|
|
43
|
-
//
|
|
33
|
+
// Per-chat send decision, resolved live at each tick:
|
|
34
|
+
// send — authoritative DM/group, OR provisional. Emit the packet.
|
|
35
|
+
// skip-open — confirmed OpenChat; the LOCO ACTION needs a `linkId` the
|
|
36
|
+
// resolver does not surface today (logged once).
|
|
37
|
+
// skip-unresolved — chat unknown to the resolver; skip silently.
|
|
38
|
+
//
|
|
39
|
+
// Provisional entries send on purpose. A chat getChats never surfaces (e.g. a
|
|
40
|
+
// stale sub-device session returns a partial list) stays provisional forever, so
|
|
41
|
+
// skipping it disabled typing for exactly the chats a user actively messages. The
|
|
42
|
+
// inbound push proves the chat is real; the provisional bucket is @kakao-group
|
|
43
|
+
// (never @kakao-open), and a provisional-that-is-actually-OpenChat fails soft —
|
|
44
|
+
// sendTyping throws on non-success and the callback swallows it as a warn.
|
|
44
45
|
export type KakaoTypingChatClass = 'send' | 'skip-open' | 'skip-unresolved'
|
|
45
46
|
|
|
46
47
|
export function kakaoTypingClassFromLookup(
|
|
47
48
|
lookup: { workspace: string; provisional: boolean } | null,
|
|
48
49
|
): KakaoTypingChatClass {
|
|
49
|
-
if (lookup === null
|
|
50
|
+
if (lookup === null) return 'skip-unresolved'
|
|
50
51
|
if (lookup.workspace === '@kakao-open') return 'skip-open'
|
|
51
52
|
return 'send'
|
|
52
53
|
}
|
|
@@ -54,9 +55,10 @@ export function kakaoTypingClassFromLookup(
|
|
|
54
55
|
export function createKakaoTypingCallback(deps: {
|
|
55
56
|
logger: KakaoTypingLogger
|
|
56
57
|
sendTyping: KakaoTypingSender
|
|
57
|
-
// Live per-chat classifier — consults the channel resolver at send time
|
|
58
|
-
//
|
|
59
|
-
// session key was minted
|
|
58
|
+
// Live per-chat classifier — consults the channel resolver at send time, not
|
|
59
|
+
// the (stale) session-key target: an unknown room is skipped, a room confirmed
|
|
60
|
+
// as OpenChat after the session key was minted is skipped, and a provisional or
|
|
61
|
+
// authoritative DM/group room sends.
|
|
60
62
|
classifyChat: (chatId: string) => KakaoTypingChatClass
|
|
61
63
|
formatChannelTag?: (workspace: string, chat: string) => Promise<string>
|
|
62
64
|
}): KakaoTypingCallbackHandle {
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import {
|
|
2
|
+
discardAttachmentResponse,
|
|
3
|
+
readAttachmentErrorSnippet,
|
|
4
|
+
readAttachmentResponse,
|
|
5
|
+
} from '@/channels/fetch-attachment'
|
|
6
|
+
|
|
7
|
+
const MAX_SLACK_REDIRECTS = 5
|
|
8
|
+
const SLACK_DOWNLOAD_HOSTS = ['slack.com', 'slack-edge.com', 'slack-files.com'] as const
|
|
9
|
+
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308])
|
|
10
|
+
|
|
11
|
+
export type SlackDownloadMetadata = {
|
|
12
|
+
name?: string
|
|
13
|
+
mimetype?: string
|
|
14
|
+
size?: number
|
|
15
|
+
url_private?: string
|
|
16
|
+
url_private_download?: string
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type SlackAttachmentFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
|
|
20
|
+
|
|
21
|
+
export async function downloadSlackAttachment(options: {
|
|
22
|
+
metadata: SlackDownloadMetadata
|
|
23
|
+
token: string
|
|
24
|
+
cookie?: string
|
|
25
|
+
maxBytes: number
|
|
26
|
+
fetchImpl?: SlackAttachmentFetch
|
|
27
|
+
}): Promise<{ buffer: Buffer; url: URL }> {
|
|
28
|
+
const rawUrl = options.metadata.url_private_download ?? options.metadata.url_private
|
|
29
|
+
if (rawUrl === undefined || rawUrl === '') throw new Error('Slack file metadata has no private download URL')
|
|
30
|
+
const fetchImpl = options.fetchImpl ?? fetch
|
|
31
|
+
let url = parseTrustedSlackUrl(rawUrl)
|
|
32
|
+
|
|
33
|
+
for (let redirects = 0; ; redirects++) {
|
|
34
|
+
const response = await fetchImpl(url, {
|
|
35
|
+
headers: {
|
|
36
|
+
Authorization: `Bearer ${options.token}`,
|
|
37
|
+
...(options.cookie === undefined ? {} : { Cookie: `d=${options.cookie}` }),
|
|
38
|
+
},
|
|
39
|
+
redirect: 'manual',
|
|
40
|
+
})
|
|
41
|
+
if (REDIRECT_STATUSES.has(response.status)) {
|
|
42
|
+
await discardAttachmentResponse(response)
|
|
43
|
+
if (redirects >= MAX_SLACK_REDIRECTS) throw new Error('Slack attachment redirect limit exceeded')
|
|
44
|
+
const location = response.headers.get('location')
|
|
45
|
+
if (location === null) throw new Error('Slack attachment redirect omitted Location')
|
|
46
|
+
url = parseTrustedSlackUrl(new URL(location, url).toString())
|
|
47
|
+
continue
|
|
48
|
+
}
|
|
49
|
+
if (!response.ok) {
|
|
50
|
+
const snippet = await readAttachmentErrorSnippet(response)
|
|
51
|
+
throw new Error(`Slack attachment download failed (${response.status})${snippet === '' ? '' : `: ${snippet}`}`)
|
|
52
|
+
}
|
|
53
|
+
const contentType = response.headers.get('content-type')?.toLocaleLowerCase() ?? ''
|
|
54
|
+
if (contentType.includes('text/html') || contentType.includes('application/xhtml+xml')) {
|
|
55
|
+
await discardAttachmentResponse(response)
|
|
56
|
+
throw new Error('Slack attachment download returned an HTML login response')
|
|
57
|
+
}
|
|
58
|
+
return { buffer: await readAttachmentResponse(response, options.maxBytes), url }
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function parseTrustedSlackUrl(raw: string): URL {
|
|
63
|
+
const url = new URL(raw)
|
|
64
|
+
if (
|
|
65
|
+
url.protocol !== 'https:' ||
|
|
66
|
+
!SLACK_DOWNLOAD_HOSTS.some((host) => url.hostname === host || url.hostname.endsWith(`.${host}`))
|
|
67
|
+
) {
|
|
68
|
+
throw new Error(`refusing untrusted Slack attachment URL host: ${url.hostname}`)
|
|
69
|
+
}
|
|
70
|
+
return url
|
|
71
|
+
}
|
|
@@ -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
|
-
}
|