typeclaw 0.39.0 → 0.39.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 (36) hide show
  1. package/README.md +1 -0
  2. package/package.json +2 -2
  3. package/src/agent/attention-escalation.ts +154 -4
  4. package/src/agent/git-nudge.ts +7 -7
  5. package/src/agent/session-origin.ts +21 -0
  6. package/src/bundled-plugins/backup/index.ts +5 -2
  7. package/src/bundled-plugins/backup/runner.ts +55 -23
  8. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +7 -8
  9. package/src/bundled-plugins/memory/dreaming.ts +37 -24
  10. package/src/channels/adapters/kakaotalk-membership.ts +67 -0
  11. package/src/channels/adapters/kakaotalk.ts +8 -0
  12. package/src/channels/adapters/line-token.ts +55 -0
  13. package/src/channels/adapters/line.ts +74 -0
  14. package/src/channels/adapters/webex-bot-classify.ts +14 -1
  15. package/src/channels/adapters/webex-bot.ts +24 -1
  16. package/src/channels/adapters/webex-classify.ts +16 -1
  17. package/src/channels/adapters/webex.ts +27 -1
  18. package/src/channels/router.ts +55 -2
  19. package/src/cli/hostd.ts +40 -0
  20. package/src/config/config.ts +7 -5
  21. package/src/container/shared.ts +115 -14
  22. package/src/container/shell.ts +12 -2
  23. package/src/doctor/commit.ts +10 -10
  24. package/src/dreams/git.ts +20 -7
  25. package/src/dreams/index.ts +22 -7
  26. package/src/git/reconcile-ignored.ts +56 -27
  27. package/src/git/resolve-agent-git.ts +12 -0
  28. package/src/git/system-commit.ts +16 -10
  29. package/src/hostd/daemon.ts +16 -0
  30. package/src/hostd/webex-renewal-manager.ts +216 -0
  31. package/src/init/dockerfile.ts +13 -4
  32. package/src/init/gitignore.ts +4 -2
  33. package/src/secrets/schema.ts +1 -0
  34. package/src/secrets/webex-renewal.ts +215 -0
  35. package/src/server/index.ts +25 -3
  36. package/typeclaw.schema.json +6 -1
