typeclaw 0.37.7 → 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 (44) hide show
  1. package/README.md +2 -2
  2. package/auth.schema.json +109 -0
  3. package/package.json +2 -2
  4. package/secrets.schema.json +109 -0
  5. package/src/agent/session-origin.ts +16 -2
  6. package/src/bundled-plugins/memory/README.md +12 -1
  7. package/src/bundled-plugins/memory/index.ts +39 -2
  8. package/src/channels/adapters/kakaotalk.ts +1 -1
  9. package/src/channels/adapters/webex-bot-channel-resolver.ts +29 -0
  10. package/src/channels/adapters/webex-bot-classify.ts +98 -0
  11. package/src/channels/adapters/webex-bot-reference.ts +49 -0
  12. package/src/channels/adapters/webex-bot.ts +462 -0
  13. package/src/channels/adapters/webex-channel-resolver.ts +29 -0
  14. package/src/channels/adapters/webex-classify.ts +104 -0
  15. package/src/channels/adapters/webex-format.ts +53 -0
  16. package/src/channels/adapters/webex-id-ref.ts +32 -0
  17. package/src/channels/adapters/webex-reference.ts +49 -0
  18. package/src/channels/adapters/webex.ts +493 -0
  19. package/src/channels/manager.ts +75 -4
  20. package/src/channels/persistence.ts +67 -5
  21. package/src/channels/router.ts +9 -0
  22. package/src/channels/schema.ts +17 -1
  23. package/src/cli/channel.ts +155 -8
  24. package/src/cli/init.ts +129 -6
  25. package/src/config/channels-mutation.ts +11 -2
  26. package/src/doctor/channel-checks.ts +56 -1
  27. package/src/hostd/daemon.ts +7 -5
  28. package/src/hostd/protocol.ts +2 -2
  29. package/src/init/checkpoint.ts +1 -1
  30. package/src/init/index.ts +97 -17
  31. package/src/init/run-owner-claim.ts +2 -0
  32. package/src/init/webex-auth.ts +68 -0
  33. package/src/inspect/label.ts +13 -2
  34. package/src/inspect/render.ts +5 -3
  35. package/src/permissions/match-rule.ts +7 -3
  36. package/src/permissions/resolve.ts +44 -5
  37. package/src/role-claim/match-rule.ts +7 -2
  38. package/src/secrets/codex-auth-json.ts +52 -17
  39. package/src/secrets/defaults.ts +1 -0
  40. package/src/secrets/encryption.ts +5 -1
  41. package/src/secrets/export-codex-auth-file.ts +26 -3
  42. package/src/secrets/schema.ts +35 -0
  43. package/src/secrets/webex-store.ts +113 -0
  44. package/typeclaw.schema.json +321 -1
@@ -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> {
@@ -19,6 +19,7 @@ export const CHANNEL_FIELD_ENV = {
19
19
  'discord-bot': { token: 'DISCORD_BOT_TOKEN' },
20
20
  'slack-bot': { botToken: 'SLACK_BOT_TOKEN', appToken: 'SLACK_APP_TOKEN' },
21
21
  'telegram-bot': { token: 'TELEGRAM_BOT_TOKEN' },
22
+ 'webex-bot': { token: 'WEBEX_BOT_TOKEN' },
22
23
  } as const satisfies Record<string, Record<string, string>>
23
24
 
24
25
  export type KnownAdapterId = keyof typeof CHANNEL_FIELD_ENV
@@ -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:
@@ -93,6 +93,18 @@ const kakaoEncryptedPasswordSchema = z
93
93
  })
94
94
  .strict()
95
95
 
