typeclaw 0.48.12 → 0.49.0
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/package.json +6 -3
- package/scripts/dump-system-prompt.ts +52 -110
- package/src/agent/attention-escalation.ts +8 -5
- package/src/agent/auth-reloadable.ts +2 -3
- package/src/agent/auth.ts +59 -79
- package/src/agent/compaction.ts +2 -2
- package/src/agent/index.ts +173 -85
- package/src/agent/live-sessions.ts +2 -2
- package/src/agent/live-subagents.ts +1 -0
- package/src/agent/llm-replay-sanitizer.ts +1 -1
- package/src/agent/model-overrides.ts +1 -1
- package/src/agent/multimodal/look-at.ts +3 -3
- package/src/agent/multimodal/read-redirect.ts +1 -1
- package/src/agent/plugin-tools.ts +76 -39
- package/src/agent/prompt-cache-key.ts +42 -0
- package/src/agent/provider-error.ts +179 -10
- package/src/agent/reload-tool.ts +1 -1
- package/src/agent/restart-handoff/index.ts +7 -14
- package/src/agent/reviewer-activity.ts +68 -0
- package/src/agent/session-origin.ts +33 -0
- package/src/agent/subagents.ts +14 -2
- package/src/agent/system-prompt.ts +68 -202
- package/src/agent/todo/continuation-policy.ts +12 -4
- package/src/agent/tool-error-remediation.ts +1 -1
- package/src/agent/tool-file-safety.ts +113 -14
- package/src/agent/tool-not-found-nudge.ts +1 -1
- package/src/agent/tool-result-budget.ts +2 -2
- package/src/agent/tools/channel-disengage.ts +2 -2
- package/src/agent/tools/channel-edit.ts +2 -2
- package/src/agent/tools/channel-fetch-attachment.ts +2 -2
- package/src/agent/tools/channel-history-render.ts +2 -1
- package/src/agent/tools/channel-history.ts +2 -2
- package/src/agent/tools/channel-react.ts +2 -2
- package/src/agent/tools/channel-read.ts +2 -2
- package/src/agent/tools/channel-reply.ts +25 -7
- package/src/agent/tools/channel-send.ts +51 -9
- package/src/agent/tools/curl-impersonate.ts +11 -2
- package/src/agent/tools/grant-role.ts +2 -2
- package/src/agent/tools/post-github-review.ts +79 -17
- package/src/agent/tools/restart.ts +2 -2
- package/src/agent/tools/skip-response.ts +4 -4
- package/src/agent/tools/spawn-subagent.ts +165 -14
- package/src/agent/tools/stream-snapshot.ts +2 -2
- package/src/agent/tools/subagent-cancel.ts +2 -2
- package/src/agent/tools/subagent-output.ts +10 -2
- package/src/agent/tools/todo/index.ts +2 -2
- package/src/agent/tools/webfetch/tool.ts +2 -2
- package/src/agent/tools/websearch.ts +2 -2
- package/src/bundled-plugins/backup/README.md +10 -9
- package/src/bundled-plugins/backup/runner.ts +140 -58
- package/src/bundled-plugins/backup/subagents.ts +58 -26
- package/src/bundled-plugins/github-cli-auth/gh-command.ts +34 -2
- package/src/bundled-plugins/github-cli-auth/granted-push.ts +135 -0
- package/src/bundled-plugins/github-cli-auth/index.ts +83 -11
- package/src/bundled-plugins/github-cli-auth/review-account.ts +23 -0
- package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -2
- package/src/bundled-plugins/github-cli-auth/review-recorder.ts +45 -7
- package/src/bundled-plugins/operator/operator.ts +15 -4
- package/src/bundled-plugins/reviewer/skills/code-review.ts +1 -1
- package/src/bundled-plugins/security/index.ts +50 -2
- package/src/bundled-plugins/security/policies/git-exfil.ts +24 -12
- package/src/channels/adapters/discord-bot-reactions.ts +18 -0
- package/src/channels/adapters/discord-bot.ts +122 -67
- package/src/channels/adapters/discord-reactions.ts +18 -0
- package/src/channels/adapters/discord.ts +114 -8
- package/src/channels/adapters/github/inbound.ts +103 -8
- package/src/channels/adapters/github/index.ts +251 -19
- package/src/channels/adapters/github/last-alive.ts +27 -0
- package/src/channels/adapters/github/outbound.ts +54 -18
- package/src/channels/adapters/github/pending-review-store.ts +141 -0
- package/src/channels/adapters/github/permission-guidance.ts +1 -0
- package/src/channels/adapters/github/reactions.ts +100 -0
- package/src/channels/adapters/github/reconcile-cooldown-store.ts +197 -67
- package/src/channels/adapters/github/reconcile-open-prs.ts +418 -33
- package/src/channels/adapters/github/recovery.ts +106 -0
- package/src/channels/adapters/github/review-check.ts +510 -0
- package/src/channels/adapters/github/review-submitter.ts +34 -2
- package/src/channels/adapters/instagram.ts +32 -14
- package/src/channels/adapters/kakaotalk.ts +22 -7
- package/src/channels/adapters/line.ts +18 -3
- package/src/channels/adapters/outbound-account.ts +20 -0
- package/src/channels/adapters/own-reactions.ts +66 -0
- package/src/channels/adapters/recovery-correlation.ts +214 -0
- package/src/channels/adapters/slack-bot-classify.ts +18 -11
- package/src/channels/adapters/slack-bot-dedupe.ts +111 -28
- package/src/channels/adapters/slack-bot-reactions.ts +18 -0
- package/src/channels/adapters/slack-bot.ts +125 -57
- package/src/channels/adapters/slack-classify.ts +25 -4
- package/src/channels/adapters/slack-inbound-revision.ts +96 -0
- package/src/channels/adapters/slack-reactions.ts +18 -0
- package/src/channels/adapters/slack-thread-ts.ts +6 -0
- package/src/channels/adapters/slack.ts +48 -3
- package/src/channels/adapters/teams.ts +14 -4
- package/src/channels/adapters/telegram-bot.ts +56 -10
- package/src/channels/adapters/webex-bot.ts +12 -2
- package/src/channels/adapters/webex.ts +12 -2
- package/src/channels/background-handoff.ts +434 -0
- package/src/channels/background-obligations.ts +893 -0
- package/src/channels/continuity-types.ts +271 -0
- package/src/channels/github-review-check.ts +598 -0
- package/src/channels/github-review-turn-ledger.ts +102 -28
- package/src/channels/github-review-verdict-coordinator.ts +96 -13
- package/src/channels/github-token-bridge.ts +11 -5
- package/src/channels/inbound-journal.ts +1738 -0
- package/src/channels/index.ts +6 -1
- package/src/channels/manager.ts +17 -7
- package/src/channels/recovery-dispatcher.ts +264 -0
- package/src/channels/recovery-notice.ts +94 -0
- package/src/channels/recovery-outbox.ts +459 -0
- package/src/channels/router.ts +2582 -633
- package/src/channels/schema.ts +8 -1
- package/src/channels/subagent-completion-bridge.ts +17 -14
- package/src/channels/types.ts +121 -16
- package/src/channels/waiting-reactions.ts +664 -0
- package/src/cli/compose.ts +7 -4
- package/src/cli/hostd.ts +49 -3
- package/src/cli/inspect.ts +11 -14
- package/src/cli/model.ts +7 -5
- package/src/cli/oauth-callbacks.ts +38 -23
- package/src/coding-agent/broker-body.ts +38 -0
- package/src/coding-agent/broker.ts +290 -0
- package/src/coding-agent/claude.ts +95 -0
- package/src/coding-agent/codex.ts +104 -0
- package/src/coding-agent/index.ts +506 -0
- package/src/coding-agent/omo-state.ts +69 -0
- package/src/coding-agent/omo-stream.ts +98 -0
- package/src/coding-agent/omo.ts +192 -0
- package/src/coding-agent/runner.ts +263 -0
- package/src/coding-agent/tool.ts +62 -0
- package/src/coding-agent/worktree.ts +355 -0
- package/src/compose/restart.ts +10 -3
- package/src/compose/start.ts +20 -3
- package/src/config/config.ts +70 -26
- package/src/config/providers.ts +278 -50
- package/src/container/exit-reason.ts +44 -0
- package/src/container/index.ts +5 -0
- package/src/container/log-archive.ts +51 -13
- package/src/container/memory-limit.ts +1 -1
- package/src/container/memory-oversubscription.ts +36 -6
- package/src/container/oom-events.ts +86 -0
- package/src/container/restart.ts +2 -0
- package/src/container/shared.ts +8 -1
- package/src/container/start.ts +25 -13
- package/src/container/stop.ts +6 -2
- package/src/container/tool-oom-priority.ts +32 -0
- package/src/cron/consumer.ts +10 -4
- package/src/cron/reloadable.ts +23 -2
- package/src/doctor/checks.ts +14 -2
- package/src/hostd/daemon.ts +20 -10
- package/src/hostd/spawn.ts +106 -5
- package/src/hostd/version.ts +20 -0
- package/src/hostd/watchdog.ts +241 -0
- package/src/init/dockerfile.ts +57 -592
- package/src/init/index.ts +6 -7
- package/src/init/oauth-login.ts +57 -17
- package/src/inspect/transcript-view.ts +6 -3
- package/src/mcp/client.ts +3 -1
- package/src/operations/classify-tool-outcome.ts +45 -1
- package/src/operations/incidents.ts +10 -5
- package/src/plugin/core-tool-names.ts +1 -1
- package/src/plugin/define.ts +1 -0
- package/src/plugin/index.ts +1 -0
- package/src/plugin/types.ts +6 -1
- package/src/run/background-handoff-boot.ts +86 -0
- package/src/run/channel-session-factory.ts +5 -4
- package/src/run/index.ts +93 -93
- package/src/run/resource-sample.ts +19 -0
- package/src/sandbox/build.ts +4 -0
- package/src/sandbox/coding-agent.ts +214 -0
- package/src/sandbox/policy.ts +1 -0
- package/src/sandbox/runtime-private.ts +4 -1
- package/src/secrets/coding-agent-auth.ts +97 -0
- package/src/secrets/index.ts +0 -16
- package/src/secrets/refresh-provider-oauth.ts +30 -76
- package/src/secrets/schema.ts +3 -4
- package/src/secrets/storage.ts +133 -234
- package/src/server/command-runner.ts +6 -2
- package/src/server/index.ts +102 -41
- package/src/sessions/index.ts +1 -1
- package/src/skills/typeclaw-channel-github/SKILL.md +7 -5
- package/src/skills/typeclaw-claude-code/SKILL.md +25 -260
- package/src/skills/typeclaw-claude-code/references/auth-flow.md +7 -23
- package/src/skills/typeclaw-claude-code/references/headless-sessions.md +11 -0
- package/src/skills/typeclaw-claude-code/references/results-and-worktrees.md +13 -0
- package/src/skills/typeclaw-codex-cli/SKILL.md +35 -270
- package/src/skills/typeclaw-codex-cli/references/auth-flow.md +13 -20
- package/src/skills/typeclaw-codex-cli/references/headless-sessions.md +26 -0
- package/src/skills/typeclaw-codex-cli/references/results-and-worktrees.md +28 -0
- package/src/skills/typeclaw-config/SKILL.md +24 -24
- package/src/skills/typeclaw-config/references/dockerfile.md +14 -13
- package/src/skills/typeclaw-cron/SKILL.md +1 -1
- package/src/skills/typeclaw-github-contributing/SKILL.md +2 -2
- package/src/skills/typeclaw-memory/SKILL.md +3 -3
- package/src/skills/typeclaw-omo-cli/SKILL.md +52 -0
- package/src/skills/typeclaw-omo-cli/references/auth-flow.md +11 -0
- package/src/skills/typeclaw-omo-cli/references/headless-sessions.md +11 -0
- package/src/skills/typeclaw-omo-cli/references/results-and-worktrees.md +23 -0
- package/src/skills/typeclaw-plugins/SKILL.md +20 -20
- package/src/skills/typeclaw-skills/SKILL.md +19 -2
- package/src/skills/typeclaw-troubleshooting/SKILL.md +15 -2
- package/src/tui/index.ts +5 -3
- package/src/tui/theme.ts +1 -1
- package/typeclaw.schema.json +44 -2
- package/src/agent/adaptive-thinking-compat.ts +0 -79
- package/src/secrets/claude-credentials-json.ts +0 -129
- package/src/secrets/codex-auth-json.ts +0 -102
- package/src/secrets/export-claude-credentials-file.ts +0 -270
- package/src/secrets/export-codex-auth-file.ts +0 -250
- package/src/secrets/oauth-xai.ts +0 -348
- package/src/skills/typeclaw-claude-code/references/stop-hook.md +0 -101
- package/src/skills/typeclaw-claude-code/references/tmux-driving.md +0 -243
- package/src/skills/typeclaw-codex-cli/references/stop-hook.md +0 -92
- package/src/skills/typeclaw-codex-cli/references/tmux-driving.md +0 -239
|
@@ -27,6 +27,15 @@ export function invalidateGithubReviewSubmission(workspace: string, prNumber: nu
|
|
|
27
27
|
export function createGithubReviewSubmitter(deps: {
|
|
28
28
|
token: (context?: GithubAuthContext) => Promise<string>
|
|
29
29
|
allowApprove: () => boolean
|
|
30
|
+
accountIdentity?: () => Promise<string | undefined>
|
|
31
|
+
onReviewPosted?: (posted: {
|
|
32
|
+
repo: string
|
|
33
|
+
prNumber: number
|
|
34
|
+
headSha: string
|
|
35
|
+
state: VerifiedReviewState
|
|
36
|
+
reviewId: number
|
|
37
|
+
comments: readonly ReviewFinding[]
|
|
38
|
+
}) => void | Promise<void>
|
|
30
39
|
fetchImpl?: typeof fetch
|
|
31
40
|
}): ReviewSubmitter {
|
|
32
41
|
const fetchImpl = deps.fetchImpl ?? fetch
|
|
@@ -45,10 +54,23 @@ export function createGithubReviewSubmitter(deps: {
|
|
|
45
54
|
const token = await deps.token({ repoSlug: `${target.owner}/${target.repo}` })
|
|
46
55
|
const stable = await fetchStableAnchors(fetchImpl, token, target)
|
|
47
56
|
if (!stable.ok) return stable
|
|
57
|
+
if (
|
|
58
|
+
req.expectedHeadSha !== undefined &&
|
|
59
|
+
req.expectedHeadSha.toLocaleLowerCase() !== stable.headSha.toLocaleLowerCase()
|
|
60
|
+
) {
|
|
61
|
+
return {
|
|
62
|
+
ok: false,
|
|
63
|
+
error: `GitHub pull request head is ${stable.headSha}, not the reviewed commit ${req.expectedHeadSha}; re-review the current head before submitting`,
|
|
64
|
+
code: 'transient',
|
|
65
|
+
}
|
|
66
|
+
}
|
|
48
67
|
|
|
49
68
|
const { inline, reanchored } = partitionComments(req.comments, stable.anchors)
|
|
50
69
|
const downgraded = req.event === 'APPROVE' && !deps.allowApprove()
|
|
51
70
|
const event = downgraded ? 'COMMENT' : req.event
|
|
71
|
+
if (req.expectedAccountIdentity !== undefined && (await deps.accountIdentity?.()) !== req.expectedAccountIdentity) {
|
|
72
|
+
return { ok: false, error: 'GitHub review account identity changed or unavailable', code: 'permission-denied' }
|
|
73
|
+
}
|
|
52
74
|
if (currentReviewSubmissionGeneration(req.workspace, target.prNumber) !== submissionGeneration) {
|
|
53
75
|
return {
|
|
54
76
|
ok: false,
|
|
@@ -68,10 +90,19 @@ export function createGithubReviewSubmitter(deps: {
|
|
|
68
90
|
if (!posted.ok) return posted
|
|
69
91
|
const verified = await verifyReview(fetchImpl, token, target, posted.reviewId, event)
|
|
70
92
|
if (!verified.ok) return { ...verified, submitted: true }
|
|
93
|
+
await deps.onReviewPosted?.({
|
|
94
|
+
repo: `${target.owner}/${target.repo}`,
|
|
95
|
+
prNumber: target.prNumber,
|
|
96
|
+
headSha: stable.headSha,
|
|
97
|
+
state: verified.state,
|
|
98
|
+
reviewId: verified.reviewId,
|
|
99
|
+
comments: req.comments,
|
|
100
|
+
})
|
|
71
101
|
return {
|
|
72
102
|
ok: true,
|
|
73
103
|
reviewId: verified.reviewId,
|
|
74
104
|
state: verified.state,
|
|
105
|
+
commitSha: stable.headSha,
|
|
75
106
|
...(downgraded ? { downgraded: true } : {}),
|
|
76
107
|
...(reanchored.length > 0 ? { reanchored } : {}),
|
|
77
108
|
}
|
|
@@ -249,11 +280,11 @@ async function verifyReview(
|
|
|
249
280
|
target: ReviewTarget,
|
|
250
281
|
reviewId: number,
|
|
251
282
|
event: SubmitReviewRequest['event'],
|
|
252
|
-
): Promise<{ ok: true; reviewId: number; state:
|
|
283
|
+
): Promise<{ ok: true; reviewId: number; state: VerifiedReviewState } | (SubmitReviewResult & { ok: false })> {
|
|
253
284
|
const response = await githubFetch(fetchImpl, token, `${pullUrl(target)}/reviews/${reviewId}`)
|
|
254
285
|
if (!response.ok) return responseError(response, 'GitHub review verify')
|
|
255
286
|
const body = await readJson<{ id?: unknown; state?: unknown }>(response)
|
|
256
|
-
const expectedState =
|
|
287
|
+
const expectedState: VerifiedReviewState =
|
|
257
288
|
event === 'APPROVE' ? 'APPROVED' : event === 'REQUEST_CHANGES' ? 'CHANGES_REQUESTED' : 'COMMENTED'
|
|
258
289
|
if (body?.id !== reviewId || body.state !== expectedState) {
|
|
259
290
|
return {
|
|
@@ -326,5 +357,6 @@ function anchorKey(path: string, line: number, side: 'LEFT' | 'RIGHT'): string {
|
|
|
326
357
|
return `${path}\0${side}\0${line}`
|
|
327
358
|
}
|
|
328
359
|
|
|
360
|
+
type VerifiedReviewState = 'APPROVED' | 'CHANGES_REQUESTED' | 'COMMENTED'
|
|
329
361
|
type PullResponse = { head?: { sha?: unknown } }
|
|
330
362
|
type PullFilesResponse = Array<{ filename?: unknown; patch?: unknown }>
|
|
@@ -8,7 +8,9 @@ import type { InstagramChatSummary, InstagramMessageSummary } from 'agent-messen
|
|
|
8
8
|
|
|
9
9
|
import type { ChannelRouter } from '@/channels/router'
|
|
10
10
|
import type { ChannelAdapterConfig } from '@/channels/schema'
|
|
11
|
+
import { fallbackChannelAccountIdentity } from '@/channels/types'
|
|
11
12
|
import type {
|
|
13
|
+
ChannelSelfIdentityResolver,
|
|
12
14
|
ChannelHistoryMessage,
|
|
13
15
|
FetchHistoryArgs,
|
|
14
16
|
FetchHistoryResult,
|
|
@@ -24,6 +26,7 @@ import { createInstagramChannelResolver } from './instagram-channel-resolver'
|
|
|
24
26
|
import { classifyInbound } from './instagram-classify'
|
|
25
27
|
import { loadInstagramContinuityStore, type InstagramContinuityStore } from './instagram-continuity-store'
|
|
26
28
|
import { toInstagramPlainText } from './instagram-format'
|
|
29
|
+
import { withOutboundAccount } from './outbound-account'
|
|
27
30
|
|
|
28
31
|
export interface InstagramClientShape {
|
|
29
32
|
login(credentials?: { username: string; password: string }, accountId?: string): Promise<this>
|
|
@@ -177,6 +180,7 @@ export function createInstagramAdapter(options: InstagramAdapterOptions): Instag
|
|
|
177
180
|
const client = options.client ?? buildClient(new InstagramCredentialManager())
|
|
178
181
|
let listener: InstagramListenerShape | null = null
|
|
179
182
|
let selfUserId: string | null = null
|
|
183
|
+
const selfIdentityResolver: ChannelSelfIdentityResolver = () => (selfUserId === null ? null : { id: selfUserId })
|
|
180
184
|
let connected = false
|
|
181
185
|
let started = false
|
|
182
186
|
let inflightInbounds = 0
|
|
@@ -199,9 +203,12 @@ export function createInstagramAdapter(options: InstagramAdapterOptions): Instag
|
|
|
199
203
|
}
|
|
200
204
|
|
|
201
205
|
const historyCallback = createInstagramHistoryCallback({ client, logger, selfUserIdRef: () => selfUserId })
|
|
202
|
-
const outboundCallback =
|
|
206
|
+
const outboundCallback = withOutboundAccount(
|
|
207
|
+
createOutboundCallback({ client, logger, formatChannelTag }),
|
|
208
|
+
(workspace) => fallbackChannelAccountIdentity('instagram', workspace, selfUserId),
|
|
209
|
+
)
|
|
203
210
|
|
|
204
|
-
const processInbound = async (message: InstagramMessageSummary): Promise<boolean> => {
|
|
211
|
+
const processInbound = async (message: InstagramMessageSummary, inboundSelfId: string | null): Promise<boolean> => {
|
|
205
212
|
inflightInbounds++
|
|
206
213
|
try {
|
|
207
214
|
if (channelResolver.lookupChat(message.thread_id) === null) {
|
|
@@ -221,7 +228,7 @@ export function createInstagramAdapter(options: InstagramAdapterOptions): Instag
|
|
|
221
228
|
)
|
|
222
229
|
|
|
223
230
|
const verdict = classifyInbound(message, options.configRef(), {
|
|
224
|
-
selfUserId,
|
|
231
|
+
selfUserId: inboundSelfId,
|
|
225
232
|
lookupChat: (id) => channelResolver.lookupChat(id),
|
|
226
233
|
...(options.selfAliasesRef ? { selfAliases: options.selfAliasesRef() } : {}),
|
|
227
234
|
})
|
|
@@ -233,8 +240,19 @@ export function createInstagramAdapter(options: InstagramAdapterOptions): Instag
|
|
|
233
240
|
logger.info(
|
|
234
241
|
`[instagram] routed message_id=${message.id} ${inboundTag} mention=${verdict.payload.isBotMention} dm=${verdict.payload.isDm}`,
|
|
235
242
|
)
|
|
236
|
-
await options.router.route(
|
|
237
|
-
|
|
243
|
+
const receipt = await options.router.route({
|
|
244
|
+
...verdict.payload,
|
|
245
|
+
accountIdentity: fallbackChannelAccountIdentity('instagram', verdict.payload.workspace, inboundSelfId),
|
|
246
|
+
eventKind: 'message',
|
|
247
|
+
revision: 'original',
|
|
248
|
+
})
|
|
249
|
+
return (
|
|
250
|
+
receipt.kind === 'accepted' ||
|
|
251
|
+
receipt.kind === 'duplicate' ||
|
|
252
|
+
receipt.kind === 'observed' ||
|
|
253
|
+
receipt.kind === 'denied' ||
|
|
254
|
+
receipt.kind === 'control'
|
|
255
|
+
)
|
|
238
256
|
} catch (err) {
|
|
239
257
|
logger.error(`[instagram] handleInbound failed: ${describeError(err)}`)
|
|
240
258
|
return false
|
|
@@ -248,23 +266,21 @@ export function createInstagramAdapter(options: InstagramAdapterOptions): Instag
|
|
|
248
266
|
}
|
|
249
267
|
}
|
|
250
268
|
|
|
251
|
-
const markDelivered = async (message: InstagramMessageSummary): Promise<void> => {
|
|
252
|
-
if (continuityStore === null || selfUserId === null) return
|
|
253
|
-
await continuityStore.markMessage(selfUserId, message.thread_id, message.id)
|
|
254
|
-
}
|
|
255
|
-
|
|
256
269
|
const deliverUnseen = async (message: InstagramMessageSummary): Promise<boolean> => {
|
|
270
|
+
const accountId = selfUserId
|
|
257
271
|
if (
|
|
258
272
|
continuityStore !== null &&
|
|
259
|
-
|
|
260
|
-
continuityStore.hasMessage(
|
|
273
|
+
accountId !== null &&
|
|
274
|
+
continuityStore.hasMessage(accountId, message.thread_id, message.id)
|
|
261
275
|
) {
|
|
262
276
|
return true
|
|
263
277
|
}
|
|
264
|
-
if (!(await processInbound(message))) return false
|
|
278
|
+
if (!(await processInbound(message, accountId))) return false
|
|
265
279
|
// Checkpoint only after the router accepts the message. A crash can replay
|
|
266
280
|
// once, but persisting first would silently lose a message when routing fails.
|
|
267
|
-
|
|
281
|
+
if (continuityStore !== null && accountId !== null) {
|
|
282
|
+
await continuityStore.markMessage(accountId, message.thread_id, message.id)
|
|
283
|
+
}
|
|
268
284
|
return true
|
|
269
285
|
}
|
|
270
286
|
|
|
@@ -452,6 +468,7 @@ export function createInstagramAdapter(options: InstagramAdapterOptions): Instag
|
|
|
452
468
|
}
|
|
453
469
|
|
|
454
470
|
options.router.registerOutbound('instagram', outboundCallback)
|
|
471
|
+
options.router.registerSelfIdentity('instagram', selfIdentityResolver)
|
|
455
472
|
options.router.registerChannelNameResolver('instagram', channelResolver.resolve)
|
|
456
473
|
options.router.registerHistory('instagram', historyCallback)
|
|
457
474
|
},
|
|
@@ -460,6 +477,7 @@ export function createInstagramAdapter(options: InstagramAdapterOptions): Instag
|
|
|
460
477
|
if (!started) return
|
|
461
478
|
started = false
|
|
462
479
|
options.router.unregisterOutbound('instagram', outboundCallback)
|
|
480
|
+
options.router.unregisterSelfIdentity('instagram', selfIdentityResolver)
|
|
463
481
|
options.router.unregisterChannelNameResolver('instagram', channelResolver.resolve)
|
|
464
482
|
options.router.unregisterHistory('instagram', historyCallback)
|
|
465
483
|
listener?.stop()
|
|
@@ -21,7 +21,9 @@ import type { KakaoAccountCredentials, KakaoConfig, PendingLoginState } from 'ag
|
|
|
21
21
|
|
|
22
22
|
import { prependQuoteAnchor, type ChannelRouter } from '@/channels/router'
|
|
23
23
|
import type { ChannelAdapterConfig } from '@/channels/schema'
|
|
24
|
+
import { fallbackChannelAccountIdentity } from '@/channels/types'
|
|
24
25
|
import type {
|
|
26
|
+
ChannelSelfIdentityResolver,
|
|
25
27
|
ChannelHistoryMessage,
|
|
26
28
|
FetchHistoryArgs,
|
|
27
29
|
FetchHistoryResult,
|
|
@@ -47,6 +49,7 @@ import { createFetchAttachmentCallback } from './kakaotalk-fetch-attachment'
|
|
|
47
49
|
import { toKakaoPlainText } from './kakaotalk-format'
|
|
48
50
|
import { createKakaoMembershipResolver } from './kakaotalk-membership'
|
|
49
51
|
import { createKakaoTypingCallback, kakaoTypingClassFromLookup, KAKAO_TYPING_HEARTBEAT_MS } from './kakaotalk-typing'
|
|
52
|
+
import { withOutboundAccount } from './outbound-account'
|
|
50
53
|
|
|
51
54
|
// Structural duck-type of the upstream KakaoTalkClient class. The upstream
|
|
52
55
|
// type is a class with private fields, and TypeScript treats those
|
|
@@ -361,6 +364,7 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
|
|
|
361
364
|
})
|
|
362
365
|
let listener: KakaoTalkListener | null = null
|
|
363
366
|
let selfUserId: string | null = null
|
|
367
|
+
const selfIdentityResolver: ChannelSelfIdentityResolver = () => (selfUserId === null ? null : { id: selfUserId })
|
|
364
368
|
let connected = false
|
|
365
369
|
let started = false
|
|
366
370
|
let lastConnectedAt: number | null = null
|
|
@@ -400,11 +404,14 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
|
|
|
400
404
|
selfUserIdRef: () => selfUserId,
|
|
401
405
|
})
|
|
402
406
|
|
|
403
|
-
const outboundCallback =
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
407
|
+
const outboundCallback = withOutboundAccount(
|
|
408
|
+
createOutboundCallback({
|
|
409
|
+
client,
|
|
410
|
+
logger,
|
|
411
|
+
formatChannelTag,
|
|
412
|
+
}),
|
|
413
|
+
(workspace) => fallbackChannelAccountIdentity('kakaotalk', workspace, selfUserId),
|
|
414
|
+
)
|
|
408
415
|
|
|
409
416
|
const typing = createKakaoTypingCallback({
|
|
410
417
|
logger,
|
|
@@ -435,6 +442,7 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
|
|
|
435
442
|
event: KakaoTalkPushMessageEvent,
|
|
436
443
|
attachments: readonly InboundAttachment[] = [],
|
|
437
444
|
): Promise<void> => {
|
|
445
|
+
const inboundSelfId = selfUserId
|
|
438
446
|
inflightInbounds++
|
|
439
447
|
try {
|
|
440
448
|
if (channelResolver.lookupChat(event.chat_id) === null) {
|
|
@@ -472,7 +480,7 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
|
|
|
472
480
|
markReadIfSupported({ client, event, channelResolver, logger })
|
|
473
481
|
|
|
474
482
|
const verdict = classifyInbound(event, options.configRef(), {
|
|
475
|
-
selfUserId,
|
|
483
|
+
selfUserId: inboundSelfId,
|
|
476
484
|
lookupChat: (id) => channelResolver.lookupChat(id),
|
|
477
485
|
...(attachments.length > 0 ? { attachments } : {}),
|
|
478
486
|
...(options.selfAliasesRef ? { selfAliases: options.selfAliasesRef() } : {}),
|
|
@@ -491,7 +499,12 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
|
|
|
491
499
|
logger.info(
|
|
492
500
|
`[kakaotalk] routed log_id=${event.log_id} ${inboundTag} mention=${enriched.isBotMention} reply=${enriched.replyToBotMessageId !== null} dm=${enriched.isDm}`,
|
|
493
501
|
)
|
|
494
|
-
await options.router.route(
|
|
502
|
+
await options.router.route({
|
|
503
|
+
...enriched,
|
|
504
|
+
accountIdentity: fallbackChannelAccountIdentity('kakaotalk', enriched.workspace, inboundSelfId),
|
|
505
|
+
eventKind: 'message',
|
|
506
|
+
revision: 'original',
|
|
507
|
+
})
|
|
495
508
|
} catch (err) {
|
|
496
509
|
logger.error(`[kakaotalk] handleInbound failed: ${describeError(err)}`)
|
|
497
510
|
} finally {
|
|
@@ -678,6 +691,7 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
|
|
|
678
691
|
// but outboundCallback would still send via a dead client). Stop()
|
|
679
692
|
// unregisters in the inverse order.
|
|
680
693
|
options.router.registerOutbound('kakaotalk', outboundCallback)
|
|
694
|
+
options.router.registerSelfIdentity('kakaotalk', selfIdentityResolver)
|
|
681
695
|
options.router.registerTyping('kakaotalk', typing.callback)
|
|
682
696
|
options.router.setTypingCapability('kakaotalk', true)
|
|
683
697
|
// KakaoTalk expires the indicator ~5s after the last packet, faster than
|
|
@@ -694,6 +708,7 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
|
|
|
694
708
|
if (!started) return
|
|
695
709
|
started = false
|
|
696
710
|
options.router.unregisterOutbound('kakaotalk', outboundCallback)
|
|
711
|
+
options.router.unregisterSelfIdentity('kakaotalk', selfIdentityResolver)
|
|
697
712
|
options.router.unregisterTyping('kakaotalk', typing.callback)
|
|
698
713
|
options.router.setTypingCapability('kakaotalk', false)
|
|
699
714
|
typing.reset()
|
|
@@ -14,7 +14,9 @@ import {
|
|
|
14
14
|
|
|
15
15
|
import type { ChannelRouter } from '@/channels/router'
|
|
16
16
|
import type { ChannelAdapterConfig } from '@/channels/schema'
|
|
17
|
+
import { fallbackChannelAccountIdentity } from '@/channels/types'
|
|
17
18
|
import type {
|
|
19
|
+
ChannelSelfIdentityResolver,
|
|
18
20
|
ChannelHistoryMessage,
|
|
19
21
|
FetchHistoryArgs,
|
|
20
22
|
FetchHistoryResult,
|
|
@@ -31,6 +33,7 @@ import { createLineChannelResolver } from './line-channel-resolver'
|
|
|
31
33
|
import { classifyInbound } from './line-classify'
|
|
32
34
|
import { toLinePlainText } from './line-format'
|
|
33
35
|
import { LINE_TOKEN_REFRESH_SKEW_MS, nextRefreshDelayMs } from './line-token'
|
|
36
|
+
import { withOutboundAccount } from './outbound-account'
|
|
34
37
|
|
|
35
38
|
// Structural duck-type of the upstream LineClient class. Declaring this as an
|
|
36
39
|
// interface (rather than reusing the nominal class type) lets test fakes
|
|
@@ -186,6 +189,7 @@ export function createLineAdapter(options: LineAdapterOptions): LineAdapter {
|
|
|
186
189
|
const client = options.client ?? buildClient(credManager)
|
|
187
190
|
let listener: LineListener | null = null
|
|
188
191
|
let selfUserId: string | null = null
|
|
192
|
+
const selfIdentityResolver: ChannelSelfIdentityResolver = () => (selfUserId === null ? null : { id: selfUserId })
|
|
189
193
|
let connected = false
|
|
190
194
|
let started = false
|
|
191
195
|
let inflightInbounds = 0
|
|
@@ -214,7 +218,10 @@ export function createLineAdapter(options: LineAdapterOptions): LineAdapter {
|
|
|
214
218
|
selfUserIdRef: () => selfUserId,
|
|
215
219
|
})
|
|
216
220
|
|
|
217
|
-
const outboundCallback =
|
|
221
|
+
const outboundCallback = withOutboundAccount(
|
|
222
|
+
createOutboundCallback({ client, logger, formatChannelTag }),
|
|
223
|
+
(workspace) => fallbackChannelAccountIdentity('line', workspace, selfUserId),
|
|
224
|
+
)
|
|
218
225
|
|
|
219
226
|
// The SDK's AuthService updates the LIVE client's token in-place and emits this
|
|
220
227
|
// event; we mirror it into secrets.json so the next container start boots from a
|
|
@@ -262,6 +269,7 @@ export function createLineAdapter(options: LineAdapterOptions): LineAdapter {
|
|
|
262
269
|
}
|
|
263
270
|
|
|
264
271
|
const processInbound = async (event: LinePushMessageEvent): Promise<void> => {
|
|
272
|
+
const inboundSelfId = selfUserId
|
|
265
273
|
inflightInbounds++
|
|
266
274
|
try {
|
|
267
275
|
if (channelResolver.lookupChat(event.chat_id) === null) {
|
|
@@ -286,7 +294,7 @@ export function createLineAdapter(options: LineAdapterOptions): LineAdapter {
|
|
|
286
294
|
)
|
|
287
295
|
|
|
288
296
|
const verdict = classifyInbound(event, options.configRef(), {
|
|
289
|
-
selfUserId,
|
|
297
|
+
selfUserId: inboundSelfId,
|
|
290
298
|
lookupChat: (id) => channelResolver.lookupChat(id),
|
|
291
299
|
text,
|
|
292
300
|
attachments,
|
|
@@ -300,7 +308,12 @@ export function createLineAdapter(options: LineAdapterOptions): LineAdapter {
|
|
|
300
308
|
logger.info(
|
|
301
309
|
`[line] routed message_id=${event.message_id} ${inboundTag} mention=${verdict.payload.isBotMention} dm=${verdict.payload.isDm}`,
|
|
302
310
|
)
|
|
303
|
-
await options.router.route(
|
|
311
|
+
await options.router.route({
|
|
312
|
+
...verdict.payload,
|
|
313
|
+
accountIdentity: fallbackChannelAccountIdentity('line', verdict.payload.workspace, inboundSelfId),
|
|
314
|
+
eventKind: 'message',
|
|
315
|
+
revision: 'original',
|
|
316
|
+
})
|
|
304
317
|
} catch (err) {
|
|
305
318
|
logger.error(`[line] handleInbound failed: ${describeError(err)}`)
|
|
306
319
|
} finally {
|
|
@@ -393,6 +406,7 @@ export function createLineAdapter(options: LineAdapterOptions): LineAdapter {
|
|
|
393
406
|
// failure cannot leave the router pointing at callbacks for a
|
|
394
407
|
// half-initialized adapter. stop() unregisters in inverse order.
|
|
395
408
|
options.router.registerOutbound('line', outboundCallback)
|
|
409
|
+
options.router.registerSelfIdentity('line', selfIdentityResolver)
|
|
396
410
|
options.router.registerChannelNameResolver('line', channelResolver.resolve)
|
|
397
411
|
options.router.registerHistory('line', historyCallback)
|
|
398
412
|
},
|
|
@@ -405,6 +419,7 @@ export function createLineAdapter(options: LineAdapterOptions): LineAdapter {
|
|
|
405
419
|
refreshTimer = null
|
|
406
420
|
}
|
|
407
421
|
options.router.unregisterOutbound('line', outboundCallback)
|
|
422
|
+
options.router.unregisterSelfIdentity('line', selfIdentityResolver)
|
|
408
423
|
options.router.unregisterChannelNameResolver('line', channelResolver.resolve)
|
|
409
424
|
options.router.unregisterHistory('line', historyCallback)
|
|
410
425
|
if (inflightInbounds > 0) {
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { OutboundCallback } from '@/channels/types'
|
|
2
|
+
|
|
3
|
+
// A captured callback may outlive adapter reload. Validate the account attached
|
|
4
|
+
// to this sender, not whichever replacement now occupies the router registry.
|
|
5
|
+
export function withOutboundAccount(
|
|
6
|
+
send: OutboundCallback,
|
|
7
|
+
accountIdentity: (workspace: string) => string | undefined,
|
|
8
|
+
): OutboundCallback {
|
|
9
|
+
return (message) => {
|
|
10
|
+
const expected = message.sendOptions?.expectedAccountIdentity
|
|
11
|
+
if (expected !== undefined && accountIdentity(message.workspace) !== expected) {
|
|
12
|
+
return Promise.resolve({
|
|
13
|
+
ok: false as const,
|
|
14
|
+
error: 'Adapter account identity changed',
|
|
15
|
+
recoveryFailure: { kind: 'identity' as const, safeReason: 'adapter account identity changed' },
|
|
16
|
+
})
|
|
17
|
+
}
|
|
18
|
+
return send(message)
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { AdapterId } from '@/channels/schema'
|
|
2
|
+
import type {
|
|
3
|
+
PrepareOwnReactionCallback,
|
|
4
|
+
ReactionErrorCode,
|
|
5
|
+
ReactionRef,
|
|
6
|
+
RemoveOwnReactionCallback,
|
|
7
|
+
RemoveOwnReactionResult,
|
|
8
|
+
} from '@/channels/types'
|
|
9
|
+
|
|
10
|
+
import { describeError } from '../describe-error'
|
|
11
|
+
|
|
12
|
+
export function createOwnReactionCallbacks<T>(deps: {
|
|
13
|
+
adapter: AdapterId
|
|
14
|
+
identity: () => string | null | Promise<string | null>
|
|
15
|
+
decode: (ref: ReactionRef) => T | null
|
|
16
|
+
encode: (target: T) => ReactionRef
|
|
17
|
+
emoji: (emoji: string) => string | null
|
|
18
|
+
remove: (target: T, emoji: string) => Promise<unknown>
|
|
19
|
+
classify: (error: unknown) => ReactionErrorCode
|
|
20
|
+
absent: (error: unknown) => boolean
|
|
21
|
+
}): { prepare: PrepareOwnReactionCallback; remove: RemoveOwnReactionCallback } {
|
|
22
|
+
return {
|
|
23
|
+
prepare: async (req) => {
|
|
24
|
+
if (req.adapter !== deps.adapter) return null
|
|
25
|
+
const target = deps.decode(req.reactionRef)
|
|
26
|
+
const emoji = deps.emoji(req.emoji)
|
|
27
|
+
if (target === null || emoji === null || emoji === '') return null
|
|
28
|
+
const accountIdentity = await deps.identity()
|
|
29
|
+
return accountIdentity ? { accountIdentity, target: deps.encode(target), emoji } : null
|
|
30
|
+
},
|
|
31
|
+
remove: async (req): Promise<RemoveOwnReactionResult> => {
|
|
32
|
+
if (req.adapter !== deps.adapter) return { ok: false, code: 'unsupported', error: 'wrong reaction adapter' }
|
|
33
|
+
const target = deps.decode(req.target)
|
|
34
|
+
const emoji = deps.emoji(req.emoji)
|
|
35
|
+
if (target === null || emoji === null || emoji === '')
|
|
36
|
+
return { ok: false, code: 'unsupported', error: 'invalid reaction target or emoji' }
|
|
37
|
+
try {
|
|
38
|
+
const identity = await deps.identity()
|
|
39
|
+
if (!identity || identity !== req.expectedAccountIdentity)
|
|
40
|
+
return { ok: false, code: 'identity', error: 'authenticated reaction account changed or unavailable' }
|
|
41
|
+
await deps.remove(target, emoji)
|
|
42
|
+
return { ok: true }
|
|
43
|
+
} catch (error) {
|
|
44
|
+
if (deps.absent(error)) return { ok: true }
|
|
45
|
+
const code = deps.classify(error)
|
|
46
|
+
const retryAfter =
|
|
47
|
+
typeof error === 'object' && error !== null && 'retryAfter' in error && typeof error.retryAfter === 'number'
|
|
48
|
+
? error.retryAfter * 1000
|
|
49
|
+
: undefined
|
|
50
|
+
return {
|
|
51
|
+
ok: false,
|
|
52
|
+
code:
|
|
53
|
+
code === 'permission-denied'
|
|
54
|
+
? 'permission'
|
|
55
|
+
: code === 'rate-limited'
|
|
56
|
+
? 'rate-limit'
|
|
57
|
+
: code === 'unsupported'
|
|
58
|
+
? 'unsupported'
|
|
59
|
+
: 'transient',
|
|
60
|
+
error: describeError(error),
|
|
61
|
+
...(retryAfter !== undefined ? { retryAfter } : {}),
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
|
|
3
|
+
import { z } from 'zod'
|
|
4
|
+
|
|
5
|
+
import type { RecoveryFailure } from '../continuity-types'
|
|
6
|
+
import type { RecoveryAdapterCallbacks, OutboundMessage, SendResult } from '../types'
|
|
7
|
+
import { RecoveryTransportError } from '../types'
|
|
8
|
+
|
|
9
|
+
export const recoveryMarker = (id: string): string => `<!-- typeclaw-recovery:${id} -->`
|
|
10
|
+
export const recoveryNonce = (id: string): string => createHash('sha256').update(id).digest('hex').slice(0, 24)
|
|
11
|
+
|
|
12
|
+
const rowSchema = z.object({
|
|
13
|
+
id: z.string().optional(),
|
|
14
|
+
ts: z.string().optional(),
|
|
15
|
+
user: z.string().optional(),
|
|
16
|
+
thread_ts: z.string().optional(),
|
|
17
|
+
author: z.object({ id: z.string() }).optional(),
|
|
18
|
+
nonce: z.union([z.string(), z.number()]).nullish(),
|
|
19
|
+
// Other apps' message metadata in the same history page must not fail the whole parse.
|
|
20
|
+
metadata: z
|
|
21
|
+
.object({ event_type: z.string().optional(), event_payload: z.record(z.string(), z.unknown()).optional() })
|
|
22
|
+
.optional(),
|
|
23
|
+
})
|
|
24
|
+
const responseSchema = z.object({
|
|
25
|
+
ok: z.boolean().optional(),
|
|
26
|
+
error: z.string().optional(),
|
|
27
|
+
// Discord errors carry a string; Slack chat.postMessage returns the posted message object.
|
|
28
|
+
message: z.unknown().optional(),
|
|
29
|
+
has_more: z.boolean().optional(),
|
|
30
|
+
errors: z.array(z.unknown()).optional(),
|
|
31
|
+
team_id: z.string().optional(),
|
|
32
|
+
user_id: z.string().optional(),
|
|
33
|
+
id: z.string().optional(),
|
|
34
|
+
ts: z.string().optional(),
|
|
35
|
+
messages: z.array(rowSchema).optional(),
|
|
36
|
+
response_metadata: z.object({ next_cursor: z.string().optional() }).optional(),
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
export function recoveryHttpFailure(response: Response, platformError?: string): RecoveryFailure {
|
|
40
|
+
const retry = response.headers.get('Retry-After')
|
|
41
|
+
const seconds = retry === null ? NaN : Number(retry)
|
|
42
|
+
const retryAfter = Number.isFinite(seconds)
|
|
43
|
+
? Math.max(0, seconds * 1000)
|
|
44
|
+
: retry === null
|
|
45
|
+
? undefined
|
|
46
|
+
: Math.max(0, Date.parse(retry) - Date.now())
|
|
47
|
+
const rateLimited = response.status === 429 || platformError === 'ratelimited'
|
|
48
|
+
const permission =
|
|
49
|
+
response.status === 401 ||
|
|
50
|
+
response.status === 403 ||
|
|
51
|
+
['invalid_auth', 'not_authed', 'missing_scope', 'token_revoked', 'not_in_channel'].includes(platformError ?? '')
|
|
52
|
+
const target = response.status === 404 || platformError === 'channel_not_found'
|
|
53
|
+
return {
|
|
54
|
+
kind: rateLimited ? 'rate-limit' : permission ? 'permission' : target ? 'target' : 'transient',
|
|
55
|
+
safeReason: rateLimited
|
|
56
|
+
? 'Platform rate limit'
|
|
57
|
+
: permission
|
|
58
|
+
? 'Platform authorization unavailable'
|
|
59
|
+
: target
|
|
60
|
+
? 'Destination unavailable'
|
|
61
|
+
: 'Platform request failed',
|
|
62
|
+
...(Number.isFinite(retryAfter) ? { retryAfter } : {}),
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function json(fetchImpl: typeof fetch, url: string, init: RequestInit): Promise<z.infer<typeof responseSchema>> {
|
|
67
|
+
const response = await fetchImpl(url, init)
|
|
68
|
+
if (!response.ok) throw new RecoveryTransportError(recoveryHttpFailure(response))
|
|
69
|
+
const body = responseSchema.parse(await response.json())
|
|
70
|
+
if (!response.ok || body.ok === false || body.errors?.length)
|
|
71
|
+
throw new RecoveryTransportError(recoveryHttpFailure(response, body.error))
|
|
72
|
+
return body
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function createBotRecoveryCallbacks(
|
|
76
|
+
platform: 'slack-bot' | 'discord-bot',
|
|
77
|
+
token: string,
|
|
78
|
+
fetchImpl: typeof fetch = fetch,
|
|
79
|
+
cachedAccountIdentity: (workspace?: string) => string | undefined = () => undefined,
|
|
80
|
+
): RecoveryAdapterCallbacks {
|
|
81
|
+
const slack = platform === 'slack-bot'
|
|
82
|
+
const headers = { Authorization: slack ? `Bearer ${token}` : `Bot ${token}`, 'Content-Type': 'application/json' }
|
|
83
|
+
const accountIdentity = async (workspace?: string) => {
|
|
84
|
+
const actor = await json(
|
|
85
|
+
fetchImpl,
|
|
86
|
+
slack ? 'https://slack.com/api/auth.test' : 'https://discord.com/api/v10/users/@me',
|
|
87
|
+
{ method: slack ? 'POST' : 'GET', headers },
|
|
88
|
+
)
|
|
89
|
+
if (slack ? !actor.team_id || !actor.user_id : !actor.id) throw new Error('recovery-account-identity-unavailable')
|
|
90
|
+
if (slack && workspace !== undefined && workspace !== '@dm' && actor.team_id !== workspace) return undefined
|
|
91
|
+
return slack ? `slack-bot:${actor.team_id}:${actor.user_id}` : `discord-bot:${actor.id}`
|
|
92
|
+
}
|
|
93
|
+
return {
|
|
94
|
+
accountIdentity,
|
|
95
|
+
cachedAccountIdentity,
|
|
96
|
+
async reconcile(record) {
|
|
97
|
+
const identity = await accountIdentity(record.target.workspace)
|
|
98
|
+
if (!identity || identity !== (record.boundAccountIdentity ?? record.accountIdentity))
|
|
99
|
+
throw new Error('recovery-account-identity-changed')
|
|
100
|
+
const actorId = identity.split(':').at(-1)
|
|
101
|
+
const target = record.target
|
|
102
|
+
let cursor: string | undefined
|
|
103
|
+
const seen = new Set<string>()
|
|
104
|
+
do {
|
|
105
|
+
let rows: z.infer<typeof rowSchema>[]
|
|
106
|
+
let next: string | undefined
|
|
107
|
+
if (slack) {
|
|
108
|
+
// Form-encoded like createSlackHistoryCallback: the JSON body for conversations.replies came back
|
|
109
|
+
// `invalid_arguments` in production, so reconcile never saw the notice it had already posted.
|
|
110
|
+
const form = new URLSearchParams({ channel: target.chat, limit: '100', include_all_metadata: 'true' })
|
|
111
|
+
if (target.thread) form.set('ts', target.thread)
|
|
112
|
+
if (cursor) form.set('cursor', cursor)
|
|
113
|
+
const data = await json(
|
|
114
|
+
fetchImpl,
|
|
115
|
+
`https://slack.com/api/conversations.${target.thread ? 'replies' : 'history'}`,
|
|
116
|
+
{
|
|
117
|
+
method: 'POST',
|
|
118
|
+
headers: { ...headers, 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' },
|
|
119
|
+
body: form.toString(),
|
|
120
|
+
},
|
|
121
|
+
)
|
|
122
|
+
if (!data.messages) throw new Error('recovery-history-missing-messages')
|
|
123
|
+
rows = data.messages
|
|
124
|
+
next = data.response_metadata?.next_cursor || undefined
|
|
125
|
+
if (data.has_more && !next) throw new Error('recovery-history-missing-cursor')
|
|
126
|
+
const found = rows.find(
|
|
127
|
+
(row) =>
|
|
128
|
+
row.user === actorId &&
|
|
129
|
+
row.metadata?.event_type === 'typeclaw_recovery' &&
|
|
130
|
+
row.metadata?.event_payload?.delivery_id === record.deliveryId &&
|
|
131
|
+
(target.thread ? row.thread_ts === target.thread : !row.thread_ts || row.thread_ts === row.ts),
|
|
132
|
+
)
|
|
133
|
+
if (found?.ts) return { status: 'found', messageId: found.ts, messageIds: [found.ts] }
|
|
134
|
+
} else {
|
|
135
|
+
const channel = target.thread ?? target.chat
|
|
136
|
+
const response = await fetchImpl(
|
|
137
|
+
`https://discord.com/api/v10/channels/${encodeURIComponent(channel)}/messages?limit=100${cursor ? `&before=${encodeURIComponent(cursor)}` : ''}`,
|
|
138
|
+
{ headers },
|
|
139
|
+
)
|
|
140
|
+
if (!response.ok) throw new Error(`Recovery history ${response.status}`)
|
|
141
|
+
rows = z.array(rowSchema).parse(await response.json())
|
|
142
|
+
if (rows.some((row) => !row.id)) throw new Error('recovery-history-missing-message-id')
|
|
143
|
+
const found = rows.find(
|
|
144
|
+
(row) => row.author?.id === actorId && String(row.nonce) === recoveryNonce(record.deliveryId),
|
|
145
|
+
)
|
|
146
|
+
if (found?.id) return { status: 'found', messageId: found.id, messageIds: [found.id] }
|
|
147
|
+
next = rows.length === 100 ? rows.at(-1)?.id : undefined
|
|
148
|
+
}
|
|
149
|
+
if (next && seen.has(next)) throw new Error('recovery-history-cursor-loop')
|
|
150
|
+
if (next) seen.add(next)
|
|
151
|
+
cursor = next
|
|
152
|
+
} while (cursor)
|
|
153
|
+
return { status: 'unknown' }
|
|
154
|
+
},
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export async function sendBotRecovery(
|
|
159
|
+
platform: 'slack-bot' | 'discord-bot',
|
|
160
|
+
token: string,
|
|
161
|
+
msg: OutboundMessage,
|
|
162
|
+
fetchImpl: typeof fetch = fetch,
|
|
163
|
+
): Promise<SendResult> {
|
|
164
|
+
const options = msg.sendOptions
|
|
165
|
+
if (options?.accounting !== 'recovery') throw new Error('missing-recovery-options')
|
|
166
|
+
try {
|
|
167
|
+
const callbacks = createBotRecoveryCallbacks(platform, token, fetchImpl)
|
|
168
|
+
if ((await callbacks.accountIdentity(msg.workspace)) !== options.expectedAccountIdentity)
|
|
169
|
+
return {
|
|
170
|
+
ok: false,
|
|
171
|
+
error: 'recovery-account-identity-changed',
|
|
172
|
+
recoveryFailure: { kind: 'identity', safeReason: 'Authenticated account changed' },
|
|
173
|
+
}
|
|
174
|
+
const slack = platform === 'slack-bot'
|
|
175
|
+
const data = await json(
|
|
176
|
+
fetchImpl,
|
|
177
|
+
slack
|
|
178
|
+
? 'https://slack.com/api/chat.postMessage'
|
|
179
|
+
: `https://discord.com/api/v10/channels/${encodeURIComponent(msg.thread ?? msg.chat)}/messages`,
|
|
180
|
+
{
|
|
181
|
+
method: 'POST',
|
|
182
|
+
headers: { Authorization: slack ? `Bearer ${token}` : `Bot ${token}`, 'Content-Type': 'application/json' },
|
|
183
|
+
body: JSON.stringify(
|
|
184
|
+
slack
|
|
185
|
+
? {
|
|
186
|
+
channel: msg.chat,
|
|
187
|
+
thread_ts: msg.thread ?? undefined,
|
|
188
|
+
text: msg.text,
|
|
189
|
+
unfurl_links: false,
|
|
190
|
+
unfurl_media: false,
|
|
191
|
+
metadata: { event_type: 'typeclaw_recovery', event_payload: { delivery_id: options.deliveryId } },
|
|
192
|
+
}
|
|
193
|
+
: {
|
|
194
|
+
content: msg.text,
|
|
195
|
+
nonce: recoveryNonce(options.deliveryId),
|
|
196
|
+
enforce_nonce: true,
|
|
197
|
+
allowed_mentions: { parse: [] },
|
|
198
|
+
},
|
|
199
|
+
),
|
|
200
|
+
},
|
|
201
|
+
)
|
|
202
|
+
const id = slack ? data.ts : data.id
|
|
203
|
+
return { ok: true, messageId: id, messageIds: id ? [id] : undefined }
|
|
204
|
+
} catch (error) {
|
|
205
|
+
return {
|
|
206
|
+
ok: false,
|
|
207
|
+
error: error instanceof Error ? error.message : 'recovery-transport-failed',
|
|
208
|
+
recoveryFailure:
|
|
209
|
+
error instanceof RecoveryTransportError
|
|
210
|
+
? error.failure
|
|
211
|
+
: { kind: 'transient', safeReason: 'Recovery transport failed' },
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|