typeclaw 0.40.0 → 0.42.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.
Files changed (61) hide show
  1. package/README.md +3 -2
  2. package/auth.schema.json +57 -0
  3. package/package.json +2 -2
  4. package/secrets.schema.json +57 -0
  5. package/src/agent/index.ts +10 -6
  6. package/src/agent/multimodal/look-at.ts +87 -0
  7. package/src/agent/session-origin.ts +1 -0
  8. package/src/agent/tools/channel-history-render.ts +21 -0
  9. package/src/agent/tools/channel-history.ts +2 -17
  10. package/src/agent/tools/channel-read.ts +206 -0
  11. package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +26 -2
  12. package/src/bundled-plugins/github-cli-auth/index.ts +25 -6
  13. package/src/bundled-plugins/memory/index.ts +10 -11
  14. package/src/bundled-plugins/memory/vector/hybrid.ts +73 -6
  15. package/src/bundled-plugins/memory/vector/index-on-write.ts +25 -20
  16. package/src/bundled-plugins/memory/vector/passages.ts +2 -24
  17. package/src/bundled-plugins/memory/vector/reference-index-on-write.ts +28 -23
  18. package/src/bundled-plugins/memory/vector/store.ts +2 -0
  19. package/src/bundled-plugins/memory/vector/truncation.ts +28 -0
  20. package/src/bundled-plugins/planner/planner.ts +4 -2
  21. package/src/bundled-plugins/reviewer/reviewer.ts +9 -1
  22. package/src/bundled-plugins/tool-result-cap/README.md +10 -1
  23. package/src/bundled-plugins/tool-result-cap/cap-result.ts +8 -0
  24. package/src/channels/adapters/discord-bot.ts +112 -0
  25. package/src/channels/adapters/instagram-channel-resolver.ts +113 -0
  26. package/src/channels/adapters/instagram-classify.ts +69 -0
  27. package/src/channels/adapters/instagram-format.ts +8 -0
  28. package/src/channels/adapters/instagram.ts +346 -0
  29. package/src/channels/adapters/kakaotalk-classify.ts +31 -6
  30. package/src/channels/adapters/kakaotalk.ts +1 -1
  31. package/src/channels/adapters/slack-bot.ts +147 -0
  32. package/src/channels/manager.ts +60 -2
  33. package/src/channels/router.ts +64 -0
  34. package/src/channels/schema.ts +5 -0
  35. package/src/channels/types.ts +46 -0
  36. package/src/cli/channel.ts +76 -1
  37. package/src/cli/init.ts +1 -0
  38. package/src/cli/status.ts +37 -14
  39. package/src/config/channels-mutation.ts +2 -1
  40. package/src/doctor/channel-checks.ts +28 -0
  41. package/src/hostd/daemon.ts +59 -19
  42. package/src/hostd/kakao-renewal-manager.ts +35 -10
  43. package/src/hostd/protocol.ts +2 -0
  44. package/src/hostd/tailscale.ts +41 -5
  45. package/src/hostd/webex-renewal-manager.ts +13 -4
  46. package/src/init/index.ts +50 -1
  47. package/src/init/instagram-auth.ts +134 -0
  48. package/src/init/run-owner-claim.ts +1 -0
  49. package/src/permissions/match-rule.ts +1 -1
  50. package/src/permissions/resolve.ts +1 -0
  51. package/src/plugin/index.ts +1 -0
  52. package/src/plugin/manager.ts +14 -0
  53. package/src/plugin/registry.ts +12 -0
  54. package/src/plugin/types.ts +4 -0
  55. package/src/role-claim/match-rule.ts +2 -1
  56. package/src/run/index.ts +46 -20
  57. package/src/secrets/instagram-store.ts +112 -0
  58. package/src/secrets/schema.ts +18 -0
  59. package/src/skills/typeclaw-channel-instagram/SKILL.md +30 -0
  60. package/src/test-helpers/rm-temp-dir.ts +24 -0
  61. package/typeclaw.schema.json +161 -1
@@ -8,6 +8,7 @@ import { defaultDockerExec, type DockerExec, type HostDaemonRegisterPayload } fr
8
8
  import type { PortForwardEvent } from '@/portbroker'
