typeclaw 0.48.9 → 0.48.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/package.json +1 -1
  2. package/scripts/apparmor/typeclaw-bwrap +43 -0
  3. package/scripts/verify-apparmor-signals.sh +161 -0
  4. package/scripts/verify-mask-fd-sandbox.sh +176 -0
  5. package/src/agent/index.ts +9 -0
  6. package/src/agent/live-subagents.ts +98 -0
  7. package/src/agent/session-origin.ts +5 -1
  8. package/src/agent/tools/channel-reply.ts +30 -2
  9. package/src/agent/tools/channel-send.ts +19 -2
  10. package/src/agent/tools/spawn-subagent.ts +37 -1
  11. package/src/agent/tools/subagent-cancel.ts +14 -2
  12. package/src/bundled-plugins/backup/README.md +4 -3
  13. package/src/bundled-plugins/backup/runner.ts +125 -32
  14. package/src/bundled-plugins/github-cli-auth/gh-command.ts +106 -9
  15. package/src/bundled-plugins/github-cli-auth/git-command.ts +94 -9
  16. package/src/bundled-plugins/github-cli-auth/index.ts +45 -5
  17. package/src/channels/adapters/github/inbound.ts +210 -27
  18. package/src/channels/adapters/github/index.ts +16 -18
  19. package/src/channels/adapters/github/reconcile-cooldown-store.ts +15 -1
  20. package/src/channels/adapters/github/recover-failed-deliveries.ts +7 -2
  21. package/src/channels/adapters/github/review-submitter.ts +28 -0
  22. package/src/channels/adapters/instagram-continuity-store.ts +141 -0
  23. package/src/channels/adapters/instagram.ts +149 -4
  24. package/src/channels/github-repo.ts +11 -0
  25. package/src/channels/github-review-verdict-coordinator.ts +179 -29
  26. package/src/channels/github-verdict-activity.ts +12 -6
  27. package/src/channels/manager.ts +10 -0
  28. package/src/channels/persistence.ts +28 -2
  29. package/src/channels/router.ts +371 -33
  30. package/src/channels/schema.ts +18 -0
  31. package/src/channels/types.ts +11 -0
  32. package/src/cli/compose.ts +7 -4
  33. package/src/compose/restart.ts +26 -16
  34. package/src/compose/start.ts +24 -14
  35. package/src/config/config.ts +9 -1
  36. package/src/container/restart.ts +4 -0
  37. package/src/container/shared.ts +30 -3
  38. package/src/container/start.ts +137 -56
  39. package/src/doctor/apparmor.ts +101 -0
  40. package/src/doctor/checks.ts +2 -0
  41. package/src/hostd/daemon.ts +40 -17
  42. package/src/init/dockerfile.ts +7 -6
  43. package/src/init/windows-dev-link.ts +34 -2
  44. package/src/run/channel-session-factory.ts +35 -15
  45. package/src/run/index.ts +1 -0
  46. package/src/sandbox/availability.ts +7 -5
  47. package/src/skills/typeclaw-channel-github/SKILL.md +4 -2
  48. package/typeclaw.schema.json +7 -0
@@ -2,6 +2,7 @@ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
2
2
  import { dirname, join } from 'node:path'
3
3
 
4
4
  import { describeError } from '../../describe-error'
5
+ import { canonicalGithubRepo } from '../../github-repo'
5
6
 
6
7
  // Durable per-PR replay cooldown for the open-PR reconcile pass.
7
8
  //
@@ -66,7 +67,7 @@ export function reconcileCooldownPath(agentDir: string): string {
66
67
  }
67
68
 
68
69
  function markerKey(repo: string, prId: number): string {
69
- return `${repo}#${prId}`
70
+ return `${canonicalGithubRepo(repo)}#${prId}`
70
71
  }
71
72
 
72
73
  export type ReconcileCooldownStore = {
@@ -74,6 +75,7 @@ export type ReconcileCooldownStore = {
74
75
  // Flush BEFORE routing the synthetic inbound: a crash between marking and
75
76
  // session creation must not re-trigger a replay on the next restart.
76
77
  markReplayed: (repo: string, prId: number, now: number) => Promise<void>
78
+ clear: (repo: string, prId: number) => Promise<void>
77
79
  prune: (repo: string, openPrIds: ReadonlySet<number>, now: number) => Promise<void>
78
80
  }
79
81
 
@@ -116,6 +118,18 @@ export async function loadReconcileCooldownStore(
116
118
  throw err
117
119
  }
118
120
  },
