typeclaw 0.38.0 → 0.38.1

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 (40) hide show
  1. package/auth.schema.json +109 -0
  2. package/package.json +2 -2
  3. package/secrets.schema.json +109 -0
  4. package/src/agent/session-origin.ts +15 -2
  5. package/src/bundled-plugins/memory/README.md +12 -1
  6. package/src/bundled-plugins/memory/index.ts +39 -2
  7. package/src/channels/adapters/kakaotalk.ts +1 -1
  8. package/src/channels/adapters/webex-bot-classify.ts +20 -14
  9. package/src/channels/adapters/webex-bot-reference.ts +8 -6
  10. package/src/channels/adapters/webex-bot.ts +106 -39
  11. package/src/channels/adapters/webex-channel-resolver.ts +29 -0
  12. package/src/channels/adapters/webex-classify.ts +104 -0
  13. package/src/channels/adapters/webex-format.ts +53 -0
  14. package/src/channels/adapters/webex-id-ref.ts +32 -0
  15. package/src/channels/adapters/webex-reference.ts +49 -0
  16. package/src/channels/adapters/webex.ts +493 -0
  17. package/src/channels/manager.ts +63 -7
  18. package/src/channels/persistence.ts +67 -5
  19. package/src/channels/router.ts +8 -0
  20. package/src/channels/schema.ts +2 -0
  21. package/src/cli/channel.ts +118 -7
  22. package/src/cli/init.ts +70 -1
  23. package/src/config/channels-mutation.ts +2 -1
  24. package/src/doctor/channel-checks.ts +43 -0
  25. package/src/hostd/daemon.ts +7 -5
  26. package/src/hostd/protocol.ts +2 -2
  27. package/src/init/checkpoint.ts +1 -1
  28. package/src/init/index.ts +60 -3
  29. package/src/init/run-owner-claim.ts +1 -0
  30. package/src/init/webex-auth.ts +68 -0
  31. package/src/inspect/label.ts +13 -2
  32. package/src/inspect/render.ts +5 -3
  33. package/src/permissions/resolve.ts +38 -1
  34. package/src/role-claim/match-rule.ts +5 -1
  35. package/src/secrets/codex-auth-json.ts +52 -17
  36. package/src/secrets/encryption.ts +5 -1
  37. package/src/secrets/export-codex-auth-file.ts +26 -3
  38. package/src/secrets/schema.ts +35 -0
  39. package/src/secrets/webex-store.ts +113 -0
  40. package/typeclaw.schema.json +160 -0
@@ -21,7 +21,7 @@ export const INIT_CHECKPOINT_PATH = join('.typeclaw', 'init-progress.json')
21
21
 
22
22
  export const WIZARD_CHECKPOINT_VERSION = 1
23
23
 
24
- export type WizardChannelChoice = 'slack' | 'discord' | 'telegram' | 'kakaotalk' | 'github' | 'none'
24
+ export type WizardChannelChoice = 'slack' | 'discord' | 'telegram' | 'webex' | 'kakaotalk' | 'github' | 'none'
25
25
 
26
26
  export type AuthMethod = 'api-key' | 'oauth'
27
27
 
package/src/init/index.ts CHANGED
@@ -84,6 +84,7 @@ export type InitStep =
84
84
  | 'oauth-login'
85
85
  | 'scaffold'
86
86
  | 'kakaotalk-auth'
87
+ | 'webex-auth'
87
88
  | 'github-webhooks'
88
89
  | 'install'
89
90
  | 'dockerfile'
@@ -91,6 +92,7 @@ export type InitStep =
91
92
  | 'hatching'
92
93
 
93
94
  export type KakaotalkAuthResult = { ok: true } | { ok: false; reason: string }
95
+ export type WebexAuthResult = { ok: true } | { ok: false; reason: string }
94
96
 
95
97
  // Structured credential block for the GitHub channel adapter. Mirrors the
96
98
  // shape `runAddChannel({ channel: 'github', ... })` consumes so the wizard
@@ -126,6 +128,8 @@ export type InitStepEvent =
126
128
  | { step: 'scaffold'; phase: 'done' }
127
129
  | { step: 'kakaotalk-auth'; phase: 'start' }
128
130
  | { step: 'kakaotalk-auth'; phase: 'done'; result: KakaotalkAuthResult }
131
+ | { step: 'webex-auth'; phase: 'start' }
132
+ | { step: 'webex-auth'; phase: 'done'; result: WebexAuthResult }
129
133
  | { step: 'github-webhooks'; phase: 'start' }
130
134
  | { step: 'github-webhooks'; phase: 'done'; result: EagerGithubWebhookInstallResult }
131
135
  | { step: 'install'; phase: 'start' }
@@ -154,6 +158,7 @@ export type HatchRunner = (options: {
154
158
  }) => Promise<HatchingResult>