@@ -0,0 +1,215 @@
1
+ import { join } from 'node:path'
2
+
3
+ import { loginWithPassword as upstreamLoginWithPassword } from 'agent-messenger/webex'
4
+
5
+ import { decrypt, EncryptionError } from './encryption'
6
+ import { type KeyStore, KeyStoreError } from './keys'
7
+ import { type WebexChannelBlock } from './schema'
8
+ import { SecretsBackend } from './storage'
9
+ import { SecretsWebexCredentialStore } from './webex-store'
10
+
11
+ // Webex password-login access tokens live ~27h. The daily renewal tick fires
12
+ // every 24h, so a token must be refreshed while it still has more than one
13
+ // tick-interval of life left — otherwise it expires in the gap between two
14
+ // ticks and every REST call (send, history, KMS key fetch) 401s while the
15
+ // Mercury listener stays connected on its already-authenticated socket. We
16
+ // renew when the token is within 8h of `expires_at`: that clears a full 24h
17
+ // tick plus headroom for host sleep / daemon respawn, and a fresh token
18
+ // minted on each tick keeps the window comfortably ahead of expiry.
19
+ export const RENEWAL_WINDOW_MS = 8 * 60 * 60 * 1000
20
+
21
+ export type WebexRenewalDecision =
22
+ | { kind: 'skip'; reason: 'no_account' | 'fresh_enough'; expiresInMs?: number }
23
+ | {
24
+ kind: 'reauth_required'
25
+ reason: 'no_password' | 'no_email' | 'key_missing' | 'decrypt_failed'
26
+ message: string
27
+ }
28
+ | { kind: 'should_renew'; account: WebexAccountSnapshot; password: string }
29
+
30
+ export type WebexAccountSnapshot = {
31
+ account_id: string
32
+ email: string
33
+ created_at: string
34
+ updated_at: string
35
+ }
36
+
37
+ export type WebexRenewalAttempt =
38
+ | { kind: 'ok'; account_id: string; previousExpiresAt: number; nextExpiresAt: number }
39
+ | { kind: 'reauth_required'; account_id: string; reason: string; message: string }
40
+ | { kind: 'transient_failure'; account_id: string; reason: string }
41
+
42
+ export type LoginWithPasswordFn = typeof upstreamLoginWithPassword
43
+
44
+ export type WebexRenewalContext = {
45
+ containerName: string
46
+ agentDir: string
47
+ keyStore: KeyStore
48
+ now?: () => number
49
+ loginWithPassword?: LoginWithPasswordFn
50
+ idbrokerHost?: string
51
+ }
52
+
53
+ export async function decideRenewal(block: WebexChannelBlock, ctx: WebexRenewalContext): Promise<WebexRenewalDecision> {
54
+ const accountId = block.currentAccount
55
+ if (!accountId) return { kind: 'skip', reason: 'no_account' }
56
+ const account = block.accounts[accountId]
57
+ if (!account) return { kind: 'skip', reason: 'no_account' }
58
+
59
+ const now = (ctx.now ?? Date.now)()
60
+ const expiresInMs = account.expires_at - now
61
+ if (Number.isFinite(expiresInMs) && expiresInMs > RENEWAL_WINDOW_MS) {
62
+ return { kind: 'skip', reason: 'fresh_enough', expiresInMs }
63
+ }
64
+
65
+ if (!account.email) {
66
+ return {
67
+ kind: 'reauth_required',
68
+ reason: 'no_email',
69
+ message: `Webex account ${accountId} has no stored email — run \`typeclaw channel reauth webex\`.`,
70
+ }
71
+ }
72
+ if (!account.encryptedPassword) {
73
+ return {
74
+ kind: 'reauth_required',
75
+ reason: 'no_password',
76
+ message: `Webex account ${accountId} has no stored password — run \`typeclaw channel reauth webex\`.`,
77
+ }
78
+ }
79
+
80
+ let plaintextPassword: string
81
+ try {
82
+ const key = await ctx.keyStore.read(ctx.containerName)
83
+ plaintextPassword = decrypt(account.encryptedPassword, key, {
84
+ containerName: ctx.containerName,
85
+ accountId: account.account_id,
86
+ })
87
+ } catch (err) {
88
+ return classifyDecryptFailure(err, accountId)
89
+ }
90
+
91
+ return {
92
+ kind: 'should_renew',
93
+ account: {
94
+ account_id: account.account_id,
95
+ email: account.email,
96
+ created_at: account.created_at,
97
+ updated_at: account.updated_at,
98
+ },
99
+ password: plaintextPassword,
100
+ }
101
+ }
102
+
103
+ export async function renewCurrentAccount(
104
+ ctx: WebexRenewalContext,
105
+ ): Promise<WebexRenewalAttempt | { kind: 'skipped'; reason: string; expiresInMs?: number }> {
106
+ const secretsPath = join(ctx.agentDir, 'secrets.json')
107
+ const backend = new SecretsBackend(secretsPath)
108
+ const block = backend.readChannelsSync()?.webex
109
+ const parsed = parseBlockOrEmpty(block)
110
+ const decision = await decideRenewal(parsed, ctx)
111
+
112
+ if (decision.kind === 'skip') {
113
+ return {
114
+ kind: 'skipped',
115
+ reason: decision.reason,
116
+ ...(decision.expiresInMs !== undefined ? { expiresInMs: decision.expiresInMs } : {}),
117
+ }
118
+ }
119
+ if (decision.kind === 'reauth_required') {
120
+ return {
121
+ kind: 'reauth_required',
122
+ account_id: parsed.currentAccount ?? '',
123
+ reason: decision.reason,
124
+ message: decision.message,
125
+ }
126
+ }
127
+
128
+ const loginWithPassword = ctx.loginWithPassword ?? upstreamLoginWithPassword
129
+ const loginOptions = ctx.idbrokerHost !== undefined ? { idbrokerHost: ctx.idbrokerHost } : undefined
130
+
131
+ let result: Awaited<ReturnType<LoginWithPasswordFn>>
132
+ try {
133
+ result = await loginWithPassword(decision.account.email, decision.password, loginOptions)
134
+ } catch (err) {
135
+ return classifyLoginFailure(err, decision.account.account_id)
136
+ }
137
+
138
+ // The renewed login resolves to the same Webex user, so reuse the stored
139
+ // account_id rather than `result.userId`: the store keys accounts by id and a
140
+ // drifted id would orphan the record (and its encryptedPassword) instead of
141
+ // updating it. `setAccount` merges and preserves email/encryptedPassword.
142
+ const store = new SecretsWebexCredentialStore({ mode: 'host', secretsPath })
143
+ const nowIso = new Date().toISOString()
144
+ const previousExpiresAt = parsed.accounts[decision.account.account_id]?.expires_at ?? 0
145
+ await store.setAccount({
146
+ account_id: decision.account.account_id,
147
+ access_token: result.accessToken,
148
+ refresh_token: result.refreshToken,
149
+ expires_at: result.expiresAt,
150
+ device_url: result.deviceUrl,
151
+ user_id: result.userId,
152
+ created_at: decision.account.created_at,
153
+ updated_at: nowIso,
154
+ email: decision.account.email,
155
+ })
156
+
157
+ return {
158
+ kind: 'ok',
159
+ account_id: decision.account.account_id,
160
+ previousExpiresAt,
161
+ nextExpiresAt: result.expiresAt,
162
+ }
163
+ }
164
+
165
+ function parseBlockOrEmpty(value: unknown): WebexChannelBlock {
166
+ if (value === undefined) return { currentAccount: null, accounts: {} }
167
+ return value as WebexChannelBlock
168
+ }
169
+
170
+ function classifyLoginFailure(err: unknown, accountId: string): WebexRenewalAttempt {
171
+ const message = err instanceof Error ? err.message : String(err)
172
+ // agent-messenger's loginWithPassword throws WebexError with a `code` for
173
+ // unrecoverable auth states (SSO/IdP or MFA accounts that headless password
174
+ // login can't satisfy). Those need human reauth; everything else (network,
175
+ // 5xx, transient idbroker hiccup) is retried on the next tick.
176
+ const code = (err as { code?: unknown })?.code
177
+ if (code === 'sso_required' || code === 'mfa_required') {
178
+ return {
179
+ kind: 'reauth_required',
180
+ account_id: accountId,
181
+ reason: String(code),
182
+ message: `${message} — run \`typeclaw channel reauth webex\`.`,
183
+ }
184
+ }
185
+ return { kind: 'transient_failure', account_id: accountId, reason: message }
186
+ }
187
+
188
+ function classifyDecryptFailure(err: unknown, accountId: string): WebexRenewalDecision {
189
+ if (err instanceof KeyStoreError) {
190
+ if (err.code === 'missing') {
191
+ return {
192
+ kind: 'reauth_required',
193
+ reason: 'key_missing',
194
+ message: `Encryption key missing for Webex account ${accountId} — run \`typeclaw channel reauth webex\` to mint a fresh one.`,
195
+ }
196
+ }
197
+ return {
198
+ kind: 'reauth_required',
199
+ reason: 'key_missing',
200
+ message: `Encryption key for Webex account ${accountId} is unusable (${err.code}: ${err.message}). Move it aside and run \`typeclaw channel reauth webex\` to mint a fresh one.`,
201
+ }
202
+ }
203
+ if (err instanceof EncryptionError) {
204
+ return {
205
+ kind: 'reauth_required',
206
+ reason: 'decrypt_failed',
207
+ message: `Could not decrypt stored Webex password (${err.code}) — run \`typeclaw channel reauth webex\`.`,
208
+ }
209
+ }
210
+ return {
211
+ kind: 'reauth_required',
212
+ reason: 'decrypt_failed',
213
+ message: `Could not decrypt stored Webex password (${err instanceof Error ? err.message : String(err)}).`,
214
+ }
215
+ }
@@ -8,7 +8,7 @@ import {
8
8
  type CreateSessionOptions,
9
9
  type CreateSessionResult,
10
10
  } from '@/agent'