96
+ export const webexEncryptedPasswordSchema = z
97
+ .object({
98
+ v: z.literal(1),
99
+ alg: z.literal('AES-256-GCM'),
100
+ kid: z.string(),
101
+ iv: z.string(),
102
+ ciphertext: z.string(),
103
+ authTag: z.string(),
104
+ createdAt: z.string(),
105
+ })
106
+ .strict()
107
+
96
108
  export const kakaoAccountRecordSchema = z.object({
97
109
  account_id: z.string(),
98
110
  oauth_token: z.string(),
@@ -112,6 +124,26 @@ export const kakaoAccountRecordSchema = z.object({
112
124
 
113
125
  export type KakaoEncryptedPassword = z.infer<typeof kakaoEncryptedPasswordSchema>
114
126
 
127
+ export const webexAccountRecordSchema = z.object({
128
+ account_id: z.string(),
129
+ access_token: z.string(),
130
+ refresh_token: z.string(),
131
+ expires_at: z.number(),
132
+ device_url: z.string().optional(),
133
+ user_id: z.string().optional(),
134
+ client_id: z.string().optional(),
135
+ client_secret: z.string().optional(),
136
+ created_at: z.string(),
137
+ updated_at: z.string(),
138
+ email: z.string().optional(),
139
+ encryptedPassword: webexEncryptedPasswordSchema.optional(),
140
+ })
141
+
142
+ export const webexChannelBlockSchema = z.object({
143
+ currentAccount: z.string().nullable(),
144
+ accounts: z.record(z.string(), webexAccountRecordSchema),
145
+ })
146
+
115
147
  export const kakaoPendingLoginRecordSchema = z.object({
116
148
  device_uuid: z.string(),
117
149
  device_type: z.union([z.literal('pc'), z.literal('tablet')]),
@@ -133,6 +165,7 @@ export const channelsSchema = z
133
165
  'telegram-bot': telegramBotChannelSchema.optional(),
134
166
  line: lineChannelBlockSchema.optional(),
135
167
  kakaotalk: kakaoChannelBlockSchema.optional(),
168
+ webex: webexChannelBlockSchema.optional(),
136
169
  })
137
170
  .catchall(z.unknown())
138
171
 
@@ -158,6 +191,8 @@ export type LineChannelBlock = z.infer<typeof lineChannelBlockSchema>
158
191
  export type KakaoAccountRecord = z.infer<typeof kakaoAccountRecordSchema>
159
192
  export type PendingLoginRecord = z.infer<typeof kakaoPendingLoginRecordSchema>
160
193
  export type KakaoChannelBlock = z.infer<typeof kakaoChannelBlockSchema>
194
+ export type WebexAccountRecord = z.infer<typeof webexAccountRecordSchema>
195
+ export type WebexChannelBlock = z.infer<typeof webexChannelBlockSchema>
161
196
  export type SecretsFile = z.infer<typeof secretsFileSchema>
162
197
 
163
198
  export type ParseSecretsResult = { ok: true; file: SecretsFile } | { ok: false; reason: string }
@@ -0,0 +1,113 @@
1
+ import { sendHttp } from '@/hostd/client'
2
+
3
+ import { type WebexAccountRecord, type WebexChannelBlock, webexChannelBlockSchema } from './schema'
4
+ import { SecretsBackend } from './storage'
5
+
6
+ export type SetWebexAccountInput = WebexAccountRecord
7
+
8
+ export type SecretsWebexCredentialStoreOptions =
9
+ | { mode: 'host'; secretsPath: string }
10
+ | { mode: 'container'; secretsPath: string; hostdUrl: string; restartToken: string; containerName: string }
11
+
12
+ const EMPTY_BLOCK: WebexChannelBlock = { currentAccount: null, accounts: {} }
13
+
14
+ export class SecretsWebexCredentialStore {
15
+ private readonly backend: SecretsBackend
16
+ private writeChain: Promise<void> = Promise.resolve()
17
+
18
+ constructor(private readonly options: SecretsWebexCredentialStoreOptions) {
19
+ this.backend = new SecretsBackend(options.secretsPath)
20
+ }
21
+
22
+ async getAccount(id?: string): Promise<WebexAccountRecord | null> {
23
+ const block = this.readBlock()
24
+ const accountId = id ?? block.currentAccount
25
+ if (!accountId) return null
26
+ return block.accounts[accountId] ?? null
27
+ }
28
+
29
+ async getAccountWithRenewalFields(id?: string): Promise<WebexAccountRecord | null> {
30
+ return await this.getAccount(id)
31
+ }
32
+
33
+ async setAccount(account: SetWebexAccountInput): Promise<void> {
34
+ await this.writeBlock((block) => {
35
+ const merged = mergeAccountPreservingRenewalFields(account, block.accounts[account.account_id])
36
+ const accounts = { ...block.accounts, [account.account_id]: merged }
37
+ return { ...block, currentAccount: block.currentAccount ?? account.account_id, accounts }
38
+ })
39
+ }
40
+
41
+ async removeAccount(id: string): Promise<void> {
42
+ await this.writeBlock((block) => {
43
+ const accounts = { ...block.accounts }
44
+ delete accounts[id]
45
+ const currentAccount = block.currentAccount === id ? (Object.keys(accounts)[0] ?? null) : block.currentAccount
46
+ return { ...block, currentAccount, accounts }
47
+ })
48
+ }
49
+
50
+ async listAccounts(): Promise<Array<WebexAccountRecord & { is_current: boolean }>> {
51
+ const block = this.readBlock()
52
+ return Object.values(block.accounts).map((account) => ({
53
+ ...account,
54
+ is_current: account.account_id === block.currentAccount,
55
+ }))
56
+ }
57
+
58
+ async setCurrentAccount(id: string): Promise<void> {
59
+ await this.writeBlock((block) => ({ ...block, currentAccount: id }))
60
+ }
61
+
62
+ private readBlock(): WebexChannelBlock {
63
+ const channels =
64
+ this.options.mode === 'container' ? this.backend.tryReadChannelsSync() : this.backend.readChannelsSync()
65
+ return parseBlock(channels?.webex)
66
+ }
67
+
68
+ private async writeBlock(update: (current: WebexChannelBlock) => WebexChannelBlock): Promise<void> {
69
+ return this.enqueueWrite(async () => {
70
+ if (this.options.mode === 'container') {
71
+ const next = update(this.readBlock())
72
+ const response = await sendHttp(
73
+ {
74
+ kind: 'secrets-patch',
75
+ containerName: this.options.containerName,
76
+ patch: { channels: { webex: next } },
77
+ },
78
+ { url: this.options.hostdUrl, token: this.options.restartToken },
79
+ )
80
+ if (!response.ok) throw new Error(`secrets-patch failed: ${response.reason}`)
81
+ return
82
+ }
83
+
84
+ await this.backend.updateChannelsAsync(async (channels) => {
85
+ const next = { ...channels, webex: update(parseBlock(channels.webex)) }
86
+ return { result: undefined, next }
87
+ })
88
+ })
89
+ }
90
+
91
+ private enqueueWrite(op: () => Promise<void>): Promise<void> {
92
+ const next = this.writeChain.then(op, op)
93
+ this.writeChain = next.catch(() => {})
94
+ return next
95
+ }
96
+ }
97
+
98
+ function parseBlock(value: unknown): WebexChannelBlock {
99
+ if (value === undefined) return EMPTY_BLOCK
100
+ return webexChannelBlockSchema.parse(value)
101
+ }
102
+
103
+ function mergeAccountPreservingRenewalFields(
104
+ incoming: SetWebexAccountInput,
105
+ priorOnDisk: WebexChannelBlock['accounts'][string] | undefined,
106
+ ): WebexAccountRecord {
107
+ const merged: WebexAccountRecord = { ...incoming }
108
+ if (incoming.email !== undefined) merged.email = incoming.email
109
+ else if (priorOnDisk?.email !== undefined) merged.email = priorOnDisk.email
110
+ if (incoming.encryptedPassword !== undefined) merged.encryptedPassword = incoming.encryptedPassword
111
+ else if (priorOnDisk?.encryptedPassword !== undefined) merged.encryptedPassword = priorOnDisk.encryptedPassword
112
+ return merged
113
+ }