121
+ async clear(repo, prId): Promise<void> {
122
+ const key = markerKey(repo, prId)
123
+ const previous = markers.get(key)
124
+ if (previous === undefined) return
125
+ markers.delete(key)
126
+ try {
127
+ await flush()
128
+ } catch (err) {
129
+ markers.set(key, previous)
130
+ throw err
131
+ }
132
+ },
119
133
  async prune(repo, openPrIds, now): Promise<void> {
120
134
  let changed = false
121
135
  for (const [key, marker] of markers) {
@@ -54,7 +54,12 @@ export type RecoverFailedDeliveriesOptions = {
54
54
  // The shared processVerifiedGithubDelivery, bound to the adapter's handler
55
55
  // options. `delivery` is the GUID; the core dedups, filters by allowlist,
56
56
  // drops self-authored, and routes exactly as the live path does.
57
- process: (input: { event: string; delivery: string; payload: Record<string, unknown> }) => Promise<void>
57
+ process: (input: {
58
+ event: string
59
+ delivery: string
60
+ payload: Record<string, unknown>
61
+ recovered: true
62
+ }) => Promise<void>
58
63
  // Fast-path skip backed by the LIVE delivery dedup (shared with the webhook
59
64
  // handler): a guid here was just routed live (or reserved by `process` on
60
65
  // entry), so skip it. Best-effort only — it is a 1000-entry LRU and may evict
@@ -145,7 +150,7 @@ async function recoverHook(
145
150
 
146
151
  const payload = await fetchDeliveryPayload(fetchImpl, token, target, hook.hookId, delivery.id)
147
152
  if (payload === null) continue
148
- await options.process({ event: delivery.event, delivery: guid, payload })
153
+ await options.process({ event: delivery.event, delivery: guid, payload, recovered: true })
149
154
  // Record AFTER process resolves: an unexpected throw leaves the guid
150
155
  // unrecorded so the next sweep retries it. A no-op classify still records
151
156
  // (process returned), so a non-routable failed delivery is not refetched.
@@ -1,3 +1,4 @@
1
+ import { githubReviewerWorkKey } from '@/channels/github-repo'
1
2
  import type {
2
3
  ReviewFinding,
3
4
  ReviewSubmitter,
@@ -8,9 +9,21 @@ import type {
8
9
 
9
10
  import type { GithubAuthContext } from './auth'
10
11
  import { GITHUB_API_BASE, githubJsonHeaders } from './auth-pat'
12
+ import { createBoundedMap } from './dedup'
11
13
 
12
14
  const MAX_HEAD_STABILITY_ATTEMPTS = 3
13
15
 
16
+ // Bounded because a long-lived container accumulates one entry per drafted PR
17
+ // forever otherwise. Eviction is fail-safe: a submission that captured a bumped
18
+ // generation sees the evicted key read back as 0, mismatches, and is denied —
19
+ // eviction can only cancel a submission, never resurrect a cancelled one.
20
+ const reviewSubmissionGenerations = createBoundedMap<string, number>()
21
+
22
+ export function invalidateGithubReviewSubmission(workspace: string, prNumber: number): void {
23
+ const key = githubReviewerWorkKey(workspace, prNumber)
24
+ reviewSubmissionGenerations.set(key, currentReviewSubmissionGeneration(workspace, prNumber) + 1)
25
+ }
26
+
14
27
  export function createGithubReviewSubmitter(deps: {
15
28
  token: (context?: GithubAuthContext) => Promise<string>
16
29
  allowApprove: () => boolean
@@ -27,6 +40,7 @@ export function createGithubReviewSubmitter(deps: {
27
40
  code: 'transient',
28
41
  }
29
42
  }
43
+ const submissionGeneration = currentReviewSubmissionGeneration(req.workspace, target.prNumber)
30
44
 
31
45
  const token = await deps.token({ repoSlug: `${target.owner}/${target.repo}` })
32
46
  const stable = await fetchStableAnchors(fetchImpl, token, target)
@@ -35,6 +49,16 @@ export function createGithubReviewSubmitter(deps: {
35
49
  const { inline, reanchored } = partitionComments(req.comments, stable.anchors)
36
50
  const downgraded = req.event === 'APPROVE' && !deps.allowApprove()
37
51
  const event = downgraded ? 'COMMENT' : req.event
52
+ if (currentReviewSubmissionGeneration(req.workspace, target.prNumber) !== submissionGeneration) {
53
+ return {
54
+ ok: false,
55
+ error: 'PR converted to draft; review submission cancelled',
56
+ code: 'transient',
57
+ }
58
+ }
59
+ // Once this call dispatches fetch(), GitHub may already have accepted the
60
+ // review. Let posting, verification, and accounting settle after that
61
+ // boundary; cancelling mid-flight would leave duplicate/state ambiguity.
38
62
  const posted = await postReview(fetchImpl, token, target, {
39
63
  event,
40
64
  body: appendReanchored(req.body, reanchored),
@@ -54,6 +78,10 @@ export function createGithubReviewSubmitter(deps: {
54
78
  }
55
79
  }
56
80
 
81
+ function currentReviewSubmissionGeneration(workspace: string, prNumber: number): number {
82
+ return reviewSubmissionGenerations.get(githubReviewerWorkKey(workspace, prNumber)) ?? 0
83
+ }
84
+
57
85
  async function fetchStableAnchors(
58
86
  fetchImpl: typeof fetch,
59
87
  token: string,
@@ -0,0 +1,141 @@
1
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
2
+ import { dirname, join } from 'node:path'
3
+
4
+ import { describeError } from '../describe-error'
5
+
6
+ const FILE_VERSION = 1
7
+ const MAX_MESSAGE_IDS_PER_THREAD = 500
8
+
9
+ type ThreadState = {
10
+ accountId: string
11
+ threadId: string
12
+ messageIds: string[]
13
+ }
14
+
15
+ type FileV1 = {
16
+ version: 1
17
+ threads: ThreadState[]
18
+ }
19
+
20
+ export type InstagramContinuityLogger = {
21
+ warn: (msg: string) => void
22
+ error: (msg: string) => void
23
+ }
24
+
25
+ export type InstagramContinuityStore = {
26
+ knowsThread: (accountId: string, threadId: string) => boolean
27
+ hasMessage: (accountId: string, threadId: string, messageId: string) => boolean
28
+ seedThread: (accountId: string, threadId: string, messageIds: readonly string[]) => Promise<void>
29
+ markMessage: (accountId: string, threadId: string, messageId: string) => Promise<void>
30
+ }
31
+
32
+ export function instagramContinuityPath(agentDir: string): string {
33
+ return join(agentDir, 'channels', 'instagram-continuity.json')
34
+ }
35
+
36
+ export async function loadInstagramContinuityStore(
37
+ agentDir: string,
38
+ logger: InstagramContinuityLogger,
39
+ ): Promise<InstagramContinuityStore> {
40
+ const path = instagramContinuityPath(agentDir)
41
+ const threads = new Map<string, string[]>()
42
+ for (const state of await readStates(path, logger)) {
43
+ threads.set(threadKey(state.accountId, state.threadId), state.messageIds.slice(-MAX_MESSAGE_IDS_PER_THREAD))
44
+ }
45
+
46
+ const flush = async (): Promise<void> => {
47
+ const states: ThreadState[] = []
48
+ for (const [key, messageIds] of threads) {
49
+ const [accountId, threadId] = parseThreadKey(key)
50
+ states.push({ accountId, threadId, messageIds })
51
+ }
52
+ const payload: FileV1 = { version: FILE_VERSION, threads: states }
53
+ await mkdir(dirname(path), { recursive: true })
54
+ const tmp = `${path}.tmp`
55
+ await writeFile(tmp, `${JSON.stringify(payload, null, 2)}\n`, 'utf8')
56
+ await rename(tmp, path)
57
+ }
58
+
59
+ const saveIds = async (accountId: string, threadId: string, messageIds: readonly string[]): Promise<void> => {
60
+ const key = threadKey(accountId, threadId)
61
+ const previous = threads.get(key)
62
+ const next = Array.from(new Set(messageIds)).slice(-MAX_MESSAGE_IDS_PER_THREAD)
63
+ threads.set(key, next)
64
+ try {
65
+ await flush()
66
+ } catch (err) {
67
+ if (previous === undefined) threads.delete(key)
68
+ else threads.set(key, previous)
69
+ throw err
70
+ }
71
+ }
72
+
73
+ return {
74
+ knowsThread(accountId, threadId): boolean {
75
+ return threads.has(threadKey(accountId, threadId))
76
+ },
77
+ hasMessage(accountId, threadId, messageId): boolean {
78
+ return threads.get(threadKey(accountId, threadId))?.includes(messageId) ?? false
79
+ },
80
+ async seedThread(accountId, threadId, messageIds): Promise<void> {
81
+ await saveIds(accountId, threadId, messageIds)
82
+ },
83
+ async markMessage(accountId, threadId, messageId): Promise<void> {
84
+ const current = threads.get(threadKey(accountId, threadId)) ?? []
85
+ if (current.includes(messageId)) return
86
+ await saveIds(accountId, threadId, [...current, messageId])
87
+ },
88
+ }
89
+ }
90
+
91
+ function threadKey(accountId: string, threadId: string): string {
92
+ return `${accountId}\u0000${threadId}`
93
+ }
94
+
95
+ function parseThreadKey(key: string): [string, string] {
96
+ const separator = key.indexOf('\u0000')
97
+ return [key.slice(0, separator), key.slice(separator + 1)]
98
+ }
99
+
100
+ async function readStates(path: string, logger: InstagramContinuityLogger): Promise<ThreadState[]> {
101
+ let raw: string
102
+ try {
103
+ raw = await readFile(path, 'utf8')
104
+ } catch {
105
+ return []
106
+ }
107
+
108
+ let parsed: unknown
109
+ try {
110
+ parsed = JSON.parse(raw)
111
+ } catch (err) {
112
+ logger.error(`[instagram] ${path} corrupted: ${describeError(err)}; starting fresh`)
113
+ return []
114
+ }
115
+ if (!isObject(parsed)) {
116
+ logger.warn(`[instagram] ${path} not an object; ignored`)
117
+ return []
118
+ }
119
+ if (parsed.version !== FILE_VERSION) {
120
+ logger.warn(
121
+ `[instagram] ${path} version ${String(parsed.version)} not supported (expected ${FILE_VERSION}); ignored`,
122
+ )
123
+ return []
124
+ }
125
+ if (!Array.isArray(parsed.threads)) return []
126
+ return parsed.threads.filter(isThreadState)
127
+ }
128
+
129
+ function isObject(value: unknown): value is Record<string, unknown> {
130
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
131
+ }
132
+
133
+ function isThreadState(value: unknown): value is ThreadState {
134
+ if (!isObject(value)) return false
135
+ return (
136
+ typeof value.accountId === 'string' &&
137
+ typeof value.threadId === 'string' &&
138
+ Array.isArray(value.messageIds) &&
139
+ value.messageIds.every((id) => typeof id === 'string')
140
+ )
141
+ }
@@ -22,6 +22,7 @@ import type {
22
22
  import { describeError } from '../describe-error'
23
23
  import { createInstagramChannelResolver } from './instagram-channel-resolver'
24
24
  import { classifyInbound } from './instagram-classify'
25
+ import { loadInstagramContinuityStore, type InstagramContinuityStore } from './instagram-continuity-store'
25
26
  import { toInstagramPlainText } from './instagram-format'
26
27
 
27
28
  export interface InstagramClientShape {
@@ -89,6 +90,7 @@ const consoleLogger: InstagramAdapterLogger = {
89
90
  }
90
91
 
91
92
  export type InstagramAdapterOptions = {
93
+ agentDir?: string
92
94
  router: ChannelRouter
93
95
  configRef: () => ChannelAdapterConfig
94
96
  logger?: InstagramAdapterLogger
@@ -97,6 +99,7 @@ export type InstagramAdapterOptions = {
97
99
  client?: InstagramClientShape
98
100
  clientFactory?: (credManager?: InstagramCredentialManager) => InstagramClientShape
99
101
  listenerCtorResolver?: () => { ctor: InstagramListenerCtor; transport: 'hybrid' | 'polling' }
102
+ continuityStore?: InstagramContinuityStore
100
103
  now?: () => number
101
104
  }
102
105
 
@@ -107,6 +110,7 @@ export type InstagramAdapter = {
107
110
  }
108
111
 
109
112
  export const INSTAGRAM_HISTORY_LIMIT_MAX = 200
113
+ const INSTAGRAM_RECOVERY_CHAT_LIMIT = 100
110
114
 
111
115
  export function createOutboundCallback(deps: {
112
116
  client: Pick<InstagramClientShape, 'sendMessage'>
@@ -177,6 +181,13 @@ export function createInstagramAdapter(options: InstagramAdapterOptions): Instag
177
181
  let started = false
178
182
  let inflightInbounds = 0
179
183
  let stopWaiters: Array<() => void> = []
184
+ let continuityStore: InstagramContinuityStore | null = options.continuityStore ?? null
185
+ let activeTransport: 'realtime' | 'polling' = 'polling'
186
+ let inboundQueue = Promise.resolve()
187
+ let adapterStartedAt = 0
188
+ const bootstrapBaselines = new Map<string, readonly string[]>()
189
+ const recoveryLimitWarnedThreads = new Set<string>()
190
+ let recoveryChatLimitWarned = false
180
191
 
181
192
  const channelResolver = createInstagramChannelResolver({ client, logger })
182
193
 
@@ -190,7 +201,7 @@ export function createInstagramAdapter(options: InstagramAdapterOptions): Instag
190
201
  const historyCallback = createInstagramHistoryCallback({ client, logger, selfUserIdRef: () => selfUserId })
191
202
  const outboundCallback = createOutboundCallback({ client, logger, formatChannelTag })
192
203
 
193
- const processInbound = async (message: InstagramMessageSummary): Promise<void> => {
204
+ const processInbound = async (message: InstagramMessageSummary): Promise<boolean> => {
194
205
  inflightInbounds++
195
206
  try {
196
207
  if (channelResolver.lookupChat(message.thread_id) === null) {
@@ -216,15 +227,17 @@ export function createInstagramAdapter(options: InstagramAdapterOptions): Instag
216
227
  })
217
228
  if (verdict.kind === 'drop') {
218
229
  logger.info(`[instagram] dropped message_id=${message.id} reason=${verdict.reason}`)
219
- return
230
+ return true
220
231
  }
221
232
 
222
233
  logger.info(
223
234
  `[instagram] routed message_id=${message.id} ${inboundTag} mention=${verdict.payload.isBotMention} dm=${verdict.payload.isDm}`,
224
235
  )
225
236
  await options.router.route(verdict.payload)
237
+ return true
226
238
  } catch (err) {
227
239
  logger.error(`[instagram] handleInbound failed: ${describeError(err)}`)
240
+ return false
228
241
  } finally {
229
242
  inflightInbounds--
230
243
  if (inflightInbounds === 0 && stopWaiters.length > 0) {
@@ -235,10 +248,117 @@ export function createInstagramAdapter(options: InstagramAdapterOptions): Instag
235
248
  }
236
249
  }
237
250
 
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
+ const deliverUnseen = async (message: InstagramMessageSummary): Promise<boolean> => {
257
+ if (
258
+ continuityStore !== null &&
259
+ selfUserId !== null &&
260
+ continuityStore.hasMessage(selfUserId, message.thread_id, message.id)
261
+ ) {
262
+ return true
263
+ }
264
+ if (!(await processInbound(message))) return false
265
+ // Checkpoint only after the router accepts the message. A crash can replay
266
+ // once, but persisting first would silently lose a message when routing fails.
267
+ await markDelivered(message)
268
+ return true
269
+ }
270
+
271
+ const fetchRecoveryMessages = async (threadId: string): Promise<InstagramMessageSummary[]> => {
272
+ const messages = await client.getMessages(threadId, INSTAGRAM_HISTORY_LIMIT_MAX)
273
+ if (messages.length === INSTAGRAM_HISTORY_LIMIT_MAX && !recoveryLimitWarnedThreads.has(threadId)) {
274
+ recoveryLimitWarnedThreads.add(threadId)
275
+ logger.warn(
276
+ `[instagram] recovery history reached limit=${INSTAGRAM_HISTORY_LIMIT_MAX} chat=${threadId}; older unseen messages cannot be recovered without upstream pagination`,
277
+ )
278
+ }
279
+ return messages.toSorted((left, right) => Date.parse(left.timestamp) - Date.parse(right.timestamp))
280
+ }
281
+
282
+ const establishUnknownThread = async (
283
+ threadId: string,
284
+ messages: readonly InstagramMessageSummary[],
285
+ ): Promise<void> => {
286
+ if (continuityStore === null || selfUserId === null) return
287
+ const bootstrapIds = bootstrapBaselines.get(threadId)
288
+ const baselineIds = bootstrapIds ?? messages.filter(isBeforeAdapterStart).map((message) => message.id)
289
+ await continuityStore.seedThread(selfUserId, threadId, baselineIds)
290
+ bootstrapBaselines.delete(threadId)
291
+ }
292
+
293
+ const reconcileThread = async (threadId: string): Promise<boolean> => {
294
+ if (continuityStore === null || selfUserId === null) return true
295
+ const messages = await fetchRecoveryMessages(threadId)
296
+ if (!continuityStore.knowsThread(selfUserId, threadId)) await establishUnknownThread(threadId, messages)
297
+ for (const message of messages) {
298
+ if (!(await deliverUnseen(message))) return false
299
+ }
300
+ return true
301
+ }
302
+
303
+ const reconcileAll = async (): Promise<void> => {
304
+ const chats = await client.listChats(INSTAGRAM_RECOVERY_CHAT_LIMIT)
305
+ warnIfChatLimitReached(chats.length)
306
+ for (const chat of chats) {
307
+ try {
308
+ await reconcileThread(chat.id)
309
+ } catch (err) {
310
+ logger.error(`[instagram] recovery failed chat=${chat.id}: ${describeError(err)}`)
311
+ }
312
+ }
313
+ }
314
+
315
+ const seedBootstrap = async (): Promise<void> => {
316
+ const chats = await client.listChats(INSTAGRAM_RECOVERY_CHAT_LIMIT)
317
+ warnIfChatLimitReached(chats.length)
318
+ for (const chat of chats) {
319
+ try {
320
+ if (continuityStore === null || selfUserId === null || continuityStore.knowsThread(selfUserId, chat.id)) {
321
+ await reconcileThread(chat.id)
322
+ continue
323
+ }
324
+ const messages = await fetchRecoveryMessages(chat.id)
325
+ const baselineIds = messages.filter(isBeforeAdapterStart).map((message) => message.id)
326
+ bootstrapBaselines.set(chat.id, baselineIds)
327
+ await continuityStore.seedThread(selfUserId, chat.id, baselineIds)
328
+ bootstrapBaselines.delete(chat.id)
329
+ for (const message of messages) {
330
+ if (!(await deliverUnseen(message))) break
331
+ }
332
+ } catch (err) {
333
+ logger.error(`[instagram] bootstrap failed chat=${chat.id}: ${describeError(err)}`)
334
+ }
335
+ }
336
+ }
337
+
338
+ const warnIfChatLimitReached = (chatCount: number): void => {
339
+ if (chatCount !== INSTAGRAM_RECOVERY_CHAT_LIMIT || recoveryChatLimitWarned) return
340
+ recoveryChatLimitWarned = true
341
+ logger.warn(
342
+ `[instagram] recovery chat list reached limit=${INSTAGRAM_RECOVERY_CHAT_LIMIT}; older chats cannot be recovered without upstream pagination`,
343
+ )
344
+ }
345
+
346
+ const isBeforeAdapterStart = (message: InstagramMessageSummary): boolean => {
347
+ const timestamp = Date.parse(message.timestamp)
348
+ return Number.isNaN(timestamp) || timestamp < adapterStartedAt
349
+ }
350
+
351
+ const enqueueInbound = (task: () => Promise<void>): void => {
352
+ inboundQueue = inboundQueue.then(task).catch((err: unknown) => {
353
+ logger.error(`[instagram] recovery failed: ${describeError(err)}`)
354
+ })
355
+ }
356
+
238
357
  return {
239
358
  async start(): Promise<void> {
240
359
  if (started) return
241
360
  started = true
361
+ adapterStartedAt = (options.now ?? Date.now)()
242
362
 
243
363
  try {
244
364
  const credentialStore = options.credentialsStore ?? null
@@ -269,28 +389,52 @@ export function createInstagramAdapter(options: InstagramAdapterOptions): Instag
269
389
  throw err
270
390
  }
271
391
 
392
+ if (continuityStore === null && options.agentDir !== undefined) {
393
+ continuityStore = await loadInstagramContinuityStore(options.agentDir, logger)
394
+ }
395
+
272
396
  try {
273
397
  await channelResolver.refresh()
274
398
  } catch (err) {
275
399
  logger.warn(`[instagram] initial chat list fetch failed: ${describeError(err)}`)
276
400
  }
277
401
 
402
+ try {
403
+ await seedBootstrap()
404
+ } catch (err) {
405
+ logger.warn(`[instagram] initial recovery failed: ${describeError(err)}`)
406
+ }
407
+
278
408
  const resolved = (options.listenerCtorResolver ?? resolveInstagramListenerCtor)()
279
409
  listener = new resolved.ctor(client, { pollInterval: 5_000 })
280
410
  logger.info(`[instagram] listener transport=${resolved.transport}`)
281
411
  listener.on('connected', ({ userId, transport = 'polling' }) => {
412
+ if (!started) return
282
413
  connected = true
414
+ activeTransport = transport
283
415
  logger.info(`[instagram] connected (user_id=${userId}, transport=${transport})`)
416
+ enqueueInbound(reconcileAll)
284
417
  })
285
418
  listener.on('disconnected', () => {
419
+ if (!started) return
286
420
  connected = false
287
421
  logger.warn('[instagram] disconnected; SDK will reconnect with backoff')
288
422
  })
289
423
  listener.on('error', (err) => {
424
+ if (!started) return
290
425
  logger.error(`[instagram] listener error: ${describeError(err)}`)
291
426
  })
292
427
  listener.on('message', (message) => {
293
- void processInbound(message)
428
+ if (!started) return
429
+ const transport = activeTransport
430
+ enqueueInbound(async () => {
431
+ const unknownThread =
432
+ continuityStore !== null &&
433
+ selfUserId !== null &&
434
+ !continuityStore.knowsThread(selfUserId, message.thread_id)
435
+ if ((transport === 'polling' || unknownThread) && !(await reconcileThread(message.thread_id))) return
436
+ await deliverUnseen(message)
437
+ })
294
438
  })
295
439
 
296
440
  try {
@@ -318,12 +462,13 @@ export function createInstagramAdapter(options: InstagramAdapterOptions): Instag
318
462
  options.router.unregisterOutbound('instagram', outboundCallback)
319
463
  options.router.unregisterChannelNameResolver('instagram', channelResolver.resolve)
320
464
  options.router.unregisterHistory('instagram', historyCallback)
465
+ listener?.stop()
466
+ await inboundQueue
321
467
  if (inflightInbounds > 0) {
322
468
  await new Promise<void>((resolve) => {
323
469
  stopWaiters.push(resolve)
324
470
  })
325
471
  }
326
- listener?.stop()
327
472
  listener = null
328
473
  selfUserId = null
329
474
  connected = false
@@ -0,0 +1,11 @@
1
+ export function canonicalGithubRepo(repo: string): string {
2
+ return repo
3
+ .trim()
4
+ .replace(/\/+$/, '')
5
+ .replace(/\.git$/i, '')
6
+ .toLocaleLowerCase()
7
+ }
8
+
9
+ export function githubReviewerWorkKey(repo: string, prNumber: number): string {
10
+ return `reviewer:github:${canonicalGithubRepo(repo)}#${prNumber}`
11
+ }