typeclaw 0.41.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 (43) 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/session-origin.ts +1 -0
  7. package/src/agent/tools/channel-history-render.ts +21 -0
  8. package/src/agent/tools/channel-history.ts +2 -17
  9. package/src/agent/tools/channel-read.ts +206 -0
  10. package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +26 -2
  11. package/src/bundled-plugins/github-cli-auth/index.ts +25 -6
  12. package/src/bundled-plugins/memory/vector/hybrid.ts +73 -6
  13. package/src/bundled-plugins/memory/vector/passages.ts +2 -24
  14. package/src/bundled-plugins/memory/vector/truncation.ts +28 -0
  15. package/src/bundled-plugins/tool-result-cap/README.md +10 -1
  16. package/src/bundled-plugins/tool-result-cap/cap-result.ts +8 -0
  17. package/src/channels/adapters/discord-bot.ts +112 -0
  18. package/src/channels/adapters/instagram-channel-resolver.ts +113 -0
  19. package/src/channels/adapters/instagram-classify.ts +69 -0
  20. package/src/channels/adapters/instagram-format.ts +8 -0
  21. package/src/channels/adapters/instagram.ts +346 -0
  22. package/src/channels/adapters/slack-bot.ts +147 -0
  23. package/src/channels/manager.ts +60 -2
  24. package/src/channels/router.ts +64 -0
  25. package/src/channels/schema.ts +5 -0
  26. package/src/channels/types.ts +46 -0
  27. package/src/cli/channel.ts +76 -1
  28. package/src/cli/init.ts +1 -0
  29. package/src/cli/status.ts +37 -14
  30. package/src/config/channels-mutation.ts +2 -1
  31. package/src/doctor/channel-checks.ts +28 -0
  32. package/src/hostd/daemon.ts +11 -7
  33. package/src/hostd/protocol.ts +2 -0
  34. package/src/init/index.ts +50 -1
  35. package/src/init/instagram-auth.ts +134 -0
  36. package/src/init/run-owner-claim.ts +1 -0
  37. package/src/permissions/match-rule.ts +1 -1
  38. package/src/permissions/resolve.ts +1 -0
  39. package/src/role-claim/match-rule.ts +2 -1
  40. package/src/secrets/instagram-store.ts +112 -0
  41. package/src/secrets/schema.ts +18 -0
  42. package/src/skills/typeclaw-channel-instagram/SKILL.md +30 -0
  43. package/typeclaw.schema.json +161 -1
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.
@@ -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',
@@ -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',
@@ -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.