11
- import { applyTurnThinkingLevel } from '@/agent/attention-escalation'
11
+ import { applyTurnThinkingLevel, getQuestionSignal, type QuestionSignal } from '@/agent/attention-escalation'
12
12
  import { runPluginDoctorChecks, runPluginDoctorFix } from '@/agent/doctor'
13
13
  import type { LiveSessionRegistry } from '@/agent/live-sessions'
14
14
  import type { LiveSubagentRegistry } from '@/agent/live-subagents'
@@ -165,6 +165,14 @@ type TunnelLogsWs = ServerWebSocket<TunnelLogsWsData>
165
165
  type InspectWs = ServerWebSocket<InspectWsData>
166
166
  type AnyOwnerWs = Ws | CommandWs
167
167
 
168
+ // A turn whose assistant leaf aborted or errored never produced a usable turn,
169
+ // so its question shape must not seed the next turn's cross-turn escalation.
170
+ function tuiTurnLeafFailed(session: AgentSession): boolean {
171
+ const leaf = session.sessionManager?.getLeafEntry()
172
+ if (!leaf || leaf.type !== 'message' || leaf.message.role !== 'assistant') return false
173
+ return leaf.message.stopReason === 'aborted' || leaf.message.stopReason === 'error'
174
+ }
175
+
168
176
  type QueuedPrompt = {
169
177
  streamMessageId: StreamMessageId
170
178
  text: string
@@ -180,6 +188,9 @@ type SessionState = {
180
188
  // loop, no-stream fallback) can use the live getter as the reset target — both
181
189
  // read this captured default instead.
182
190
  turnThinkingDefault: AgentSession['thinkingLevel']
191
+ // Prior real user turn's question shape, for cross-turn "Jeff Bezos" escalation.
192
+ // Null until the first user turn; carried turn-to-turn within this session only.
193
+ lastQuestionSignal: QuestionSignal | null
183
194
  sessionFileId: string
184
195
  origin: SessionOrigin
185
196
  sessionManager: { getSessionFile: () => string | undefined } | undefined
@@ -525,6 +536,7 @@ export function createServer({
525
536
  const state: SessionState = {
526
537
  session,
527
538
  turnThinkingDefault: session.thinkingLevel,
539
+ lastQuestionSignal: null,
528
540
  sessionFileId,
529
541
  origin,
530
542
  sessionManager,
@@ -789,8 +801,12 @@ export function createServer({
789
801
  retrievalContext.results.length > 0
790
802
  ? `${renderTurnTimeAnchor()}\n\n${msg.text}\n\n${retrievalContext.results}`
791
803
  : `${renderTurnTimeAnchor()}\n\n${msg.text}`
792
- applyTurnThinkingLevel(state.session, msg.text, state.turnThinkingDefault)
804
+ applyTurnThinkingLevel(state.session, msg.text, state.turnThinkingDefault, state.lastQuestionSignal)
793
805
  await state.session.prompt(turnText)
806
+ // A usable turn seeds the next turn's escalation; a failed leaf must
807
+ // CLEAR the prior signal (not just skip), else an older question
808
+ // leaks across the failed turn and wrongly escalates the next one.
809
+ state.lastQuestionSignal = tuiTurnLeafFailed(state.session) ? null : getQuestionSignal(msg.text)
794
810
  send(ws, doneMessage(state))
795
811
  } catch (err) {
796
812
  const message = err instanceof Error ? err.message : String(err)
@@ -1094,8 +1110,14 @@ async function drain(
1094
1110
  retrievalContext.results.length > 0
1095
1111
  ? `${renderTurnTimeAnchor()}\n\n${item.text}\n\n${retrievalContext.results}`
1096
1112
  : `${renderTurnTimeAnchor()}\n\n${item.text}`
1097
- applyTurnThinkingLevel(state.session, item.text, state.turnThinkingDefault)
1113
+ applyTurnThinkingLevel(state.session, item.text, state.turnThinkingDefault, state.lastQuestionSignal)
1098
1114
  await state.session.prompt(turnText)
1115
+ // Only real user turns move the signal: a usable turn seeds it, a failed
1116
+ // leaf CLEARS it (else an older question leaks across the failed turn).
1117
+ // Todo-continuation turns are not user turns, so they leave it untouched.
1118
+ if (item.source !== TODO_CONTINUATION_SOURCE) {
1119
+ state.lastQuestionSignal = tuiTurnLeafFailed(state.session) ? null : getQuestionSignal(item.text)
1120
+ }
1099
1121
  send(ws, doneMessage(state))
1100
1122
  } catch (err) {
1101
1123
  const message = err instanceof Error ? err.message : String(err)
@@ -454,13 +454,18 @@
454
454
  },
455
455
  "compose": {
456
456
  "default": {
457
- "exclude": false
457
+ "exclude": false,
458
+ "monorepo": false
458
459
  },
459
460
  "type": "object",
460
461
  "properties": {
461
462
  "exclude": {
462
463
  "default": false,
463
464
  "type": "boolean"
465
+ },
466
+ "monorepo": {
467
+ "default": false,
468
+ "type": "boolean"
464
469
  }
465
470
  }
466
471
  },