155
159
 
156
160
  export type KakaotalkAuthRunner = (options: { cwd: string }) => Promise<KakaotalkAuthResult>
161
+ export type WebexAuthRunner = (options: { cwd: string }) => Promise<WebexAuthResult>
157
162
 
158
163
  export type LineAuthResult = { ok: true } | { ok: false; reason: string }
159
164
  export type LineAuthRunner = (options: { cwd: string }) => Promise<LineAuthResult>
@@ -209,9 +214,11 @@ export type InitOptions = {
209
214
  withSlack?: boolean
210
215
  withTelegram?: boolean
211
216
  withWebex?: boolean
217
+ withWebexUser?: boolean
212
218
  withKakaotalk?: boolean
213
219
  withGithub?: boolean
214
220
  runKakaotalkAuth?: KakaotalkAuthRunner
221
+ runWebexAuth?: WebexAuthRunner
215
222
  // Structured GitHub credentials collected by the wizard. When omitted and
216
223
  // `withGithub` is true, the existing secrets.json#channels.github block is
217
224
  // reused as-is (the wizard's "reuse existing credentials" path).
@@ -250,9 +257,11 @@ export async function runInit({
250
257
  withSlack,
251
258
  withTelegram,
252
259
  withWebex,
260
+ withWebexUser = false,
253
261
  withKakaotalk = false,
254
262
  withGithub = false,
255
263
  runKakaotalkAuth,
264
+ runWebexAuth,
256
265
  githubCredentials,
257
266
  githubFetchImpl,
258
267
  onProgress,
@@ -329,6 +338,7 @@ export async function runInit({
329
338
  withSlack: wantsSlack,
330
339
  withTelegram: wantsTelegram,
331
340
  withWebex: wantsWebex,
341
+ withWebexUser,
332
342
  withKakaotalk,
333
343
  })
334
344
  // Only write the LLM API key on the api-key path. OAuth providers persist
@@ -363,6 +373,15 @@ export async function runInit({
363
373
  }
364
374
  }
365
375
 
376
+ if (withWebexUser && runWebexAuth !== undefined) {
377
+ emit({ step: 'webex-auth', phase: 'start' })
378
+ const result = await runWebexAuth({ cwd })
379
+ emit({ step: 'webex-auth', phase: 'done', result })
380
+ if (!result.ok) {
381
+ throw new Error(`Webex authentication failed: ${result.reason}`)
382
+ }
383
+ }
384
+
366
385
  // Write the structured github channel block alongside scaffold's bot-token
367
386
  // blocks. We do NOT delegate to runAddChannel because that's the `channel
368
387
  // add` semantics — strict no-overwrite, throws when secrets.json#channels
@@ -406,6 +425,7 @@ export async function runInit({
406
425
  if (wantsSlack) configuredChannels.push('slack-bot')
407
426
  if (wantsTelegram) configuredChannels.push('telegram-bot')
408
427
  if (wantsWebex) configuredChannels.push('webex-bot')
428
+ if (withWebexUser) configuredChannels.push('webex')
409
429
  if (withKakaotalk) configuredChannels.push('kakaotalk')
410
430
  if (withGithub) configuredChannels.push('github')
411
431
 
@@ -560,6 +580,7 @@ export type ScaffoldOptions = {
560
580
  withSlack?: boolean
561
581
  withTelegram?: boolean
562
582
  withWebex?: boolean
583
+ withWebexUser?: boolean
563
584
  withKakaotalk?: boolean
564
585
  }
565
586
 
@@ -593,6 +614,7 @@ export async function scaffold(root: string, options: ScaffoldOptions = {}): Pro
593
614
  if (options.withSlack) channels['slack-bot'] = {}
594
615
  if (options.withTelegram) channels['telegram-bot'] = {}
595
616
  if (options.withWebex) channels['webex-bot'] = {}
617
+ if (options.withWebexUser) channels.webex = {}
596
618
  if (options.withKakaotalk) channels.kakaotalk = {}
597
619
  if (Object.keys(channels).length > 0) config.channels = channels
598
620
  // No default `member` match is seeded. A fresh chat agent starts with every
@@ -936,7 +958,7 @@ export async function hasExistingChannelSecrets(
936
958
  case 'telegram':
937
959
  return hasSecretField(channels['telegram-bot'], 'token')
938
960
  case 'webex':
939
- return hasSecretField(channels['webex-bot'], 'token')
961
+ return hasCurrentWebexAccount(channels.webex)
940
962
  case 'github':
941
963
  // GitHub credentials alone are not enough to scaffold a working
942
964
  // channel: typeclaw.json#channels.github also needs webhookUrl and
@@ -995,6 +1017,20 @@ function hasSecretField(slot: unknown, field: string): boolean {
995
1017
  return false
996
1018
  }
997
1019
 
1020
+ function hasCurrentWebexAccount(block: unknown): boolean {
1021
+ if (!isObjectRecord(block)) return false
1022
+ const current = (block as { currentAccount?: unknown }).currentAccount
1023
+ if (typeof current !== 'string' || current.length === 0) return false
1024
+ const accounts = (block as { accounts?: unknown }).accounts
1025
+ if (!isObjectRecord(accounts)) return false
1026
+ const account = accounts[current]
1027
+ if (!isObjectRecord(account)) return false
1028
+ const token = (account as { access_token?: unknown }).access_token
1029
+ const email = (account as { email?: unknown }).email
1030
+ const encryptedPassword = (account as { encryptedPassword?: unknown }).encryptedPassword
1031
+ return typeof token === 'string' && token.length > 0 && typeof email === 'string' && isObjectRecord(encryptedPassword)
1032
+ }
1033
+
998
1034
  function isObjectRecord(value: unknown): value is Record<string, unknown> {
999
1035
  return typeof value === 'object' && value !== null && !Array.isArray(value)
1000
1036
  }
@@ -1031,7 +1067,15 @@ function ignoreExists(error: NodeJS.ErrnoException): void {
1031
1067
  // scaffold-test cases above demonstrates how easy it is to lose a single
1032
1068
  // behavior under a mode flag.
1033
1069
 
1034
- export type ChannelKind = 'discord-bot' | 'slack-bot' | 'telegram-bot' | 'webex-bot' | 'line' | 'kakaotalk' | 'github'
1070
+ export type ChannelKind =
1071
+ | 'discord-bot'
1072
+ | 'slack-bot'
1073
+ | 'telegram-bot'
1074
+ | 'webex'
1075
+ | 'webex-bot'
1076
+ | 'line'
1077
+ | 'kakaotalk'
1078
+ | 'github'
1035
1079
 
1036
1080
  // Public adapter names match the typeclaw.json `channels.*` keys exactly.
1037
1081
  // The CLI takes these as the optional positional arg, the picker shows
@@ -1041,13 +1085,14 @@ export const CHANNEL_KINDS: ReadonlyArray<ChannelKind> = [
1041
1085
  'slack-bot',
1042
1086
  'discord-bot',
1043
1087
  'telegram-bot',
1088
+ 'webex',
1044
1089
  'webex-bot',
1045
1090
  'line',
1046
1091
  'kakaotalk',
1047
1092
  'github',
1048
1093
  ]
1049
1094
 
1050
- export type AddChannelStep = 'line-auth' | 'kakaotalk-auth' | 'config' | 'secrets' | 'github-webhooks'
1095
+ export type AddChannelStep = 'line-auth' | 'kakaotalk-auth' | 'webex-auth' | 'config' | 'secrets' | 'github-webhooks'
1051
1096
 
1052
1097
  export type AddChannelStepEvent =
1053
1098
  | { step: 'config'; phase: 'start' }
@@ -1056,6 +1101,8 @@ export type AddChannelStepEvent =
1056
1101
  | { step: 'line-auth'; phase: 'done'; result: LineAuthResult }
1057
1102
  | { step: 'kakaotalk-auth'; phase: 'start' }
1058
1103
  | { step: 'kakaotalk-auth'; phase: 'done'; result: KakaotalkAuthResult }
1104
+ | { step: 'webex-auth'; phase: 'start' }
1105
+ | { step: 'webex-auth'; phase: 'done'; result: WebexAuthResult }
1059
1106
  | { step: 'secrets'; phase: 'start' }
1060
1107
  | { step: 'secrets'; phase: 'done' }
1061
1108
  | { step: 'github-webhooks'; phase: 'start' }
@@ -1072,6 +1119,7 @@ export type AddChannelOptions = {
1072
1119
  | { channel: 'slack-bot'; slackBotToken: string; slackAppToken: string }
1073
1120
  | { channel: 'telegram-bot'; telegramBotToken: string }
1074
1121
  | { channel: 'webex-bot'; webexBotToken: string }
1122
+ | { channel: 'webex'; runWebexAuth: WebexAuthRunner }
1075
1123
  | { channel: 'line'; runLineAuth: LineAuthRunner }
1076
1124
  | { channel: 'kakaotalk'; runKakaotalkAuth: KakaotalkAuthRunner }
1077
1125
  | {
@@ -1113,6 +1161,13 @@ export async function runAddChannel(options: AddChannelOptions): Promise<void> {
1113
1161
  if (!result.ok) throw new Error(`KakaoTalk authentication failed: ${result.reason}`)
1114
1162
  }
1115
1163
 
1164
+ if (options.channel === 'webex') {
1165
+ emit({ step: 'webex-auth', phase: 'start' })
1166
+ const result = await options.runWebexAuth({ cwd: options.cwd })
1167
+ emit({ step: 'webex-auth', phase: 'done', result })
1168
+ if (!result.ok) throw new Error(`Webex authentication failed: ${result.reason}`)
1169
+ }
1170
+
1116
1171
  emit({ step: 'config', phase: 'start' })
1117
1172
  await mergeChannelIntoConfig(options.cwd, options)
1118
1173
  emit({ step: 'config', phase: 'done' })
@@ -1187,6 +1242,8 @@ function channelSecretsFromOptions(options: AddChannelOptions): ChannelSecrets {
1187
1242
  return { token: options.telegramBotToken }
1188
1243
  case 'webex-bot':
1189
1244
  return { token: options.webexBotToken }
1245
+ case 'webex':
1246
+ return {}
1190
1247
  case 'line':
1191
1248
  // LINE auth writes its structured account block directly to
1192
1249
  // secrets.json#channels.line before config mutation.
@@ -10,6 +10,7 @@ const CHANNEL_LABELS: Record<ChannelKind, string> = {
10
10
  'discord-bot': 'Discord',
11
11
  github: 'GitHub',
12
12
  'telegram-bot': 'Telegram',
13
+ webex: 'Webex (User)',
13
14
  'webex-bot': 'Webex',
14
15
  line: 'LINE',
15
16
  kakaotalk: 'KakaoTalk',
@@ -0,0 +1,68 @@
1
+ import { join, resolve } from 'node:path'
2
+
3
+ import { loginWithPassword as upstreamLoginWithPassword, type PasswordLoginResult } from 'agent-messenger/webex'
4
+
5
+ import { containerNameFromCwd } from '@/container'
6
+ import { keysDir } from '@/hostd/paths'
7
+ import { encrypt } from '@/secrets/encryption'
8
+ import { createKeyStore, type KeyStore } from '@/secrets/keys'
9
+ import type { WebexAccountRecord } from '@/secrets/schema'
10
+ import { SecretsWebexCredentialStore } from '@/secrets/webex-store'
11
+
12
+ export type WebexBootstrapStatus = { ok: true } | { ok: false; reason: string }
13
+
14
+ export type LoginWithPasswordFn = typeof upstreamLoginWithPassword
15
+
16
+ export type WebexLoginInput = {
17
+ email: string
18
+ password: string
19
+ agentDir: string
20
+ idbrokerHost?: string
21
+ loginWithPassword?: LoginWithPasswordFn
22
+ keyStore?: KeyStore
23
+ containerName?: string
24
+ }
25
+
26
+ export function webexSecretsPath(agentDir: string): string {
27
+ return join(agentDir, 'secrets.json')
28
+ }
29
+
30
+ export async function runWebexBootstrap(input: WebexLoginInput): Promise<WebexBootstrapStatus> {
31
+ try {
32
+ const loginWithPassword = input.loginWithPassword ?? upstreamLoginWithPassword
33
+ const store = new SecretsWebexCredentialStore({ mode: 'host', secretsPath: webexSecretsPath(input.agentDir) })
34
+ const loginOptions = input.idbrokerHost !== undefined ? { idbrokerHost: input.idbrokerHost } : undefined
35
+ const result = await loginWithPassword(input.email, input.password, loginOptions)
36
+
37
+ const now = new Date().toISOString()
38
+ const accountId = result.userId || input.email
39
+ const containerName = input.containerName ?? containerNameFromCwd(resolve(input.agentDir))
40
+ const keyStore = input.keyStore ?? createKeyStore({ keysDir: keysDir() })
41
+ const key = await keyStore.ensure(containerName)
42
+ const encryptedPassword = encrypt(input.password, key, {
43
+ containerName,
44
+ accountId,
45
+ purpose: 'webex-password',
46
+ })
47
+ const account: WebexAccountRecord = {
48
+ account_id: accountId,
49
+ access_token: result.accessToken,
50
+ refresh_token: result.refreshToken,
51
+ expires_at: result.expiresAt,
52
+ device_url: result.deviceUrl,
53
+ user_id: result.userId,
54
+ created_at: now,
55
+ updated_at: now,
56
+ email: input.email,
57
+ encryptedPassword,
58
+ }
59
+ await store.setAccount(account)
60
+ await store.setCurrentAccount(accountId)
61
+
62
+ return { ok: true }
63
+ } catch (err) {
64
+ return { ok: false, reason: err instanceof Error ? err.message : String(err) }
65
+ }
66
+ }
67
+
68
+ export type { PasswordLoginResult }
@@ -1,15 +1,19 @@
1
1
  import type { MinimalSessionOrigin } from '@/agent/session-meta'
2
+ import { toRef } from '@/channels/adapters/webex-id-ref'
2
3
 
3
4
  const ADAPTER_DISPLAY: Record<string, string> = {
4
5
  'slack-bot': 'Slack',
5
6
  'discord-bot': 'Discord',
6
7
  github: 'GitHub',
7
8
  'telegram-bot': 'Telegram',
9
+ webex: 'Webex',
10
+ 'webex-bot': 'Webex',
8
11
  line: 'LINE',
9
12
  kakaotalk: 'KakaoTalk',
10
13
  }
11
14
 
12
15
  const SLACK_CHAT_PREFIX_ADAPTERS = new Set(['slack-bot', 'discord-bot'])
16
+ const WEBEX_ADAPTERS = new Set(['webex', 'webex-bot'])
13
17
 
14
18
  export function originLabel(origin: MinimalSessionOrigin): string {
15
19
  switch (origin.kind) {
@@ -39,12 +43,19 @@ function renderChat(origin: Extract<MinimalSessionOrigin, { kind: 'channel' }>):
39
43
  const prefix = SLACK_CHAT_PREFIX_ADAPTERS.has(origin.adapter) ? '#' : ''
40
44
  return `${prefix}${origin.chatName}`
41
45
  }
42
- return origin.chat
46
+ return readableId(origin.adapter, origin.chat)
43
47
  }
44
48
 
45
49
  function renderWorkspace(origin: Extract<MinimalSessionOrigin, { kind: 'channel' }>): string {
46
50
  if (origin.workspaceName !== undefined && origin.workspaceName !== '') return origin.workspaceName
47
- return origin.workspace
51
+ return readableId(origin.adapter, origin.workspace)
52
+ }
53
+
54
+ // Webex room/workspace/person ids are base64 `ciscospark://` blobs that read as
55
+ // gibberish. With no resolved title, decode to the trailing ref (a UUID) so the
56
+ // row is at least skimmable; non-Webex ids pass through.
57
+ export function readableId(adapter: string, id: string): string {
58
+ return WEBEX_ADAPTERS.has(adapter) ? toRef(id) : id
48
59
  }
49
60
 
50
61
  export function shortSessionId(sessionId: string): string {
@@ -1,6 +1,6 @@
1
1
  import { styleText } from 'node:util'
2
2
 
3
- import { originLabel } from './label'
3
+ import { originLabel, readableId } from './label'
4
4
  import type { InspectEvent } from './types'
5
5
 
6
6
  export type RenderOptions = {
@@ -120,8 +120,10 @@ function renderBody(event: InspectEvent, opts: RenderOptions): string {
120
120
  }
121
121
 
122
122
  function renderInboundBody(event: Extract<InspectEvent, { cat: 'inbound' }>, opts: RenderOptions): string {
123
- const coord = `${event.adapter}:${event.workspace}/${event.chat}${event.thread === null ? '' : `#${event.thread}`}`
124
- const who = event.authorName !== '' ? event.authorName : event.authorId
123
+ const workspace = readableId(event.adapter, event.workspace)
124
+ const chat = readableId(event.adapter, event.chat)
125
+ const coord = `${event.adapter}:${workspace}/${chat}${event.thread === null ? '' : `#${event.thread}`}`
126
+ const who = event.authorName !== '' ? event.authorName : readableId(event.adapter, event.authorId)
125
127
  const decisionTag = tint(opts, decisionColor(event.decision), `[${event.decision}]`)
126
128
  const text = truncate(singleLine(event.text), opts.maxTextLength ?? DEFAULT_MAX_TEXT)
127
129
  return `${decisionTag} ${tint(opts, 'dim', coord)} ${who}: ${text}`
@@ -1,3 +1,4 @@
1
+ import { decodeWebexId } from '@/channels/adapters/webex-id-ref'
1
2
  import type { AdapterId } from '@/channels/schema'
2
3
 
3
4
  import type { MatchRule, Platform } from './match-rule'
@@ -7,6 +8,7 @@ const ADAPTER_TO_PLATFORM: Record<AdapterId, Platform> = {
7
8
  'discord-bot': 'discord',
8
9
  github: 'github',
9
10
  'telegram-bot': 'telegram',
11
+ webex: 'webex',
10
12
  'webex-bot': 'webex',
11
13
  line: 'line',
12
14
  kakaotalk: 'kakao',
@@ -53,10 +55,45 @@ function matchesChannel(rule: Extract<MatchRule, { kind: 'channel' }>, origin: M
53
55
  if (rule.chat !== undefined && rule.chat !== origin.chat) return false
54
56
  }
55
57
 
56
- if (rule.author !== undefined && rule.author !== origin.lastInboundAuthorId) return false
58
+ if (rule.author !== undefined && !matchesAuthor(rule.platform, rule.author, origin.lastInboundAuthorId)) return false
57
59
  return true
58
60
  }
59
61
 
62
+ // Webex person ids are base64(`ciscospark://<cluster>/PEOPLE/<uuid-or-email>`),
63
+ // so a hand-authored or claim-generated rule may carry the raw base64 id, its
64
+ // decoded ref (UUID for modern accounts, email for legacy Hydra accounts), and
65
+ // the inbound may arrive as either. We compare on the decoded PERSON ref when
66
+ // BOTH sides decode to a PEOPLE id, and otherwise fall back to raw equality —
67
+ // so `author:<uuid>`, `author:<legacy-email>`, and the legacy `author:<base64>`
68
+ // all match the same human. A value that decodes to a non-PERSON type (e.g. a
69
+ // room id pasted into `author:`) never normalizes, so it can only ever raw-
70
+ // match — a room uuid can never satisfy an author rule.
71
+ function matchesAuthor(platform: Platform, ruleAuthor: string, inboundAuthorId: string | undefined): boolean {
72
+ if (inboundAuthorId === undefined) return false
73
+ if (ruleAuthor === inboundAuthorId) return true
74
+ if (platform !== 'webex') return false
75
+ // Both sides must resolve to a real PERSON ref. `webexPersonRef` returns null
76
+ // for any non-PEOPLE id, and null === null would otherwise let two different
77
+ // room/message ids satisfy an `author:` rule — so require both non-null.
78
+ const ruleRef = webexPersonRef(ruleAuthor)
79
+ const inboundRef = webexPersonRef(inboundAuthorId)
80
+ return ruleRef !== null && inboundRef !== null && ruleRef === inboundRef
81
+ }
82
+
83
+ // Returns the comparable person identity for a Webex `author:` value: the
84
+ // decoded trailing ref when the value is a base64 PEOPLE id, or the value
85
+ // itself when it is already a ref (bare uuid/email). Returns null for anything
86
+ // that decodes to a non-PERSON Webex id, so two different resource types can
87
+ // never be coerced into matching. Emails are lower-cased so case variation in
88
+ // a legacy-account ref does not silently deny a grant. Keep this for backward
89
+ // compatibility with pre-migration rules that still carry blob-form ids.
90
+ function webexPersonRef(value: string): string | null {
91
+ const decoded = decodeWebexId(value)
92
+ if (decoded === null) return value.includes('@') ? value.toLowerCase() : value
93
+ if (decoded.type !== 'PEOPLE') return null
94
+ return decoded.uuid.includes('@') ? decoded.uuid.toLowerCase() : decoded.uuid
95
+ }
96
+
60
97
  // DM and group buckets are inferred from the workspace/chat shape of the
61
98
  // inbound origin. Different adapters mark DMs differently — Slack and Webex
62
99
  // use an `@dm` workspace marker, Discord uses a `dm` workspace marker, and
@@ -33,6 +33,7 @@ const ADAPTER_TO_PLATFORM: Record<
33
33
  'discord-bot': 'discord',
34
34
  github: 'github',
35
35
  'telegram-bot': 'telegram',
36
+ webex: 'webex',
36
37
  'webex-bot': 'webex',
37
38
  line: 'line',
38
39
  kakaotalk: 'kakao',
@@ -40,5 +41,8 @@ const ADAPTER_TO_PLATFORM: Record<
40
41
 
41
42
  export function formatClaimMatchRule(origin: PartialChannelOrigin): string {
42
43
  const platform = ADAPTER_TO_PLATFORM[origin.adapter]
43
- return `${platform}:* author:${origin.authorId}`
44
+ // Webex authorIds are stored as decoded refs (UUID, or email for legacy
45
+ // accounts). The matcher still normalizes older blob-form rules/inbounds.
46
+ const author = origin.authorId
47
+ return `${platform}:* author:${author}`
44
48
  }
@@ -1,15 +1,21 @@
1
1
  import type { ProviderCredential } from './schema'
2
2
 
3
- // Emit the on-disk shape Codex CLI consumes at ~/.codex/auth.json. Mirrors
4
- // the modern (>= 0.93) shape: a single `tokens` object with access_token,
5
- // refresh_token, and optional account_id. Codex re-derives token expiry
6
- // from the JWT's `exp` claim on every load, so we deliberately omit a
7
- // top-level `expires` field even though typeclaw stores one.
3
+ // Emit the on-disk shape Codex CLI consumes at ~/.codex/auth.json: a `tokens`
4
+ // object with id_token, access_token, refresh_token, and optional account_id.
5
+ // No top-level `expires` — codex re-derives expiry from the JWT `exp` claim.
8
6
  //
9
- // Pre-0.93 codex used a different layout (top-level OPENAI_API_KEY +
10
- // auth_mode discriminator + optional tokens). We don't emit that legacy
11
- // shape — every codex install old enough to require it has been replaced
12
- // by the version `docker.file.codexCli` installs in the container.
7
+ // id_token is load-bearing: codex's deserializer (token_data.rs) declares
8
+ // `id_token: IdTokenInfo` with no Option/#[serde(default)], so omitting it
9
+ // fails the whole auth.json load with `missing field id_token` before any
10
+ // model call. codex parses it via `parse_chatgpt_jwt_claims`, which accepts
11
+ // any decodable 3-part JWT and treats every claim as optional.
12
+ //
13
+ // We prefer a real captured id_token (`idToken`/`id_token` on the credential,
14
+ // e.g. from a future pi-ai that persists it) and fall back to `access`. The
15
+ // fallback is sound because this flow's access token is itself a ChatGPT-claims
16
+ // JWT (carries `https://api.openai.com/auth`), so codex reads the same
17
+ // plan/account fields from it — self-healing agents whose stored credential
18
+ // predates id_token capture, without a re-login.
13
19
  export function emitCodexAuthJson(credential: ProviderCredential): string {
14
20
  if (credential.type !== 'oauth') {
15
21
  throw new Error('emitCodexAuthJson only accepts oauth-typed credentials')
@@ -18,6 +24,8 @@ export function emitCodexAuthJson(credential: ProviderCredential): string {
18
24
  access?: unknown
19
25
  refresh?: unknown
20
26
  accountId?: unknown
27
+ idToken?: unknown
28
+ id_token?: unknown
21
29
  }
22
30
  const access = fields.access
23
31
  const refresh = fields.refresh
@@ -28,38 +36,65 @@ export function emitCodexAuthJson(credential: ProviderCredential): string {
28
36
  throw new Error('credential is missing a non-empty `refresh` field')
29
37
  }
30
38
 
31
- const tokens: Record<string, string> = { access_token: access, refresh_token: refresh }
39
+ const capturedIdToken = firstNonEmptyString(fields.idToken, fields.id_token)
40
+ const idToken = capturedIdToken ?? access
41
+
42
+ const tokens: Record<string, string> = {
43
+ id_token: idToken,
44
+ access_token: access,
45
+ refresh_token: refresh,
46
+ }
32
47
  if (typeof fields.accountId === 'string' && fields.accountId.length > 0) {
33
48
  tokens['account_id'] = fields.accountId
34
49
  }
35
50
  return `${JSON.stringify({ tokens }, null, 2)}\n`
36
51
  }
37
52
 
53
+ function firstNonEmptyString(...values: unknown[]): string | null {
54
+ for (const value of values) {
55
+ if (typeof value === 'string' && value.length > 0) return value
56
+ }
57
+ return null
58
+ }
59
+
38
60
  // Extracts the JWT `exp` claim (seconds since epoch) and converts to ms.
39
61
  // Used by the runtime exporter's newer-wins compare: ~/.codex/auth.json
40
62
  // carries no top-level expiry, but the JWT inside `tokens.access_token`
41
63
  // does. Returns null on any decode failure; the caller treats that as
42
64
  // "unknown freshness" and falls back to overwriting from typeclaw's copy.
43
65
  export function decodeCodexAccessTokenExpiryMs(accessToken: string): number | null {
44
- const parts = accessToken.split('.')
66
+ const payload = decodeJwtPayload(accessToken)
67
+ if (payload === null) return null
68
+ const exp = payload['exp']
69
+ if (typeof exp !== 'number' || !Number.isFinite(exp)) return null
70
+ return Math.floor(exp * 1000)
71
+ }
72
+
73
+ // True when the string decodes the way codex's `decode_jwt_payload` requires:
74
+ // three non-empty dot-separated parts with a base64url payload that is a JSON
75
+ // object. codex runs exactly this on `tokens.id_token` (via
76
+ // `parse_chatgpt_jwt_claims`) and rejects the whole auth.json if it fails, so
77
+ // the exporter uses this to decide whether an on-disk id_token is usable —
78
+ // not just non-empty.
79
+ export function isDecodableJwt(token: string): boolean {
80
+ return decodeJwtPayload(token) !== null
81
+ }
82
+
83
+ function decodeJwtPayload(jwt: string): Record<string, unknown> | null {
84
+ const parts = jwt.split('.')
45
85
  if (parts.length !== 3) return null
46
86
  const middle = parts[1] ?? ''
47
87
  if (middle === '') return null
48
88
  // base64url → base64, then pad to a multiple of 4 (atob is strict).
49
89
  const normalized = middle.replace(/-/g, '+').replace(/_/g, '/')
50
90
  const padded = normalized + '='.repeat((4 - (normalized.length % 4)) % 4)
51
- let payload: Record<string, unknown>
52
91
  try {
53
92
  const decoded = typeof atob === 'function' ? atob(padded) : Buffer.from(padded, 'base64').toString('utf8')
54
93
  const parsed: unknown = JSON.parse(decoded)
55
- if (!isPlainObject(parsed)) return null
56
- payload = parsed
94
+ return isPlainObject(parsed) ? parsed : null
57
95
  } catch {
58
96
  return null
59
97
  }
60
- const exp = payload['exp']
61
- if (typeof exp !== 'number' || !Number.isFinite(exp)) return null
62
- return Math.floor(exp * 1000)
63
98
  }
64
99
 
65
100
  function isPlainObject(value: unknown): value is Record<string, unknown> {
@@ -33,6 +33,7 @@ export type EncryptedEnvelope = {
33
33
  export type EncryptionContext = {
34
34
  containerName: string
35
35
  accountId: string
36
+ purpose?: string
36
37
  }
37
38
 
38
39
  export class EncryptionError extends Error {
@@ -112,5 +113,8 @@ export function decrypt(envelope: EncryptedEnvelope, key: Buffer, context: Encry
112
113
  // Changing this format breaks decryption of every previously-stored ciphertext.
113
114
  // See the module-header threat-model comment for the binding rationale.
114
115
  function buildAad(context: EncryptionContext): Buffer {
115
- return Buffer.from(`typeclaw:kakaotalk-password:v1:${context.containerName}:${context.accountId}`, 'utf8')
116
+ return Buffer.from(
117
+ `typeclaw:${context.purpose ?? 'kakaotalk-password'}:v1:${context.containerName}:${context.accountId}`,
118
+ 'utf8',
119
+ )
116
120
  }
@@ -11,7 +11,7 @@ import {
11
11
  import { homedir } from 'node:os'
12
12
  import { dirname, isAbsolute, join, resolve } from 'node:path'
13
13
 
14
- import { decodeCodexAccessTokenExpiryMs, emitCodexAuthJson } from './codex-auth-json'
14
+ import { decodeCodexAccessTokenExpiryMs, emitCodexAuthJson, isDecodableJwt } from './codex-auth-json'
15
15
  import type { ProviderCredential, Providers } from './schema'
16
16
  import { SecretsBackend } from './storage'
17
17
 
@@ -86,6 +86,13 @@ export function exportCodexAuthFileIfApplicable(options: ExportCodexAuthFileOpti
86
86
  // missing JWT, undecodable exp), we return true. That's the "we have a
87
87
  // valid credential, the file is unusable, replace it" fallback case (B1
88
88
  // and B6 in the design doc).
89
+ //
90
+ // A file missing a usable `id_token` is unusable too, regardless of how
91
+ // fresh its access token is: codex rejects the whole auth.json with
92
+ // `missing field id_token` before any model call. This guard runs BEFORE
93
+ // the newer-wins expiry compare so a pre-fix TypeClaw-emitted file (valid,
94
+ // possibly fresher access token, but no id_token) is always rewritten —
95
+ // the path that self-heals already-broken agents on restart.
89
96
  function shouldOverwrite(
90
97
  targetPath: string,
91
98
  credential: ProviderCredential & { expires?: unknown; access?: unknown },
@@ -105,6 +112,8 @@ function shouldOverwrite(
105
112
  return true
106
113
  }
107
114
 
115
+ if (!onDiskHasUsableIdToken(parsed)) return true
116
+
108
117
  const onDiskAccess = readOnDiskAccessToken(parsed)
109
118
  if (onDiskAccess === null) return true
110
119
 
@@ -116,11 +125,25 @@ function shouldOverwrite(
116
125
  }
117
126
 
118
127
  function readOnDiskAccessToken(parsed: unknown): string | null {
128
+ return readOnDiskToken(parsed, 'access_token')
129
+ }
130
+
131
+ // codex parses `tokens.id_token` as a JWT, so a value that is absent, empty,
132
+ // or not a decodable JWT is unusable — codex rejects the whole auth.json on
133
+ // load. Validate decodability (not just presence) so a file with a non-empty
134
+ // but malformed id_token, even alongside a fresh access token, is treated as
135
+ // stale and rewritten rather than preserved by the newer-wins compare.
136
+ function onDiskHasUsableIdToken(parsed: unknown): boolean {
137
+ const idToken = readOnDiskToken(parsed, 'id_token')
138
+ return idToken !== null && isDecodableJwt(idToken)
139
+ }
140
+
141
+ function readOnDiskToken(parsed: unknown, field: 'access_token' | 'id_token'): string | null {
119
142
  if (typeof parsed !== 'object' || parsed === null) return null
120
143
  const tokens = (parsed as Record<string, unknown>)['tokens']
121
144
  if (typeof tokens !== 'object' || tokens === null) return null
122
- const access = (tokens as Record<string, unknown>)['access_token']
123
- return typeof access === 'string' && access.length > 0 ? access : null
145
+ const value = (tokens as Record<string, unknown>)[field]
146
+ return typeof value === 'string' && value.length > 0 ? value : null
124
147
  }
125
148
 
126
149
  // Resolution order for the credential's expiry: