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
@@ -0,0 +1,134 @@
1
+ import { join } from 'node:path'
2
+
3
+ import {
4
+ createAccountId,
5
+ InstagramClient as RealInstagramClient,
6
+ InstagramCredentialManager,
7
+ type InstagramAccount,
8
+ } from 'agent-messenger/instagram'
9
+
10
+ import { SecretsInstagramCredentialStore } from '@/secrets/instagram-store'
11
+
12
+ export type InstagramBootstrapStatus = { ok: true } | { ok: false; reason: string }
13
+
14
+ export type InstagramLoginInput = {
15
+ username: string
16
+ password: string
17
+ agentDir: string
18
+ client?: InstagramLoginClient
19
+ credentialManager?: InstagramLoginCredentialManager
20
+ }
21
+
22
+ export type InstagramAuthenticateResult = {
23
+ userId: string
24
+ requiresTwoFactor?: boolean
25
+ twoFactorInfo?: Record<string, unknown>
26
+ challengeRequired?: boolean
27
+ challengePath?: string
28
+ }
29
+
30
+ export type InstagramLoginClient = {
31
+ authenticate(username: string, password: string): Promise<InstagramAuthenticateResult>
32
+ setSessionPath(path: string): void
33
+ getUserId(): string | null
34
+ }
35
+
36
+ export type InstagramLoginCredentialManager = {
37
+ ensureAccountPaths(accountId: string): Promise<{ session_path: string }>
38
+ getAccount(accountId?: string): Promise<InstagramAccount | null>
39
+ setAccount(account: InstagramAccount): Promise<void>
40
+ setCurrent(accountId: string): Promise<boolean>
41
+ }
42
+
43
+ export function instagramSecretsPath(agentDir: string): string {
44
+ return join(agentDir, 'secrets.json')
45
+ }
46
+
47
+ export function instagramConfigDir(agentDir: string): string {
48
+ return join(agentDir, 'workspace', '.agent-messenger')
49
+ }
50
+
51
+ export async function runInstagramBootstrap(input: InstagramLoginInput): Promise<InstagramBootstrapStatus> {
52
+ try {
53
+ const store = new SecretsInstagramCredentialStore({
54
+ mode: 'host',
55
+ secretsPath: instagramSecretsPath(input.agentDir),
56
+ })
57
+ const result = await withInstagramConfigDir(
58
+ instagramConfigDir(input.agentDir),
59
+ async (): Promise<InstagramBootstrapStatus> => {
60
+ const sdkManager = new InstagramCredentialManager()
61
+ const manager = input.credentialManager ?? sdkManager
62
+ const accountId = createAccountId(input.username)
63
+ const paths = await manager.ensureAccountPaths(accountId)
64
+ const client = input.client ?? buildInstagramClient(sdkManager)
65
+ client.setSessionPath(paths.session_path)
66
+ const auth = await client.authenticate(input.username, input.password)
67
+ if (auth.requiresTwoFactor) return unsupportedTwoFactor()
68
+ if (auth.challengeRequired) return unsupportedChallenge()
69
+ const userId = auth.userId || client.getUserId()
70
+ if (userId === null || userId === '') return { ok: false, reason: 'Instagram login did not authenticate' }
71
+
72
+ const now = new Date().toISOString()
73
+ await manager.setAccount({
74
+ account_id: accountId,
75
+ username: input.username,
76
+ pk: userId,
77
+ created_at: now,
78
+ updated_at: now,
79
+ })
80
+ await manager.setCurrent(accountId)
81
+
82
+ const sdkAccount = await manager.getAccount(accountId)
83
+ if (sdkAccount === null) {
84
+ return { ok: false, reason: 'Instagram login authenticated but did not persist SDK credentials' }
85
+ }
86
+ await store.setAccount({
87
+ account_id: sdkAccount.account_id,
88
+ username: sdkAccount.username,
89
+ ...(sdkAccount.full_name !== undefined ? { full_name: sdkAccount.full_name } : {}),
90
+ ...(sdkAccount.profile_pic_url !== undefined ? { profile_pic_url: sdkAccount.profile_pic_url } : {}),
91
+ ...(sdkAccount.pk !== undefined ? { pk: sdkAccount.pk } : {}),
92
+ created_at: sdkAccount.created_at,
93
+ updated_at: sdkAccount.updated_at,
94
+ })
95
+ await store.setCurrentAccount(sdkAccount.account_id)
96
+ return { ok: true }
97
+ },
98
+ )
99
+ return result
100
+ } catch (err) {
101
+ return { ok: false, reason: err instanceof Error ? err.message : String(err) }
102
+ }
103
+ }
104
+
105
+ function buildInstagramClient(manager: InstagramCredentialManager): InstagramLoginClient {
106
+ return new RealInstagramClient(manager) as unknown as InstagramLoginClient
107
+ }
108
+
109
+ function unsupportedTwoFactor(): InstagramBootstrapStatus {
110
+ return {
111
+ ok: false,
112
+ reason:
113
+ 'Instagram account requires 2FA/checkpoint, which is not yet supported by the typeclaw Instagram channel. Disable 2FA on a dedicated agent account, or complete the checkpoint in a browser first.',
114
+ }
115
+ }
116
+
117
+ function unsupportedChallenge(): InstagramBootstrapStatus {
118
+ return {
119
+ ok: false,
120
+ reason:
121
+ 'Instagram account requires 2FA/checkpoint, which is not yet supported by the typeclaw Instagram channel. Disable 2FA on a dedicated agent account, or complete the checkpoint in a browser first.',
122
+ }
123
+ }
124
+
125
+ async function withInstagramConfigDir<T>(dir: string, fn: () => Promise<T>): Promise<T> {
126
+ const previous = process.env.AGENT_MESSENGER_CONFIG_DIR
127
+ process.env.AGENT_MESSENGER_CONFIG_DIR = dir
128
+ try {
129
+ return await fn()
130
+ } finally {
131
+ if (previous === undefined) delete process.env.AGENT_MESSENGER_CONFIG_DIR
132
+ else process.env.AGENT_MESSENGER_CONFIG_DIR = previous
133
+ }
134
+ }
@@ -14,6 +14,7 @@ const CHANNEL_LABELS: Record<ChannelKind, string> = {
14
14
  'telegram-bot': 'Telegram',
15
15
  webex: 'Webex (User)',
16
16
  'webex-bot': 'Webex',
17
+ instagram: 'Instagram',
17
18
  line: 'LINE',
18
19
  kakaotalk: 'KakaoTalk',
19
20
  }
@@ -16,7 +16,7 @@
16
16
  // error messages with typo suggestions; a single big regex would only ever
17
17
  // say "didn't match".
18
18
 
19
- export const PLATFORMS = ['slack', 'discord', 'telegram', 'webex', 'line', 'kakao', 'github'] as const
19
+ export const PLATFORMS = ['slack', 'discord', 'telegram', 'webex', 'instagram', 'line', 'kakao', 'github'] as const
20
20
  export type Platform = (typeof PLATFORMS)[number]
21
21
 
22
22
  const SUBAGENT_NAME = /^[a-z][a-z0-9-]*$/
@@ -9,6 +9,7 @@ const ADAPTER_TO_PLATFORM: Record<AdapterId, Platform> = {
9
9
  discord: 'discord',
10
10
  'discord-bot': 'discord',
11
11
  github: 'github',
12
+ instagram: 'instagram',
12
13
  'telegram-bot': 'telegram',
13
14
  webex: 'webex',
14
15
  'webex-bot': 'webex',
@@ -89,6 +89,7 @@ export {
89
89
  type RegisteredCommand,
90
90
  type RegisteredCronJob,
91
91
  type RegisteredDoctorCheck,
92
+ type RegisteredPluginDisposer,
92
93
  type RegisteredSkillDir,
93
94
  type RegisteredSkillEntry,
94
95
  type RegisteredSubagent,
@@ -51,6 +51,7 @@ export type LoadPluginsResult = {
51
51
  failedPlugins: FailedPlugin[]
52
52
  markBooted: () => void
53
53
  setSpawnSubagent: (fn: SpawnSubagentFn) => void
54
+ disposePlugins: () => Promise<void>
54
55
  }
55
56
 
56
57
  export async function loadPlugins(opts: LoadPluginsOptions): Promise<LoadPluginsResult> {
@@ -181,9 +182,22 @@ export async function loadPlugins(opts: LoadPluginsOptions): Promise<LoadPlugins
181
182
  setSpawnSubagent: (fn) => {
182
183
  spawnSubagentImpl = fn
183
184
  },
185
+ disposePlugins: () => disposePlugins(registry),
184
186
  }
185
187
  }
186
188
 
189
+ async function disposePlugins(registry: PluginRegistry): Promise<void> {
190
+ await Promise.all(
191
+ registry.disposers.map(async (disposer) => {
192
+ try {
193
+ await disposer.dispose()
194
+ } catch (err) {
195
+ disposer.logger.warn(`onDispose failed: ${err instanceof Error ? err.message : String(err)}`)
196
+ }
197
+ }),
198
+ )
199
+ }
200
+
187
201
  // Tags WHICH sub-phase failed (for the failedPlugins report) while preserving
188
202
  // the ORIGINAL error so the caller can keep PluginSecurityError fatal even when
189
203
  // it surfaces deep inside registration.
@@ -34,6 +34,11 @@ export type RegisteredCommand = {
34
34
  command: PluginCommand
35
35
  logger: PluginLogger
36
36
  }
37
+ export type RegisteredPluginDisposer = {
38
+ pluginName: string
39
+ logger: PluginLogger
40
+ dispose: () => void | Promise<void>
41
+ }
37
42
 
38
43
  export type PluginRegistry = {
39
44
  tools: RegisteredTool[]
@@ -43,6 +48,7 @@ export type PluginRegistry = {
43
48
  skillsDirs: RegisteredSkillDir[]
44
49
  doctorChecks: RegisteredDoctorCheck[]
45
50
  commands: RegisteredCommand[]
51
+ disposers: RegisteredPluginDisposer[]
46
52
  }
47
53
 
48
54
  export type RegisterContributionsOptions = {
@@ -159,6 +165,10 @@ export function registerContributions(opts: RegisterContributionsOptions): void
159
165
  registry.commands.push({ pluginName, commandName, command, logger })
160
166
  }
161
167
  }
168
+
169
+ if (ex.onDispose) {
170
+ registry.disposers.push({ pluginName, logger, dispose: ex.onDispose })
171
+ }
162
172
  }