9
9
  import {
10
10
  discordChannelBlockSchema,
11
+ instagramChannelBlockSchema,
11
12
  kakaoChannelBlockSchema,
12
13
  lineChannelBlockSchema,
13
14
  slackChannelBlockSchema,
@@ -41,6 +42,10 @@ export type DaemonOptions = {
41
42
  onLog?: (event: DaemonLogEvent | SupervisorLogEvent) => void
42
43
  gcIntervalMs?: number
43
44
  gcMissesToDeregister?: number
45
+ // Per-step bound on teardown calls (portbroker/renewal stop) run inside the
46
+ // per-container serial chain. Defaults to CLEANUP_STEP_TIMEOUT_MS; tests
47
+ // override it to a few ms to assert the chain never wedges on a hung step.
48
+ cleanupStepTimeoutMs?: number
44
49
  socket?: string
45
50
  // When provided, the daemon honors `restart` RPCs by invoking this with the
46
51
  // (containerName, cwd) it captured at register time. Omit to disable the
@@ -130,6 +135,14 @@ const DEFAULT_GC_MISSES_TO_DEREGISTER = 3
130
135
  const MAX_REQUEST_BUFFER_BYTES = 64 * 1024
131
136
  const MAX_HTTP_REQUEST_BYTES = 64 * 1024
132
137
 
138
+ // Upper bound on any single teardown step (portbroker/renewal stop) run inside
139
+ // the per-container runSerially chain. A teardown dependency must never own a
140
+ // container's serial queue forever — that wedges every later register/deregister
141
+ // for that container (the renewal-restart wedge). Larger than tailscale's 30s
142
+ // per-call budget so a slow-but-progressing serve-off isn't cut off, yet finite
143
+ // so a genuine hang releases the queue instead of poisoning it.
144
+ const CLEANUP_STEP_TIMEOUT_MS = 60_000
145
+
133
146
  // Preferred port for the HTTP control surface. Adjacent to CONTAINER_PORT
134
147
  // (8973) for mnemonics. Stability matters: containers cache the URL in
135
148
  // TYPECLAW_HOSTD_URL at `docker run` time, so a respawn that picks a fresh
@@ -223,6 +236,21 @@ function stringifyError(error: unknown): string {
223
236
  return error instanceof Error ? error.message : String(error)
224
237
  }
225
238
 
239
+ // Races a teardown step against a wall clock so a hung dependency can't hold the
240
+ // per-container serial chain open forever. Resolves (never rejects) on timeout
241
+ // so the surrounding runSerially op always settles and releases the queue.
242
+ async function withCleanupTimeout(work: Promise<unknown>, timeoutMs: number): Promise<void> {
243
+ let timer: ReturnType<typeof setTimeout> | undefined
244
+ const timeout = new Promise<void>((resolve) => {
245
+ timer = setTimeout(resolve, timeoutMs)
246
+ })
247
+ try {
248
+ await Promise.race([work.catch(() => {}), timeout])
249
+ } finally {
250
+ if (timer) clearTimeout(timer)
251
+ }
252
+ }
253
+
226
254
  function errorCode(error: Error): unknown {
227
255
  const direct = error as Error & { code?: unknown; cause?: unknown }
228
256
  if (direct.code !== undefined) return direct.code
@@ -282,6 +310,7 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
282
310
  const exec = opts.exec ?? defaultDockerExec
283
311
  const gcIntervalMs = opts.gcIntervalMs ?? DEFAULT_GC_INTERVAL_MS
284
312
  const gcMissesToDeregister = opts.gcMissesToDeregister ?? DEFAULT_GC_MISSES_TO_DEREGISTER
313
+ const cleanupStepTimeoutMs = opts.cleanupStepTimeoutMs ?? CLEANUP_STEP_TIMEOUT_MS
285
314
  const version = opts.version ?? UNVERSIONED_SENTINEL
286
315
  const cwds = new Map<string, string>()
287
316
  const restartTokens = new Map<string, string>()
@@ -362,9 +391,10 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
362
391
  cwds.delete(containerName)
363
392
  restartTokens.delete(containerName)
364
393
  gcMisses.delete(containerName)
365
- if (opts.portbroker) await opts.portbroker.stop(containerName, 'fatal-auth').catch(() => {})
366
- if (opts.kakaoRenewal) await opts.kakaoRenewal.stop(containerName).catch(() => {})
367
- if (opts.webexRenewal) await opts.webexRenewal.stop(containerName).catch(() => {})
394
+ if (opts.portbroker)
395
+ await withCleanupTimeout(opts.portbroker.stop(containerName, 'fatal-auth'), cleanupStepTimeoutMs)
396
+ if (opts.kakaoRenewal) await withCleanupTimeout(opts.kakaoRenewal.stop(containerName), cleanupStepTimeoutMs)
397
+ if (opts.webexRenewal) await withCleanupTimeout(opts.webexRenewal.stop(containerName), cleanupStepTimeoutMs)
368
398
  await removeRegistrationFile(containerName)
369
399
  log({ kind: 'registration-skipped', containerName, reason: `fatal broker auth: ${reason}` })
370
400
  })
@@ -430,9 +460,10 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
430
460
  restartTokens.delete(req.containerName)
431
461
  brokerTokens.delete(req.containerName)
432
462
  gcMisses.delete(req.containerName)
433
- if (opts.portbroker) await opts.portbroker.stop(req.containerName, 'deregistered').catch(() => {})
434
- if (opts.kakaoRenewal) await opts.kakaoRenewal.stop(req.containerName).catch(() => {})
435
- if (opts.webexRenewal) await opts.webexRenewal.stop(req.containerName).catch(() => {})
463
+ if (opts.portbroker)
464
+ await withCleanupTimeout(opts.portbroker.stop(req.containerName, 'deregistered'), cleanupStepTimeoutMs)
465
+ if (opts.kakaoRenewal) await withCleanupTimeout(opts.kakaoRenewal.stop(req.containerName), cleanupStepTimeoutMs)
466
+ if (opts.webexRenewal) await withCleanupTimeout(opts.webexRenewal.stop(req.containerName), cleanupStepTimeoutMs)
436
467
  await removeRegistrationFile(req.containerName)
437
468
  if (hadCwd) log({ kind: 'deregister', containerName: req.containerName, reason: 'requested' })
438
469
  return { ok: true }
@@ -500,6 +531,7 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
500
531
  channels:
501
532
  | { kakaotalk: unknown }
502
533
  | { discord: unknown }
534
+ | { instagram: unknown }
503
535
  | { line: unknown }
504
536
  | { webex: unknown }
505
537
  | { slack: unknown }
@@ -515,13 +547,15 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
515
547
  const patch =
516
548
  'line' in channelsPatch
517
549
  ? { key: 'line' as const, parsed: lineChannelBlockSchema.safeParse(channelsPatch.line) }
518
- : 'discord' in channelsPatch
519
- ? { key: 'discord' as const, parsed: discordChannelBlockSchema.safeParse(channelsPatch.discord) }
520
- : 'webex' in channelsPatch
521
- ? { key: 'webex' as const, parsed: webexChannelBlockSchema.safeParse(channelsPatch.webex) }
522
- : 'slack' in channelsPatch
523
- ? { key: 'slack' as const, parsed: slackChannelBlockSchema.safeParse(channelsPatch.slack) }
524
- : { key: 'kakaotalk' as const, parsed: kakaoChannelBlockSchema.safeParse(channelsPatch.kakaotalk) }
550
+ : 'instagram' in channelsPatch
551
+ ? { key: 'instagram' as const, parsed: instagramChannelBlockSchema.safeParse(channelsPatch.instagram) }
552
+ : 'discord' in channelsPatch
553
+ ? { key: 'discord' as const, parsed: discordChannelBlockSchema.safeParse(channelsPatch.discord) }
554
+ : 'webex' in channelsPatch
555
+ ? { key: 'webex' as const, parsed: webexChannelBlockSchema.safeParse(channelsPatch.webex) }
556
+ : 'slack' in channelsPatch
557
+ ? { key: 'slack' as const, parsed: slackChannelBlockSchema.safeParse(channelsPatch.slack) }
558
+ : { key: 'kakaotalk' as const, parsed: kakaoChannelBlockSchema.safeParse(channelsPatch.kakaotalk) }
525
559
  if (!patch.parsed.success) {
526
560
  return { ok: false, reason: patch.parsed.error.issues.map((issue) => issue.message).join('; ') }
527
561
  }
@@ -759,9 +793,9 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
759
793
  void runSerially(name, async () => {
760
794
  const hadCwd = cwds.delete(name)
761
795
  restartTokens.delete(name)
762
- if (opts.portbroker) await opts.portbroker.stop(name, 'deregistered').catch(() => {})
763
- if (opts.kakaoRenewal) await opts.kakaoRenewal.stop(name).catch(() => {})
764
- if (opts.webexRenewal) await opts.webexRenewal.stop(name).catch(() => {})
796
+ if (opts.portbroker) await withCleanupTimeout(opts.portbroker.stop(name, 'deregistered'), cleanupStepTimeoutMs)
797
+ if (opts.kakaoRenewal) await withCleanupTimeout(opts.kakaoRenewal.stop(name), cleanupStepTimeoutMs)
798
+ if (opts.webexRenewal) await withCleanupTimeout(opts.webexRenewal.stop(name), cleanupStepTimeoutMs)
765
799
  await removeRegistrationFile(name)
766
800
  if (hadCwd) log({ kind: 'deregister', containerName: name, reason: 'gone' })
767
801
  return { ok: true }
@@ -787,17 +821,23 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
787
821
  // after the teardown loop below already ran, leaking it. Let restore
788
822
  // settle (it never rejects past the detached catch) before tearing down.
789
823
  await (restoreComplete ?? Promise.resolve()).catch(() => {})
824
+ // Bound shutdown teardown too: a wedged broker/renewal stop must not
825
+ // block daemon.stop() forever, which would also stall the version-drift
826
+ // respawn flow that waits for this to return before unlinking the socket.
790
827
  if (opts.portbroker) {
791
828
  const names = Array.from(cwds.keys())
792
- await Promise.allSettled(names.map((n) => opts.portbroker!.stop(n, 'broker-stopped')))
829
+ await withCleanupTimeout(
830
+ Promise.allSettled(names.map((n) => opts.portbroker!.stop(n, 'broker-stopped'))),
831
+ cleanupStepTimeoutMs,
832
+ )
793
833
  }
794
834
  if (opts.kakaoRenewal) {
795
835
  const names = Array.from(cwds.keys())
796
- await Promise.allSettled(names.map((n) => opts.kakaoRenewal!.stop(n)))
836
+ await withCleanupTimeout(Promise.allSettled(names.map((n) => opts.kakaoRenewal!.stop(n))), cleanupStepTimeoutMs)
797
837
  }
798
838
  if (opts.webexRenewal) {
799
839
  const names = Array.from(cwds.keys())
800
- await Promise.allSettled(names.map((n) => opts.webexRenewal!.stop(n)))
840
+ await withCleanupTimeout(Promise.allSettled(names.map((n) => opts.webexRenewal!.stop(n))), cleanupStepTimeoutMs)
801
841
  }
802
842
  cwds.clear()
803
843
  restartTokens.clear()
@@ -104,7 +104,14 @@ export function createKakaoRenewalManager(opts: KakaoRenewalManagerOptions = {})
104
104
  accountId: result.account_id,
105
105
  previousUpdatedAt: result.previousUpdatedAt,
106
106
  })
107
- if (opts.onRenewalOk) {
107
+ // A tick that started before stop()/drain() (deregister, shutdown) or
108
+ // before a re-register with a different cwd can finish the slow login
109
+ // here. Restarting a container that is no longer the current
110
+ // registration would resurrect a just-deregistered agent or fight a
111
+ // shutdown, so skip onRenewalOk unless this container+cwd is still the
112
+ // live registration. Matches webex-renewal-manager's guard.
113
+ const current = latestInput.get(input.containerName)
114
+ if (opts.onRenewalOk && current?.cwd === input.cwd) {
108
115
  log({
109
116
  kind: 'kakao-renewal-restart-scheduled',
110
117
  containerName: input.containerName,
@@ -187,9 +194,21 @@ export function createKakaoRenewalManager(opts: KakaoRenewalManagerOptions = {})
187
194
 
188
195
  return {
189
196
  start(input: KakaoRenewalStartInput): void {
190
- if (opts.shouldRenew && !opts.shouldRenew(input)) return
197
+ // Tear down any prior registration for this container BEFORE the
198
+ // shouldRenew gate. The daemon calls start() on every registration, so a
199
+ // container that had Kakao can re-register to a non-Kakao cwd; if we
200
+ // returned early without clearing, the old timer would keep ticking and a
201
+ // post-login restart guard would still match the stale cwd. Clearing
202
+ // latestInput also makes an in-flight tick's onRenewalOk re-check fail.
191
203
  const existing = timers.get(input.containerName)
192
- if (existing) existing.stop()
204
+ if (existing) {
205
+ existing.stop()
206
+ timers.delete(input.containerName)
207
+ }
208
+ latestInput.delete(input.containerName)
209
+
210
+ if (opts.shouldRenew && !opts.shouldRenew(input)) return
211
+
193
212
  latestInput.set(input.containerName, input)
194
213
  const handle = schedule(() => {
195
214
  void scheduleTick(input.containerName)
@@ -198,26 +217,32 @@ export function createKakaoRenewalManager(opts: KakaoRenewalManagerOptions = {})
198
217
  void scheduleTick(input.containerName)
199
218
  },
200
219
 
201
- async stop(containerName: string): Promise<void> {
220
+ // Must NOT await the in-flight tick: a successful tick runs onRenewalOk →
221
+ // hostdRestart → container stop() → deregister RPC → handleDeregister →
222
+ // kakaoRenewal.stop(), so awaiting inFlight here waits on the very tick that
223
+ // is parked waiting for this restart — a self-deadlock that wedges the
224
+ // daemon's per-container serial chain forever. Clearing latestInput (not the
225
+ // await) is what fails the tick's onRenewalOk guard; drain() still awaits.
226
+ stop(containerName: string): Promise<void> {
202
227
  const handle = timers.get(containerName)
203
228
  if (handle) {
204
229
  timers.delete(containerName)
205
230
  handle.stop()
206
231
  }
207
232
  latestInput.delete(containerName)
208
- // Await any in-flight tick before resolving so the caller can rely on
209
- // "stop returned → no work outstanding". Daemon shutdown depends on
210
- // this; without it, a mid-tick `attemptLogin` HTTPS call is abandoned.
211
- const promise = inFlight.get(containerName)
212
- if (promise) await promise.catch(() => {})
233
+ return Promise.resolve()
213
234
  },
214
235
 
215
236
  async drain(): Promise<void> {
216
237
  for (const [, handle] of timers) handle.stop()
217
238
  timers.clear()
218
- latestInput.clear()
239
+ // Clear latestInput AFTER awaiting in-flight: the onRenewalOk guard reads
240
+ // latestInput, so clearing first would suppress the restart of a tick that
241
+ // is mid-login when drain() runs. drain() is shutdown — it waits for that
242
+ // work to finish rather than dropping it.
219
243
  const promises = Array.from(inFlight.values())
220
244
  await Promise.allSettled(promises)
245
+ latestInput.clear()
221
246
  },
222
247
  }
223
248
  }
@@ -1,6 +1,7 @@
1
1
  import type { PortForward } from '@/config'
2
2
  import type {
3
3
  DiscordChannelBlock,
4
+ InstagramChannelBlock,
4
5
  KakaoChannelBlock,
5
6
  LineChannelBlock,
6
7
  SlackChannelBlock,
@@ -28,6 +29,7 @@ export type Request =
28
29
  channels:
29
30
  | { kakaotalk: KakaoChannelBlock }
30
31
  | { discord: DiscordChannelBlock }
32
+ | { instagram: InstagramChannelBlock }
31
33
  | { line: LineChannelBlock }
32
34
  | { webex: WebexChannelBlock }
33
35
  | { slack: SlackChannelBlock }
@@ -36,6 +36,17 @@ type TailscaleStatus = {
36
36
  const MACOS_APP_CLI = '/Applications/Tailscale.app/Contents/MacOS/Tailscale'
37
37
  const WINDOWS_CLI = 'C:\\Program Files\\Tailscale\\tailscale.exe'
38
38
 
39
+ // Per-CLI-call wall clock. The tailscaled "serve config" is a global resource
40
+ // guarded by an etag; concurrent agent restarts racing `serve`/`serve off`
41
+ // surface "Another client is changing the serve config" and the losing CLI can
42
+ // block on the lock indefinitely. An unbounded `await proc.exited` then poisons
43
+ // stopAll() → portbroker.stop() → the daemon's per-container serial chain (the
44
+ // renewal-restart wedge). 30s is far longer than a healthy serve call yet bounds
45
+ // the hang. Kept below the daemon teardown budget so a timed-out call surfaces
46
+ // as a normal tailscale-serve-failed before the teardown wrapper trips.
47
+ const TAILSCALE_CLI_TIMEOUT_MS = 30_000
48
+ const TAILSCALE_TIMEOUT_EXIT_CODE = 124
49
+
39
50
  export function createTailscaleServeManager(opts: TailscaleServeManagerOptions): TailscaleServeManager {
40
51
  const exec = opts.exec ?? defaultTailscaleExec
41
52
  const log = opts.onLog ?? (() => {})
@@ -153,7 +164,11 @@ export const defaultTailscaleExec: TailscaleExec = async (args) => {
153
164
  return { exitCode: 127, stdout: '', stderr: lastError }
154
165
  }
155
166
 
156
- async function runTailscale(bin: string, args: string[]): Promise<TailscaleExecResult> {
167
+ export async function runTailscale(
168
+ bin: string,
169
+ args: string[],
170
+ timeoutMs: number = TAILSCALE_CLI_TIMEOUT_MS,
171
+ ): Promise<TailscaleExecResult> {
157
172
  const bun = getBun()
158
173
  if (!bun) return { exitCode: 127, stdout: '', stderr: 'bun runtime not available' }
159
174
  try {
@@ -163,10 +178,31 @@ async function runTailscale(bin: string, args: string[]): Promise<TailscaleExecR
163
178
  stderr: 'pipe',
164
179
  env: bin === MACOS_APP_CLI ? { ...process.env, TAILSCALE_BE_CLI: '1' } : process.env,
165
180
  })
166
- const exitCode = await proc.exited
167
- const stdout = await new Response(proc.stdout).text()
168
- const stderr = await new Response(proc.stderr).text()
169
- return { exitCode, stdout, stderr }
181
+ // Drain both pipes concurrently with the exit wait. Reading them only after
182
+ // `proc.exited` can deadlock: a child that fills its stdout/stderr pipe
183
+ // buffer blocks on write while we block on exit, so neither side advances.
184
+ const stdoutPromise = new Response(proc.stdout).text().catch(() => '')
185
+ const stderrPromise = new Response(proc.stderr).text().catch(() => '')
186
+
187
+ let timer: ReturnType<typeof setTimeout> | undefined
188
+ const timedOut = new Promise<'timeout'>((resolve) => {
189
+ timer = setTimeout(() => resolve('timeout'), timeoutMs)
190
+ })
191
+ const outcome = await Promise.race([proc.exited.then(() => 'exited' as const), timedOut])
192
+ if (timer) clearTimeout(timer)
193
+
194
+ if (outcome === 'timeout') {
195
+ try {
196
+ proc.kill()
197
+ } catch {}
198
+ return {
199
+ exitCode: TAILSCALE_TIMEOUT_EXIT_CODE,
200
+ stdout: '',
201
+ stderr: `tailscale ${args.join(' ')} timed out after ${timeoutMs}ms`,
202
+ }
203
+ }
204
+
205
+ return { exitCode: await proc.exited, stdout: await stdoutPromise, stderr: await stderrPromise }
170
206
  } catch (error) {
171
207
  const code = typeof error === 'object' && error !== null && 'code' in error ? String(error.code) : ''
172
208
  const exitCode = code === 'ENOENT' ? 127 : 1
@@ -194,23 +194,32 @@ export function createWebexRenewalManager(opts: WebexRenewalManagerOptions = {})
194
194
  void scheduleTick(input.containerName)
195
195
  },
196
196
 
197
- async stop(containerName: string): Promise<void> {
197
+ // Must NOT await the in-flight tick: a successful tick runs onRenewalOk →
198
+ // hostdRestart → container stop() → deregister RPC → handleDeregister →
199
+ // webexRenewal.stop(), so awaiting inFlight here waits on the very tick that
200
+ // is parked waiting for this restart — a self-deadlock that wedges the
201
+ // daemon's per-container serial chain forever. Clearing latestInput (not the
202
+ // await) is what fails the tick's onRenewalOk guard; drain() still awaits.
203
+ stop(containerName: string): Promise<void> {
198
204
  const handle = timers.get(containerName)
199
205
  if (handle) {
200
206
  timers.delete(containerName)
201
207
  handle.stop()
202
208
  }
203
209
  latestInput.delete(containerName)
204
- const promise = inFlight.get(containerName)
205
- if (promise) await promise.catch(() => {})
210
+ return Promise.resolve()
206
211
  },
207
212
 
208
213
  async drain(): Promise<void> {
209
214
  for (const [, handle] of timers) handle.stop()
210
215
  timers.clear()
211
- latestInput.clear()
216
+ // Clear latestInput AFTER awaiting in-flight: the onRenewalOk guard reads
217
+ // latestInput, so clearing first would suppress the restart of a tick that
218
+ // is mid-login when drain() runs. drain() is shutdown — it waits for that
219
+ // work to finish rather than dropping it.
212
220
  const promises = Array.from(inFlight.values())
213
221
  await Promise.allSettled(promises)
222
+ latestInput.clear()
214
223
  },
215
224
  }
216
225
  }
package/src/init/index.ts CHANGED
@@ -86,6 +86,7 @@ export type InitStep =
86
86
  | 'scaffold'
87
87
  | 'slack-auth'
88
88
  | 'discord-auth'
89
+ | 'instagram-auth'
89
90
  | 'kakaotalk-auth'
90
91
  | 'webex-auth'
91
92
  | 'github-webhooks'
@@ -98,6 +99,7 @@ export type KakaotalkAuthResult = { ok: true } | { ok: false; reason: string }
98
99
  export type WebexAuthResult = { ok: true } | { ok: false; reason: string }
99
100
  export type SlackAuthResult = { ok: true } | { ok: false; reason: string }
100
101
  export type DiscordAuthResult = { ok: true } | { ok: false; reason: string }
102
+ export type InstagramAuthResult = { ok: true } | { ok: false; reason: string }
101
103
 
102
104
  // Structured credential block for the GitHub channel adapter. Mirrors the
103
105
  // shape `runAddChannel({ channel: 'github', ... })` consumes so the wizard
@@ -137,6 +139,8 @@ export type InitStepEvent =
137
139
  | { step: 'webex-auth'; phase: 'done'; result: WebexAuthResult }
138
140
  | { step: 'discord-auth'; phase: 'start' }
139
141
  | { step: 'discord-auth'; phase: 'done'; result: DiscordAuthResult }
142
+ | { step: 'instagram-auth'; phase: 'start' }
143
+ | { step: 'instagram-auth'; phase: 'done'; result: InstagramAuthResult }
140
144
  | { step: 'github-webhooks'; phase: 'start' }
141
145
  | { step: 'github-webhooks'; phase: 'done'; result: EagerGithubWebhookInstallResult }
142
146
  | { step: 'install'; phase: 'start' }
@@ -169,6 +173,7 @@ export type WebexAuthRunner = (options: { cwd: string }) => Promise<WebexAuthRes
169
173
 
170
174
  export type LineAuthResult = { ok: true } | { ok: false; reason: string }
171
175
  export type LineAuthRunner = (options: { cwd: string }) => Promise<LineAuthResult>
176
+ export type InstagramAuthRunner = (options: { cwd: string }) => Promise<InstagramAuthResult>
172
177
 
173
178
  // Discriminated by `kind` so the type system enforces "you can't pass an
174
179
  // API key to an OAuth provider, and you can't pass an OAuth runner to an
@@ -223,11 +228,13 @@ export type InitOptions = {
223
228
  withTelegram?: boolean
224
229
  withWebex?: boolean
225
230
  withWebexUser?: boolean
231
+ withInstagram?: boolean
226
232
  withKakaotalk?: boolean
227
233
  withGithub?: boolean
228
234
  runKakaotalkAuth?: KakaotalkAuthRunner
229
235
  runWebexAuth?: WebexAuthRunner
230
236
  runDiscordAuth?: DiscordAuthRunner
237
+ runInstagramAuth?: InstagramAuthRunner
231
238
  // Structured GitHub credentials collected by the wizard. When omitted and
232
239
  // `withGithub` is true, the existing secrets.json#channels.github block is
233
240
  // reused as-is (the wizard's "reuse existing credentials" path).
@@ -273,11 +280,13 @@ export async function runInit({
273
280
  withTelegram,
274
281
  withWebex,
275
282
  withWebexUser = false,
283
+ withInstagram = false,
276
284
  withKakaotalk = false,
277
285
  withGithub = false,
278
286
  runKakaotalkAuth,
279
287
  runWebexAuth,
280
288
  runDiscordAuth,
289
+ runInstagramAuth,
281
290
  githubCredentials,
282
291
  githubFetchImpl,
283
292
  onProgress,
@@ -358,6 +367,7 @@ export async function runInit({
358
367
  withTelegram: wantsTelegram,
359
368
  withWebex: wantsWebex,
360
369
  withWebexUser,
370
+ withInstagram,
361
371
  withKakaotalk,
362
372
  platform,
363
373
  })
@@ -412,6 +422,15 @@ export async function runInit({
412
422
  }
413
423
  }
414
424
 
425
+ if (withInstagram && runInstagramAuth !== undefined) {
426
+ emit({ step: 'instagram-auth', phase: 'start' })
427
+ const result = await runInstagramAuth({ cwd })
428
+ emit({ step: 'instagram-auth', phase: 'done', result })
429
+ if (!result.ok) {
430
+ throw new Error(`Instagram authentication failed: ${result.reason}`)
431
+ }
432
+ }
433
+
415
434
  // Write the structured github channel block alongside scaffold's bot-token
416
435
  // blocks. We do NOT delegate to runAddChannel because that's the `channel
417
436
  // add` semantics — strict no-overwrite, throws when secrets.json#channels
@@ -463,6 +482,7 @@ export async function runInit({
463
482
  if (wantsTelegram) configuredChannels.push('telegram-bot')
464
483
  if (wantsWebex) configuredChannels.push('webex-bot')
465
484
  if (withWebexUser) configuredChannels.push('webex')
485
+ if (withInstagram) configuredChannels.push('instagram')
466
486
  if (withKakaotalk) configuredChannels.push('kakaotalk')
467
487
  if (withGithub) configuredChannels.push('github')
468
488
 
@@ -633,6 +653,7 @@ export type ScaffoldOptions = {
633
653
  withTelegram?: boolean
634
654
  withWebex?: boolean
635
655
  withWebexUser?: boolean
656
+ withInstagram?: boolean
636
657
  withKakaotalk?: boolean
637
658
  // Defaults to `process.platform`; controls the dev-mode typeclaw spec
638
659
  // (`link:` on Windows, `file:` on POSIX). Tests inject it.
@@ -671,6 +692,7 @@ export async function scaffold(root: string, options: ScaffoldOptions = {}): Pro
671
692
  if (options.withTelegram) channels['telegram-bot'] = {}
672
693
  if (options.withWebex) channels['webex-bot'] = {}
673
694
  if (options.withWebexUser) channels.webex = {}
695
+ if (options.withInstagram) channels.instagram = {}
674
696
  if (options.withKakaotalk) channels.kakaotalk = {}
675
697
  if (Object.keys(channels).length > 0) config.channels = channels
676
698
  // No default `member` match is seeded. A fresh chat agent starts with every
@@ -986,7 +1008,7 @@ export async function hasExistingOAuthCredentials(root: string, providerId: Know
986
1008
  // kakaotalk` anyway — better to re-auth now during init.
987
1009
  export async function hasExistingChannelSecrets(
988
1010
  root: string,
989
- channel: 'discord' | 'slack' | 'telegram' | 'webex' | 'line' | 'kakaotalk' | 'github',
1011
+ channel: 'discord' | 'slack' | 'telegram' | 'webex' | 'instagram' | 'line' | 'kakaotalk' | 'github',
990
1012
  ): Promise<boolean> {
991
1013
  const channels = new SecretsBackend(join(root, 'secrets.json')).tryReadChannelsSync()
992
1014
  if (channels === null) return false
@@ -1008,6 +1030,18 @@ export async function hasExistingChannelSecrets(
1008
1030
  // surfaced as a hard error inside `runAddChannel` to prevent silent
1009
1031
  // overwrites.
1010
1032
  return false
1033
+ case 'instagram': {
1034
+ const block = channels.instagram
1035
+ if (!isObjectRecord(block)) return false
1036
+ const current = (block as { currentAccount?: unknown }).currentAccount
1037
+ if (typeof current !== 'string' || current.length === 0) return false
1038
+ const accounts = (block as { accounts?: unknown }).accounts
1039
+ if (!isObjectRecord(accounts)) return false
1040
+ const account = accounts[current]
1041
+ if (!isObjectRecord(account)) return false
1042
+ const username = (account as { username?: unknown }).username
1043
+ return typeof username === 'string' && username.length > 0
1044
+ }
1011
1045
  case 'line': {
1012
1046
  // A usable LINE block needs a current account whose record carries an
1013
1047
  // auth_token. Unlike KakaoTalk there are no renewal fields (email +
@@ -1115,6 +1149,7 @@ export type ChannelKind =
1115
1149
  | 'telegram-bot'
1116
1150
  | 'webex'
1117
1151
  | 'webex-bot'
1152
+ | 'instagram'
1118
1153
  | 'line'
1119
1154
  | 'kakaotalk'
1120
1155
  | 'github'
@@ -1131,6 +1166,7 @@ export const CHANNEL_KINDS: ReadonlyArray<ChannelKind> = [
1131
1166
  'telegram-bot',
1132
1167
  'webex',
1133
1168
  'webex-bot',
1169
+ 'instagram',
1134
1170
  'line',
1135
1171
  'kakaotalk',
1136
1172
  'github',
@@ -1138,6 +1174,7 @@ export const CHANNEL_KINDS: ReadonlyArray<ChannelKind> = [
1138
1174
 
1139
1175
  export type AddChannelStep =
1140
1176
  | 'line-auth'
1177
+ | 'instagram-auth'
1141
1178
  | 'kakaotalk-auth'
1142
1179
  | 'webex-auth'
1143
1180
  | 'discord-auth'
@@ -1151,6 +1188,8 @@ export type AddChannelStepEvent =
1151
1188
  | { step: 'config'; phase: 'done' }
1152
1189
  | { step: 'line-auth'; phase: 'start' }
1153
1190
  | { step: 'line-auth'; phase: 'done'; result: LineAuthResult }
1191
+ | { step: 'instagram-auth'; phase: 'start' }
1192
+ | { step: 'instagram-auth'; phase: 'done'; result: InstagramAuthResult }
1154
1193
  | { step: 'kakaotalk-auth'; phase: 'start' }
1155
1194
  | { step: 'kakaotalk-auth'; phase: 'done'; result: KakaotalkAuthResult }
1156
1195
  | { step: 'webex-auth'; phase: 'start' }
@@ -1178,6 +1217,7 @@ export type AddChannelOptions = {
1178
1217
  | { channel: 'telegram-bot'; telegramBotToken: string }
1179
1218
  | { channel: 'webex-bot'; webexBotToken: string }
1180
1219
  | { channel: 'webex'; runWebexAuth: WebexAuthRunner }
1220
+ | { channel: 'instagram'; runInstagramAuth: InstagramAuthRunner }
1181
1221
  | { channel: 'line'; runLineAuth: LineAuthRunner }
1182
1222
  | { channel: 'kakaotalk'; runKakaotalkAuth: KakaotalkAuthRunner }
1183
1223
  | {
@@ -1215,6 +1255,13 @@ export async function runAddChannel(options: AddChannelOptions): Promise<void> {
1215
1255
  if (!result.ok) throw new Error(`LINE authentication failed: ${result.reason}`)
1216
1256
  }
1217
1257
 
1258
+ if (options.channel === 'instagram') {
1259
+ emit({ step: 'instagram-auth', phase: 'start' })
1260
+ const result = await options.runInstagramAuth({ cwd: options.cwd })
1261
+ emit({ step: 'instagram-auth', phase: 'done', result })
1262
+ if (!result.ok) throw new Error(`Instagram authentication failed: ${result.reason}`)
1263
+ }
1264
+
1218
1265
  if (options.channel === 'kakaotalk') {
1219
1266
  emit({ step: 'kakaotalk-auth', phase: 'start' })
1220
1267
  const result = await options.runKakaotalkAuth({ cwd: options.cwd })
@@ -1324,6 +1371,8 @@ function channelSecretsFromOptions(options: AddChannelOptions): ChannelSecrets {
1324
1371
  return { token: options.webexBotToken }
1325
1372
  case 'webex':
1326
1373
  return {}
1374
+ case 'instagram':
1375
+ return {}
1327
1376
  case 'line':
1328
1377
  // LINE auth writes its structured account block directly to
1329
1378
  // secrets.json#channels.line before config mutation.