163
173
 
164
174
  export function discardRegistrationsBy(pluginName: string, registry: PluginRegistry, hooks: HookBus): void {
@@ -169,6 +179,7 @@ export function discardRegistrationsBy(pluginName: string, registry: PluginRegis
169
179
  registry.skillsDirs = registry.skillsDirs.filter((d) => d.pluginName !== pluginName)
170
180
  registry.doctorChecks = registry.doctorChecks.filter((d) => d.pluginName !== pluginName)
171
181
  registry.commands = registry.commands.filter((c) => c.pluginName !== pluginName)
182
+ registry.disposers = registry.disposers.filter((d) => d.pluginName !== pluginName)
172
183
  hooks.unregisterAll(pluginName)
173
184
  }
174
185
 
@@ -181,6 +192,7 @@ export function emptyRegistry(): PluginRegistry {
181
192
  skillsDirs: [],
182
193
  doctorChecks: [],
183
194
  commands: [],
195
+ disposers: [],
184
196
  }
185
197
  }
186
198
 
@@ -294,6 +294,10 @@ export type PluginExports = {
294
294
  skillsDirs?: string[]
295
295
  hooks?: Hooks
296
296
  doctorChecks?: Record<string, PluginDoctorCheck>
297
+ // Released once when the agent stops, for plugin-lifetime resources a GC can't
298
+ // reclaim deterministically (open DB handles, timers). Disposers are isolated:
299
+ // one throwing never blocks the others.
300
+ onDispose?: () => void | Promise<void>
297
301
  }
298
302
 
299
303
  // `typeclaw doctor` plugin extension surface. Each check is read-only by
@@ -27,13 +27,14 @@ export type PartialChannelOrigin = {
27
27
 
28
28
  const ADAPTER_TO_PLATFORM: Record<
29
29
  ChannelKey['adapter'],
30
- 'slack' | 'discord' | 'telegram' | 'webex' | 'kakao' | 'line' | 'github'
30
+ 'slack' | 'discord' | 'telegram' | 'webex' | 'kakao' | 'line' | 'github' | 'instagram'
31
31
  > = {
32
32
  slack: 'slack',
33
33
  'slack-bot': 'slack',
34
34
  discord: 'discord',
35
35
  'discord-bot': 'discord',
36
36
  github: 'github',
37
+ instagram: 'instagram',
37
38
  'telegram-bot': 'telegram',
38
39
  webex: 'webex',
39
40
  'webex-bot': 'webex',
package/src/run/index.ts CHANGED
@@ -125,24 +125,32 @@ export type StartAgentResult = {
125
125
  stop: () => void | Promise<void>
126
126
  }
127
127
 
128
- // Thin wrapper that owns ONLY the boot-failure cleanup of process-global
129
- // installs. `installCodexFetchObserver` and `installFatalGuard` attach
130
- // process-wide listeners before the fallible boot work; if any boot step throws
131
- // before `startAgentRuntime` returns, the caller never receives a
132
- // `StartAgentResult` and can never call `stop()`, so those listeners would
133
- // strand and double-fire into the next `startAgent`. The runtime hands its
134
- // disposer back via `onProcessGlobalsInstalled`; on a boot throw we dispose and
128
+ // Owns boot-failure cleanup for everything installed before `startAgentRuntime`
129
+ // returns a `StartAgentResult`. `installCodexFetchObserver`/`installFatalGuard`
130
+ // attach process-wide listeners, and `loadPlugins` opens plugin-lifetime
131
+ // resources (the memory plugin's sqlite handle); if any boot step throws before
132
+ // the result exists, the caller never receives `stop()`, so each of those would
133
+ // strand. The runtime registers each cleanup via `registerBootCleanup` as boot
134
+ // progresses; on a throw we run them all (newest first, best-effort) and
135
135
  // rethrow, on success ownership transfers to the returned `stop()`. `return
136
136
  // await` is load-bearing — without it an async boot rejection would escape this
137
- // try. Dispose is idempotent, so the success path's `stop()` never double-fires.
137
+ // try. Cleanups are idempotent, so the success path's `stop()` never double-fires.
138
138
  export async function startAgent(options: StartAgentOptions): Promise<StartAgentResult> {
139
- const captured: { dispose: (() => void) | null } = { dispose: null }
139
+ const bootCleanups: Array<() => void | Promise<void>> = []
140
140
  try {
141
- return await startAgentRuntime(options, (dispose) => {
142
- captured.dispose = dispose
141
+ return await startAgentRuntime(options, (cleanup) => {
142
+ bootCleanups.push(cleanup)
143
143
  })
144
144
  } catch (err) {
145
- captured.dispose?.()
145
+ for (const cleanup of bootCleanups.reverse()) {
146
+ try {
147
+ await cleanup()
148
+ } catch (cleanupErr) {
149
+ console.warn(
150
+ `[run] boot-failure cleanup error: ${cleanupErr instanceof Error ? cleanupErr.message : cleanupErr}`,
151
+ )
152
+ }
153
+ }
146
154
  throw err
147
155
  }
148
156
  }
@@ -161,7 +169,7 @@ async function startAgentRuntime(
161
169
  createChannelManager: createChannelManagerFor = createChannelManager,
162
170
  createTunnelManager: createTunnelManagerFor = createTunnelManager,
163
171
  }: StartAgentOptions,
164
- onProcessGlobalsInstalled: (dispose: () => void) => void,
172
+ registerBootCleanup: (cleanup: () => void | Promise<void>) => void,
165
173
  ): Promise<StartAgentResult> {
166
174
  const reloadRegistry = new ReloadRegistry()
167
175
 
@@ -216,7 +224,7 @@ async function startAgentRuntime(
216
224
  if (sigtermHandler !== null) process.removeListener('SIGTERM', sigtermHandler)
217
225
  }
218
226
  let sigtermHandler: (() => void) | null = null
219
- onProcessGlobalsInstalled(disposeProcessGlobals)
227
+ registerBootCleanup(disposeProcessGlobals)
220
228
 
221
229
  const { config: cwdConfig, pluginConfigs: pluginConfigsByName } = loadConfigBundleSync(cwd)
222
230
  const githubTokenBridge = createGithubTokenBridge()
@@ -261,6 +269,9 @@ async function startAgentRuntime(
261
269
  if (mcpManager !== null) await mcpManager.closeAll()
262
270
  throw err
263
271
  }
272
+ // Plugins are loaded (sqlite handles open); from here any boot failure must
273
+ // release them — the caller gets no stop() on the failure path.
274
+ registerBootCleanup(() => pluginsLoaded.disposePlugins())
264
275
 
265
276
  reloadRegistry.register(
266
277
  createConfigReloadable({
@@ -555,6 +566,7 @@ async function startAgentRuntime(
555
566
  return name
556
567
  },
557
568
  })
569
+ registerBootCleanup(() => subagentConsumer.stop())
558
570
  subagentConsumer.start()
559
571
 
560
572
  // Populated by startScheduler's factory (onCountStore). The consumer
@@ -693,11 +705,13 @@ async function startAgentRuntime(
693
705
  // delivers only to live subscribers (no replay), so a fire published before
694
706
  // the subscription exists would be lost. Subscribing to an empty stream is
695
707
  // harmless when there are no jobs.
708
+ registerBootCleanup(() => cronConsumer.stop())
696
709
  cronConsumer.start()
697
710
  const scheduler = await startScheduler({
698
711
  cwd,
699
712
  loadCron,
700
713
  createSchedulerFor: factory,
714
+ registerBootCleanup,
701
715
  stream,
702
716
  hasInternalJobs: internalJobs().length > 0,
703
717
  getSubagents: () => pluginRuntime.get().subagents,
@@ -713,6 +727,7 @@ async function startAgentRuntime(
713
727
  }
714
728
 
715
729
  const tunnelBridge: TunnelBridge = createTunnelBridge({ stream, channelManager })
730
+ registerBootCleanup(() => tunnelBridge.stop())
716
731
 
717
732
  // Bridge `subagent.completed` broadcasts into the channel router so a
718
733
  // backgrounded subagent finishing wakes up its parent channel session
@@ -723,6 +738,7 @@ async function startAgentRuntime(
723
738
  stream,
724
739
  router: channelManager.router,
725
740
  })
741
+ registerBootCleanup(() => subagentCompletionBridge.stop())
726
742
 
727
743
  // Fan a landed formal review verdict out to the sibling sessions reviewing the
728
744
  // same PR so they stand down from a redundant verdict (the per-thread fan-out
@@ -733,12 +749,14 @@ async function startAgentRuntime(
733
749
  stream,
734
750
  router: channelManager.router,
735
751
  })
752
+ registerBootCleanup(() => prVerdictActivityBridge.stop())
736
753
  setReviewObserver((review) => {
737
754
  stream.publish({
738
755
  target: { kind: 'broadcast' },
739
756
  payload: { kind: 'pr.verdict-activity', ...review },
740
757
  })
741
758
  })
759
+ registerBootCleanup(() => setReviewObserver(null))
742
760
 
743
761
  // Registered before channels so its cache clear lands before any channel
744
762
  // session teardown observes it. secrets.json provider credentials are not
@@ -773,6 +791,7 @@ async function startAgentRuntime(
773
791
  console.warn(`[run] channel restart-resume reserve failed: ${err instanceof Error ? err.message : err}`)
774
792
  }
775
793
 
794
+ registerBootCleanup(() => channelManager.stop())
776
795
  await channelManager.start()
777
796
 
778
797
  if (restartReservation !== null) {
@@ -903,7 +922,7 @@ async function startAgentRuntime(
903
922
  ...mcpManagerOpt,
904
923
  })
905
924
 
906
- const server = createServer({
925
+ const serverFactory = createServer({
907
926
  port,
908
927
  reloadAll: () => reloadRegistry.reloadAll(),
909
928
  reloadRegistry,
@@ -924,23 +943,26 @@ async function startAgentRuntime(
924
943
  ...runtimeVersionOpt,
925
944
  ...tuiTokenOpt,
926
945
  ...containerBrokerOpt,
927
- }).start()
946
+ })
947
+ let server: BunServer | null = null
948
+ registerBootCleanup(() => server?.stop(true))
949
+ server = serverFactory.start()
928
950
 
929
951
  // Tunnel manager starts AFTER the WS server is up so a slow/hanging
930
952
  // provider (PR 2's cloudflared first-URL wait) cannot block TUI, reload,
931
953
  // or channel adapter availability. External providers resolve URLs
932
954
  // synchronously; future managed providers will resolve asynchronously
933
955
  // and broadcast URL events when ready.
956
+ registerBootCleanup(() => tunnelManager.stop())
934
957
  await tunnelManager.start()
935
958
 
936
959
  let stopped = false
937
960
  const stop = async () => {
938
961
  if (stopped) return
939
962
  stopped = true
940
- // The crash-guard and codex-observer disposers run in `finally` so an
941
- // earlier async teardown rejection (tunnel/channel/mcp stop) cannot strand
942
- // the process-global listeners they removed — a stranded fatal-guard
943
- // listener would survive into the next `startAgent` and double-fire.
963
+ // The final disposers run in `finally` so an earlier async teardown
964
+ // rejection cannot strand process-global listeners or plugin-owned handles
965
+ // into the next `startAgent`.
944
966
  try {
945
967
  scheduler?.stop()
946
968
  cronConsumer.stop()
@@ -955,6 +977,7 @@ async function startAgentRuntime(
955
977
  await channelManager.stop()
956
978
  await mcpManager?.closeAll()
957
979
  } finally {
980
+ await pluginsLoaded.disposePlugins()
958
981
  disposeProcessGlobals()
959
982
  }
960
983
  }
@@ -1079,6 +1102,7 @@ async function startScheduler({
1079
1102
  cwd,
1080
1103
  loadCron,
1081
1104
  createSchedulerFor,
1105
+ registerBootCleanup,
1082
1106
  stream,
1083
1107
  hasInternalJobs,
1084
1108
  getSubagents,
@@ -1087,6 +1111,7 @@ async function startScheduler({
1087
1111
  cwd: string
1088
1112
  loadCron: LoadCronFn
1089
1113
  createSchedulerFor: SchedulerFactory
1114
+ registerBootCleanup: (cleanup: () => void | Promise<void>) => void
1090
1115
  stream: Stream
1091
1116
  hasInternalJobs: boolean
1092
1117
  getSubagents?: () => SubagentRegistry
@@ -1111,6 +1136,7 @@ async function startScheduler({
1111
1136
  stream.publish({ target: { kind: 'cron', jobId: job.id }, payload: job })
1112
1137
  }
1113
1138
  const scheduler = await createSchedulerFor({ cwd, file, onFire, onCountStore })
1139
+ registerBootCleanup(() => scheduler.stop())
1114
1140
  scheduler.start()
1115
1141
  return scheduler
1116
1142
  }
@@ -0,0 +1,112 @@
1
+ import { sendHttp } from '@/hostd/client'
2
+
3
+ import { type InstagramAccountRecord, type InstagramChannelBlock, instagramChannelBlockSchema } from './schema'
4
+ import { SecretsBackend } from './storage'
5
+
6
+ export type SecretsInstagramCredentialStoreOptions =
7
+ | { mode: 'host'; secretsPath: string }
8
+ | { mode: 'container'; secretsPath: string; hostdUrl: string; restartToken: string; containerName: string }
9
+
10
+ const EMPTY_BLOCK: InstagramChannelBlock = { currentAccount: null, accounts: {} }
11
+
12
+ export class SecretsInstagramCredentialStore {
13
+ private readonly backend: SecretsBackend
14
+ private writeChain: Promise<void> = Promise.resolve()
15
+
16
+ constructor(private readonly options: SecretsInstagramCredentialStoreOptions) {
17
+ this.backend = new SecretsBackend(options.secretsPath)
18
+ }
19
+
20
+ async load(): Promise<InstagramConfig> {
21
+ return toInstagramConfig(this.readBlock())
22
+ }
23
+
24
+ async save(config: InstagramConfig): Promise<void> {
25
+ await this.writeBlock(() => fromInstagramConfig(config))
26
+ }
27
+
28
+ async getAccount(id?: string): Promise<InstagramAccountRecord | null> {
29
+ const config = await this.load()
30
+ if (id) return config.accounts[id] ?? null
31
+ if (!config.current) return null
32
+ return config.accounts[config.current] ?? null
33
+ }
34
+
35
+ async setAccount(account: InstagramAccountRecord): Promise<void> {
36
+ await this.writeBlock((block) => {
37
+ const accounts = { ...block.accounts, [account.account_id]: account }
38
+ return { ...block, currentAccount: block.currentAccount ?? account.account_id, accounts }
39
+ })
40
+ }
41
+
42
+ async removeAccount(id: string): Promise<void> {
43
+ await this.writeBlock((block) => {
44
+ const accounts = { ...block.accounts }
45
+ delete accounts[id]
46
+ const currentAccount = block.currentAccount === id ? (Object.keys(accounts)[0] ?? null) : block.currentAccount
47
+ return { ...block, currentAccount, accounts }
48
+ })
49
+ }
50
+
51
+ async listAccounts(): Promise<Array<InstagramAccountRecord & { is_current: boolean }>> {
52
+ const config = await this.load()
53
+ return Object.values(config.accounts).map((account) => ({
54
+ ...account,
55
+ is_current: account.account_id === config.current,
56
+ }))
57
+ }
58
+
59
+ async setCurrentAccount(id: string): Promise<void> {
60
+ await this.writeBlock((block) => ({ ...block, currentAccount: id }))
61
+ }
62
+
63
+ private readBlock(): InstagramChannelBlock {
64
+ const channels =
65
+ this.options.mode === 'container' ? this.backend.tryReadChannelsSync() : this.backend.readChannelsSync()
66
+ return parseBlock(channels?.instagram)
67
+ }
68
+
69
+ private async writeBlock(update: (current: InstagramChannelBlock) => InstagramChannelBlock): Promise<void> {
70
+ return this.enqueueWrite(async () => {
71
+ if (this.options.mode === 'container') {
72
+ const next = update(this.readBlock())
73
+ const response = await sendHttp(
74
+ {
75
+ kind: 'secrets-patch',
76
+ containerName: this.options.containerName,
77
+ patch: { channels: { instagram: next } },
78
+ },
79
+ { url: this.options.hostdUrl, token: this.options.restartToken },
80
+ )
81
+ if (!response.ok) throw new Error(`secrets-patch failed: ${response.reason}`)
82
+ return
83
+ }
84
+
85
+ await this.backend.updateChannelsAsync(async (channels) => {
86
+ const next = { ...channels, instagram: update(parseBlock(channels.instagram)) }
87
+ return { result: undefined, next }
88
+ })
89
+ })
90
+ }
91
+
92
+ private enqueueWrite(op: () => Promise<void>): Promise<void> {
93
+ const next = this.writeChain.then(op, op)
94
+ this.writeChain = next.catch(() => {})
95
+ return next
96
+ }
97
+ }
98
+
99
+ function parseBlock(value: unknown): InstagramChannelBlock {
100
+ if (value === undefined) return EMPTY_BLOCK
101
+ return instagramChannelBlockSchema.parse(value)
102
+ }
103
+
104
+ export type InstagramConfig = { current: string | null; accounts: Record<string, InstagramAccountRecord> }
105
+
106
+ function toInstagramConfig(block: InstagramChannelBlock): InstagramConfig {
107
+ return { current: block.currentAccount, accounts: block.accounts }
108
+ }
109
+
110
+ function fromInstagramConfig(config: InstagramConfig): InstagramChannelBlock {
111
+ return { currentAccount: config.current, accounts: config.accounts }
112
+ }
@@ -90,6 +90,21 @@ export const lineChannelBlockSchema = z.object({
90
90
  accounts: z.record(z.string(), lineAccountRecordSchema),
91
91
  })
92
92
 
93
+ export const instagramAccountRecordSchema = z.object({
94
+ account_id: z.string(),
95
+ username: z.string(),
96
+ full_name: z.string().optional(),
97
+ profile_pic_url: z.string().optional(),
98
+ pk: z.string().optional(),
99
+ created_at: z.string(),
100
+ updated_at: z.string(),
101
+ })
102
+
103
+ export const instagramChannelBlockSchema = z.object({
104
+ currentAccount: z.string().nullable(),
105
+ accounts: z.record(z.string(), instagramAccountRecordSchema),
106
+ })
107
+
93
108
  // Encrypted password envelope produced by src/secrets/encryption.ts. Optional
94
109
  // in the schema because legacy v2 accounts (pre-renewal feature) don't have
95
110
  // one; the renewal cron treats a missing envelope as "reauth required" and
@@ -193,6 +208,7 @@ export const channelsSchema = z
193
208
  github: githubChannelSchema.optional(),
194
209
  'telegram-bot': telegramBotChannelSchema.optional(),
195
210
  line: lineChannelBlockSchema.optional(),
211
+ instagram: instagramChannelBlockSchema.optional(),
196
212
  kakaotalk: kakaoChannelBlockSchema.optional(),
197
213
  webex: webexChannelBlockSchema.optional(),
198
214
  slack: slackChannelBlockSchema.optional(),
@@ -220,6 +236,8 @@ export type DiscordAccountRecord = z.infer<typeof discordAccountRecordSchema>
220
236
  export type DiscordChannelBlock = z.infer<typeof discordChannelBlockSchema>
221
237
  export type LineAccountRecord = z.infer<typeof lineAccountRecordSchema>
222
238
  export type LineChannelBlock = z.infer<typeof lineChannelBlockSchema>
239
+ export type InstagramAccountRecord = z.infer<typeof instagramAccountRecordSchema>
240
+ export type InstagramChannelBlock = z.infer<typeof instagramChannelBlockSchema>
223
241
  export type KakaoAccountRecord = z.infer<typeof kakaoAccountRecordSchema>
224
242
  export type PendingLoginRecord = z.infer<typeof kakaoPendingLoginRecordSchema>
225
243
  export type KakaoChannelBlock = z.infer<typeof kakaoChannelBlockSchema>
@@ -0,0 +1,30 @@
1
+ ---
2
+ name: typeclaw-channel-instagram
3
+ description: Use this skill BEFORE every `channel_reply` or `channel_send` call whose adapter is `instagram`. Instagram DMs render messages as plain text — no markdown, no surfaced @-mention syntax, no threads, and no outbound attachments or stickers. Read this skill before composing anything on Instagram.
4
+ ---
5
+
6
+ # typeclaw-channel-instagram
7
+
8
+ You are speaking through the `instagram` channel adapter as a personal Instagram account.
9
+
10
+ Write plain text. The adapter strips common markdown as a safety net, but Instagram DMs do not provide rich text in this adapter.
11
+
12
+ Do not rely on:
13
+
14
+ - Markdown formatting, tables, or code fences.
15
+ - `@mention` syntax surfaced to the adapter. Address people by name in text.
16
+ - Threads or replies-with-quote. Every send is a top-level message.
17
+ - Outbound attachments, media, or stickers. The adapter sends text only via `sendMessage`.
18
+
19
+ Inbound media may be observed as metadata, but bytes are not fetchable through this adapter. Do not invent attachment ids.
20
+
21
+ Workspaces:
22
+
23
+ - `@instagram-dm` — a 1:1 direct message.
24
+ - `@instagram-group` — a group thread.
25
+
26
+ Engagement: every DM message engages. Groups are alias-only because the SDK summary does not surface native @-mention metadata.
27
+
28
+ Realtime vs polling transport is automatic and invisible to you: TypeClaw uses the hybrid listener when available and falls back to polling on older SDKs.
29
+
30
+ 2FA/checkpointed Instagram accounts are unsupported for this adapter; the operator must use a dedicated account that can authenticate without those challenges.