typeclaw 0.38.1 → 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.
- package/README.md +5 -0
- package/package.json +2 -2
- package/src/agent/attention-escalation.ts +158 -7
- package/src/agent/auth.ts +2 -2
- package/src/agent/git-nudge.ts +7 -7
- package/src/agent/index.ts +25 -2
- package/src/agent/restart/index.ts +17 -8
- package/src/agent/session-origin.ts +21 -0
- package/src/agent/subagents.ts +29 -1
- package/src/agent/system-prompt.ts +18 -5
- package/src/agent/tools/restart.ts +0 -3
- package/src/agent/tools/spawn-subagent.ts +7 -0
- package/src/bundled-plugins/backup/index.ts +5 -2
- package/src/bundled-plugins/backup/runner.ts +55 -23
- package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +7 -8
- package/src/bundled-plugins/memory/dreaming.ts +37 -24
- package/src/bundled-plugins/memory/index.ts +24 -6
- package/src/bundled-plugins/memory/memory-logger.ts +14 -10
- package/src/bundled-plugins/operator/operator.ts +1 -0
- package/src/channels/adapters/kakaotalk-membership.ts +67 -0
- package/src/channels/adapters/kakaotalk.ts +8 -0
- package/src/channels/adapters/line-token.ts +55 -0
- package/src/channels/adapters/line.ts +74 -0
- package/src/channels/adapters/webex-bot-classify.ts +14 -1
- package/src/channels/adapters/webex-bot.ts +24 -1
- package/src/channels/adapters/webex-classify.ts +16 -1
- package/src/channels/adapters/webex.ts +27 -1
- package/src/channels/router.ts +55 -2
- package/src/cli/hostd.ts +40 -0
- package/src/cli/model.ts +143 -3
- package/src/config/config.ts +101 -36
- package/src/config/index.ts +3 -0
- package/src/config/models-mutation.ts +105 -15
- package/src/config/providers-mutation.ts +4 -4
- package/src/config/providers.ts +6 -14
- package/src/container/shared.ts +136 -14
- package/src/container/shell.ts +12 -2
- package/src/container/start.ts +25 -7
- package/src/doctor/commit.ts +10 -10
- package/src/dreams/git.ts +20 -7
- package/src/dreams/index.ts +22 -7
- package/src/git/reconcile-ignored.ts +56 -27
- package/src/git/resolve-agent-git.ts +12 -0
- package/src/git/system-commit.ts +16 -10
- package/src/hostd/daemon.ts +16 -0
- package/src/hostd/index.ts +1 -11
- package/src/hostd/paths.ts +0 -16
- package/src/hostd/webex-renewal-manager.ts +216 -0
- package/src/init/dockerfile.ts +13 -4
- package/src/init/gitignore.ts +4 -2
- package/src/run/index.ts +4 -1
- package/src/secrets/schema.ts +1 -0
- package/src/secrets/webex-renewal.ts +215 -0
- package/src/server/index.ts +25 -3
- package/src/skills/typeclaw-config/SKILL.md +18 -16
- package/typeclaw.schema.json +172 -1
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// LINE access tokens (`auth_token`) are JWTs with a ~7-day lifetime. The adapter
|
|
2
|
+
// schedules a proactive refresh ahead of expiry rather than waiting for the SDK's
|
|
3
|
+
// reactive MUST_REFRESH_V3_TOKEN path, which only fires on a live request and
|
|
4
|
+
// surfaces a cryptic failure when the token is already fully expired at startup.
|
|
5
|
+
|
|
6
|
+
// Refresh once the token is within this window of its expiry. The LINE refresh
|
|
7
|
+
// token lives ~365 days and rotates on use, so refreshing early is cheap and
|
|
8
|
+
// leaves margin for missed timers (container asleep, listener reconnecting).
|
|
9
|
+
export const LINE_TOKEN_REFRESH_SKEW_MS = 24 * 60 * 60 * 1000
|
|
10
|
+
|
|
11
|
+
// Clamp the scheduled timer so a malformed or far-future `exp` can't push the
|
|
12
|
+
// next refresh check beyond a day, and a near/past expiry retries promptly
|
|
13
|
+
// rather than busy-looping.
|
|
14
|
+
const MIN_REFRESH_DELAY_MS = 60 * 1000
|
|
15
|
+
const MAX_REFRESH_DELAY_MS = 24 * 60 * 60 * 1000
|
|
16
|
+
|
|
17
|
+
export function decodeJwtExpMs(token: string): number | null {
|
|
18
|
+
const parts = token.split('.')
|
|
19
|
+
if (parts.length < 2) return null
|
|
20
|
+
const payload = parts[1]
|
|
21
|
+
if (payload === undefined || payload === '') return null
|
|
22
|
+
try {
|
|
23
|
+
const json = Buffer.from(base64UrlToBase64(payload), 'base64').toString('utf-8')
|
|
24
|
+
const parsed: unknown = JSON.parse(json)
|
|
25
|
+
if (typeof parsed !== 'object' || parsed === null) return null
|
|
26
|
+
const exp = (parsed as { exp?: unknown }).exp
|
|
27
|
+
if (typeof exp !== 'number' || !Number.isFinite(exp)) return null
|
|
28
|
+
return exp * 1000
|
|
29
|
+
} catch {
|
|
30
|
+
return null
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function isTokenNearExpiry(token: string, now: number, skewMs = LINE_TOKEN_REFRESH_SKEW_MS): boolean {
|
|
35
|
+
const expMs = decodeJwtExpMs(token)
|
|
36
|
+
// A token we can't decode is treated as needing refresh: better to attempt a
|
|
37
|
+
// (cheap, idempotent) refresh than to sit on an opaque, possibly-dead token.
|
|
38
|
+
if (expMs === null) return true
|
|
39
|
+
return now >= expMs - skewMs
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function nextRefreshDelayMs(token: string, now: number, skewMs = LINE_TOKEN_REFRESH_SKEW_MS): number {
|
|
43
|
+
const expMs = decodeJwtExpMs(token)
|
|
44
|
+
if (expMs === null) return MIN_REFRESH_DELAY_MS
|
|
45
|
+
const target = expMs - skewMs
|
|
46
|
+
const delay = target - now
|
|
47
|
+
if (delay <= 0) return MIN_REFRESH_DELAY_MS
|
|
48
|
+
return Math.min(Math.max(delay, MIN_REFRESH_DELAY_MS), MAX_REFRESH_DELAY_MS)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function base64UrlToBase64(input: string): string {
|
|
52
|
+
const replaced = input.replace(/-/g, '+').replace(/_/g, '/')
|
|
53
|
+
const pad = replaced.length % 4
|
|
54
|
+
return pad === 0 ? replaced : replaced + '='.repeat(4 - pad)
|
|
55
|
+
}
|
|
@@ -29,6 +29,7 @@ import { splitInboundLine } from './line-attachment'
|
|
|
29
29
|
import { createLineChannelResolver } from './line-channel-resolver'
|
|
30
30
|
import { classifyInbound } from './line-classify'
|
|
31
31
|
import { toLinePlainText } from './line-format'
|
|
32
|
+
import { LINE_TOKEN_REFRESH_SKEW_MS, nextRefreshDelayMs } from './line-token'
|
|
32
33
|
|
|
33
34
|
// Structural duck-type of the upstream LineClient class. Declaring this as an
|
|
34
35
|
// interface (rather than reusing the nominal class type) lets test fakes
|
|
@@ -41,6 +42,11 @@ export interface LineClient {
|
|
|
41
42
|
getMessages(chatId: string, options?: { count?: number }): Promise<LineMessage[]>
|
|
42
43
|
sendMessage(chatId: string, text: string): Promise<LineSendResult>
|
|
43
44
|
close(): void
|
|
45
|
+
// Optional on the structural type: older SDK builds predate the refresh
|
|
46
|
+
// surface, so the adapter feature-detects both before using them and a
|
|
47
|
+
// missing method degrades to "no proactive refresh" rather than a crash.
|
|
48
|
+
ensureFreshAuthToken?: (options?: { skewMs?: number }) => Promise<string | null>
|
|
49
|
+
onTokenUpdate?: (listener: (authToken: string) => void) => void
|
|
44
50
|
}
|
|
45
51
|
|
|
46
52
|
export interface LineListener {
|
|
@@ -53,6 +59,7 @@ export interface LineListener {
|
|
|
53
59
|
export type LineCredentialStore = {
|
|
54
60
|
load(): Promise<LineConfig>
|
|
55
61
|
getAccount(id?: string): Promise<LineAccountCredentials | null>
|
|
62
|
+
setAccount?(account: LineAccountCredentials): Promise<void>
|
|
56
63
|
}
|
|
57
64
|
|
|
58
65
|
const LineClient = RealLineClient as unknown as new (credManager?: LineCredentialManager) => LineClient
|
|
@@ -79,6 +86,7 @@ export type LineAdapterOptions = {
|
|
|
79
86
|
client?: LineClient
|
|
80
87
|
clientFactory?: (credManager?: LineCredentialManager) => LineClient
|
|
81
88
|
listenerFactory?: (client: LineClient) => LineListener
|
|
89
|
+
now?: () => number
|
|
82
90
|
}
|
|
83
91
|
|
|
84
92
|
export type LineAdapter = {
|
|
@@ -181,6 +189,14 @@ export function createLineAdapter(options: LineAdapterOptions): LineAdapter {
|
|
|
181
189
|
let started = false
|
|
182
190
|
let inflightInbounds = 0
|
|
183
191
|
let stopWaiters: Array<() => void> = []
|
|
192
|
+
let refreshTimer: ReturnType<typeof setTimeout> | null = null
|
|
193
|
+
// currentAuthToken tracks the freshest known token for refresh SCHEDULING;
|
|
194
|
+
// lastPersistedToken is the dedupe marker and only advances after a write to
|
|
195
|
+
// secrets actually succeeds, so a failed persist can be retried with the same
|
|
196
|
+
// token instead of being silently swallowed by the dedupe early-return.
|
|
197
|
+
let currentAuthToken: string | null = null
|
|
198
|
+
let lastPersistedToken: string | null = null
|
|
199
|
+
const now = options.now ?? Date.now
|
|
184
200
|
|
|
185
201
|
const channelResolver = createLineChannelResolver({ client, logger })
|
|
186
202
|
|
|
@@ -199,6 +215,51 @@ export function createLineAdapter(options: LineAdapterOptions): LineAdapter {
|
|
|
199
215
|
|
|
200
216
|
const outboundCallback = createOutboundCallback({ client, logger, formatChannelTag })
|
|
201
217
|
|
|
218
|
+
// The SDK's AuthService updates the LIVE client's token in-place and emits this
|
|
219
|
+
// event; we mirror it into secrets.json so the next container start boots from a
|
|
220
|
+
// fresh token instead of a dead one. The refresh token (which rotates on use)
|
|
221
|
+
// stays the SDK FileStorage's responsibility and is never copied here.
|
|
222
|
+
const persistAuthToken = async (authToken: string): Promise<void> => {
|
|
223
|
+
currentAuthToken = authToken
|
|
224
|
+
if (authToken === lastPersistedToken) return
|
|
225
|
+
const store = options.credentialsStore
|
|
226
|
+
if (!store?.setAccount) return
|
|
227
|
+
try {
|
|
228
|
+
const account = await store.getAccount()
|
|
229
|
+
if (account === null) return
|
|
230
|
+
await store.setAccount({ ...account, auth_token: authToken, updated_at: new Date(now()).toISOString() })
|
|
231
|
+
lastPersistedToken = authToken
|
|
232
|
+
logger.info('[line] persisted refreshed auth token to secrets')
|
|
233
|
+
} catch (err) {
|
|
234
|
+
logger.warn(`[line] failed to persist refreshed auth token: ${describe(err)}`)
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const refreshNow = async (): Promise<void> => {
|
|
239
|
+
if (!client.ensureFreshAuthToken) return
|
|
240
|
+
try {
|
|
241
|
+
const token = await client.ensureFreshAuthToken({ skewMs: LINE_TOKEN_REFRESH_SKEW_MS })
|
|
242
|
+
if (token) await persistAuthToken(token)
|
|
243
|
+
} catch (err) {
|
|
244
|
+
logger.warn(`[line] token refresh failed: ${describe(err)}`)
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const scheduleRefresh = (): void => {
|
|
249
|
+
if (refreshTimer !== null) clearTimeout(refreshTimer)
|
|
250
|
+
if (!client.ensureFreshAuthToken) return
|
|
251
|
+
const token = currentAuthToken
|
|
252
|
+
const delay = token ? nextRefreshDelayMs(token, now()) : LINE_TOKEN_REFRESH_SKEW_MS
|
|
253
|
+
refreshTimer = setTimeout(() => {
|
|
254
|
+
void (async () => {
|
|
255
|
+
if (!started) return
|
|
256
|
+
await refreshNow()
|
|
257
|
+
if (started) scheduleRefresh()
|
|
258
|
+
})()
|
|
259
|
+
}, delay)
|
|
260
|
+
refreshTimer.unref?.()
|
|
261
|
+
}
|
|
262
|
+
|
|
202
263
|
const processInbound = async (event: LinePushMessageEvent): Promise<void> => {
|
|
203
264
|
inflightInbounds++
|
|
204
265
|
try {
|
|
@@ -255,6 +316,10 @@ export function createLineAdapter(options: LineAdapterOptions): LineAdapter {
|
|
|
255
316
|
async start(): Promise<void> {
|
|
256
317
|
if (started) return
|
|
257
318
|
started = true
|
|
319
|
+
client.onTokenUpdate?.((authToken) => {
|
|
320
|
+
void persistAuthToken(authToken)
|
|
321
|
+
})
|
|
322
|
+
|
|
258
323
|
try {
|
|
259
324
|
const credentialStore = options.credentialsStore ?? null
|
|
260
325
|
if (credentialStore !== null) {
|
|
@@ -262,6 +327,8 @@ export function createLineAdapter(options: LineAdapterOptions): LineAdapter {
|
|
|
262
327
|
if (account === null) {
|
|
263
328
|
throw new Error('no LINE account in secrets.json#channels.line (run typeclaw init to authenticate)')
|
|
264
329
|
}
|
|
330
|
+
currentAuthToken = account.auth_token
|
|
331
|
+
lastPersistedToken = account.auth_token
|
|
265
332
|
await client.login(account)
|
|
266
333
|
} else {
|
|
267
334
|
await client.login()
|
|
@@ -272,6 +339,9 @@ export function createLineAdapter(options: LineAdapterOptions): LineAdapter {
|
|
|
272
339
|
throw err
|
|
273
340
|
}
|
|
274
341
|
|
|
342
|
+
await refreshNow()
|
|
343
|
+
scheduleRefresh()
|
|
344
|
+
|
|
275
345
|
try {
|
|
276
346
|
const profile = await client.getProfile()
|
|
277
347
|
selfUserId = profile.mid
|
|
@@ -329,6 +399,10 @@ export function createLineAdapter(options: LineAdapterOptions): LineAdapter {
|
|
|
329
399
|
async stop(): Promise<void> {
|
|
330
400
|
if (!started) return
|
|
331
401
|
started = false
|
|
402
|
+
if (refreshTimer !== null) {
|
|
403
|
+
clearTimeout(refreshTimer)
|
|
404
|
+
refreshTimer = null
|
|
405
|
+
}
|
|
332
406
|
options.router.unregisterOutbound('line', outboundCallback)
|
|
333
407
|
options.router.unregisterChannelNameResolver('line', channelResolver.resolve)
|
|
334
408
|
options.router.unregisterHistory('line', historyCallback)
|
|
@@ -12,13 +12,18 @@ export type InboundClassification =
|
|
|
12
12
|
| { kind: 'drop'; reason: InboundDropReason }
|
|
13
13
|
| { kind: 'route'; payload: InboundMessage }
|
|
14
14
|
|
|
15
|
+
// `botPersonEmail` is a second self-identity anchor alongside `botPersonRef`:
|
|
16
|
+
// legacy Hydra accounts can decode the bot identity to an email on one side and a
|
|
17
|
+
// UUID on the other, so a ref-only check leaks the agent's own reply back as a
|
|
18
|
+
// new inbound. Matching personEmail closes that echo loop. See webex-classify.ts.
|
|
15
19
|
export function classifyInbound(
|
|
16
20
|
event: WebexInboundMessage,
|
|
17
21
|
_config: ChannelAdapterConfig,
|
|
18
22
|
botPersonRef: string | null,
|
|
19
23
|
selfAliases: readonly string[] = [],
|
|
24
|
+
botPersonEmail: string | null = null,
|
|
20
25
|
): InboundClassification {
|
|
21
|
-
if (
|
|
26
|
+
if (isSelfAuthor(event, botPersonRef, botPersonEmail)) {
|
|
22
27
|
return { kind: 'drop', reason: 'self_author' }
|
|
23
28
|
}
|
|
24
29
|
|
|
@@ -66,6 +71,14 @@ export function classifyInbound(
|
|
|
66
71
|
}
|
|
67
72
|
}
|
|
68
73
|
|
|
74
|
+
function isSelfAuthor(event: WebexInboundMessage, botPersonRef: string | null, botPersonEmail: string | null): boolean {
|
|
75
|
+
if (botPersonRef !== null && event.personRef === botPersonRef) return true
|
|
76
|
+
if (botPersonEmail !== null && event.personEmail !== '') {
|
|
77
|
+
return event.personEmail.toLowerCase() === botPersonEmail.toLowerCase()
|
|
78
|
+
}
|
|
79
|
+
return false
|
|
80
|
+
}
|
|
81
|
+
|
|
69
82
|
type SplitInbound = { text: string; attachments: InboundAttachment[] }
|
|
70
83
|
|
|
71
84
|
function splitInbound(event: WebexInboundMessage): SplitInbound {
|
|
@@ -136,14 +136,24 @@ async function defaultReadFile(path: string): Promise<WebexOutboundFile> {
|
|
|
136
136
|
return { content: Bun.file(path), filename: path.split('/').pop() ?? 'attachment' }
|
|
137
137
|
}
|
|
138
138
|
|
|
139
|
+
// See webex.ts: the bot client has no AbortSignal either, so a hung listMessages
|
|
140
|
+
// is bounded by a tighter internal deadline than the router's 5s history ceiling.
|
|
141
|
+
const WEBEX_HISTORY_COLD_FETCH_TIMEOUT_MS = 2500
|
|
142
|
+
|
|
139
143
|
export function createWebexHistoryCallback(deps: {
|
|
140
144
|
client: Pick<WebexBotClient, 'listMessages'>
|
|
141
145
|
logger: WebexBotAdapterLogger
|
|
142
146
|
botPersonIdRef: () => string | null
|
|
147
|
+
timeoutMs?: number
|
|
143
148
|
}): HistoryCallback {
|
|
149
|
+
const timeoutMs = deps.timeoutMs ?? WEBEX_HISTORY_COLD_FETCH_TIMEOUT_MS
|
|
144
150
|
return async (args: FetchHistoryArgs): Promise<FetchHistoryResult> => {
|
|
145
151
|
try {
|
|
146
|
-
const messages = await
|
|
152
|
+
const messages = await raceWithTimeout(
|
|
153
|
+
deps.client.listMessages(args.chat, { max: clampLimit(args.limit, 100) }),
|
|
154
|
+
timeoutMs,
|
|
155
|
+
'[webex-bot] history fetch',
|
|
156
|
+
)
|
|
147
157
|
return { ok: true, messages: messages.map((m) => mapWebexHistoryMessage(m, deps.botPersonIdRef())).reverse() }
|
|
148
158
|
} catch (err) {
|
|
149
159
|
const message = describe(err)
|
|
@@ -297,6 +307,7 @@ export function createWebexBotAdapter(options: WebexBotAdapterOptions): WebexBot
|
|
|
297
307
|
options.configRef(),
|
|
298
308
|
botSnapshot?.ref ?? null,
|
|
299
309
|
options.selfAliasesRef?.() ?? [],
|
|
310
|
+
botSnapshot?.emails[0] ?? null,
|
|
300
311
|
)
|
|
301
312
|
if (verdict.kind === 'drop') {
|
|
302
313
|
logger.info(`[webex-bot] dropped id=${event.ref} reason=${verdict.reason}${dropHint(verdict.reason)}`)
|
|
@@ -451,6 +462,18 @@ function describe(err: unknown): string {
|
|
|
451
462
|
return err instanceof Error ? err.message : String(err)
|
|
452
463
|
}
|
|
453
464
|
|
|
465
|
+
async function raceWithTimeout<T>(work: Promise<T>, ms: number, label: string): Promise<T> {
|
|
466
|
+
let timer: ReturnType<typeof setTimeout> | null = null
|
|
467
|
+
const timeout = new Promise<never>((_, reject) => {
|
|
468
|
+
timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms)
|
|
469
|
+
})
|
|
470
|
+
try {
|
|
471
|
+
return await Promise.race([work, timeout])
|
|
472
|
+
} finally {
|
|
473
|
+
if (timer !== null) clearTimeout(timer)
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
454
477
|
function dropHint(reason: InboundDropReason): string {
|
|
455
478
|
switch (reason) {
|
|
456
479
|
case 'empty_content':
|
|
@@ -16,13 +16,20 @@ export type InboundClassification =
|
|
|
16
16
|
// `botPersonRef` is the bot's decoded UUID ref (from WebexPerson.ref), matched
|
|
17
17
|
// against the event's *Ref fields so identity comparison happens entirely in
|
|
18
18
|
// ref-space — the same currency typeclaw now stores as ChannelKey/authorId.
|
|
19
|
+
//
|
|
20
|
+
// `botPersonEmail` is a second self-identity anchor: legacy Hydra accounts can
|
|
21
|
+
// surface the bot's ref as an email on one side (`/people/me`) and a UUID on the
|
|
22
|
+
// other (Mercury event), so a ref-only check leaks the agent's own reply back as
|
|
23
|
+
// a new inbound and burns a full prompt cycle. Matching personEmail closes that
|
|
24
|
+
// echo loop regardless of which side decoded to which form.
|
|
19
25
|
export function classifyInbound(
|
|
20
26
|
event: WebexInboundMessage,
|
|
21
27
|
_config: ChannelAdapterConfig,
|
|
22
28
|
botPersonRef: string | null,
|
|
23
29
|
selfAliases: readonly string[] = [],
|
|
30
|
+
botPersonEmail: string | null = null,
|
|
24
31
|
): InboundClassification {
|
|
25
|
-
if (
|
|
32
|
+
if (isSelfAuthor(event, botPersonRef, botPersonEmail)) {
|
|
26
33
|
return { kind: 'drop', reason: 'self_author' }
|
|
27
34
|
}
|
|
28
35
|
|
|
@@ -72,6 +79,14 @@ export function classifyInbound(
|
|
|
72
79
|
}
|
|
73
80
|
}
|
|
74
81
|
|
|
82
|
+
function isSelfAuthor(event: WebexInboundMessage, botPersonRef: string | null, botPersonEmail: string | null): boolean {
|
|
83
|
+
if (botPersonRef !== null && event.personRef === botPersonRef) return true
|
|
84
|
+
if (botPersonEmail !== null && event.personEmail !== '') {
|
|
85
|
+
return event.personEmail.toLowerCase() === botPersonEmail.toLowerCase()
|
|
86
|
+
}
|
|
87
|
+
return false
|
|
88
|
+
}
|
|
89
|
+
|
|
75
90
|
type SplitInbound = { text: string; attachments: InboundAttachment[] }
|
|
76
91
|
|
|
77
92
|
function splitInbound(event: WebexInboundMessage): SplitInbound {
|
|
@@ -141,14 +141,27 @@ async function defaultReadFile(path: string): Promise<WebexOutboundFile> {
|
|
|
141
141
|
return { content: Bun.file(path), filename: path.split('/').pop() ?? 'attachment' }
|
|
142
142
|
}
|
|
143
143
|
|
|
144
|
+
// The Webex REST/internal client offers no AbortSignal, so a hung `listMessages`
|
|
145
|
+
// would otherwise block cold-start prefetch for the router's full 5s history
|
|
146
|
+
// ceiling before degrading. Racing it against a tighter internal deadline lets
|
|
147
|
+
// prefetch fall back to membership-derivation (or skip) seconds sooner, mirroring
|
|
148
|
+
// the cold-fetch fail-fast posture the membership resolver already uses.
|
|
149
|
+
const WEBEX_HISTORY_COLD_FETCH_TIMEOUT_MS = 2500
|
|
150
|
+
|
|
144
151
|
export function createWebexHistoryCallback(deps: {
|
|
145
152
|
client: Pick<WebexClient, 'listMessages'>
|
|
146
153
|
logger: WebexAdapterLogger
|
|
147
154
|
botPersonIdRef: () => string | null
|
|
155
|
+
timeoutMs?: number
|
|
148
156
|
}): HistoryCallback {
|
|
157
|
+
const timeoutMs = deps.timeoutMs ?? WEBEX_HISTORY_COLD_FETCH_TIMEOUT_MS
|
|
149
158
|
return async (args: FetchHistoryArgs): Promise<FetchHistoryResult> => {
|
|
150
159
|
try {
|
|
151
|
-
const messages = await
|
|
160
|
+
const messages = await raceWithTimeout(
|
|
161
|
+
deps.client.listMessages(args.chat, { max: clampLimit(args.limit, 100) }),
|
|
162
|
+
timeoutMs,
|
|
163
|
+
'[webex] history fetch',
|
|
164
|
+
)
|
|
152
165
|
const authorById = new Map(messages.map((m) => [m.ref, m.personRef]))
|
|
153
166
|
const botPersonId = deps.botPersonIdRef()
|
|
154
167
|
return { ok: true, messages: messages.map((m) => mapWebexHistoryMessage(m, botPersonId, authorById)).reverse() }
|
|
@@ -305,6 +318,7 @@ export function createWebexAdapter(options: WebexAdapterOptions): WebexAdapter {
|
|
|
305
318
|
options.configRef(),
|
|
306
319
|
botSnapshot?.ref ?? null,
|
|
307
320
|
options.selfAliasesRef?.() ?? [],
|
|
321
|
+
botSnapshot?.emails[0] ?? null,
|
|
308
322
|
)
|
|
309
323
|
if (verdict.kind === 'drop') {
|
|
310
324
|
logger.info(`[webex] dropped id=${event.ref} reason=${verdict.reason}${dropHint(verdict.reason)}`)
|
|
@@ -482,6 +496,18 @@ function describe(err: unknown): string {
|
|
|
482
496
|
return err instanceof Error ? err.message : String(err)
|
|
483
497
|
}
|
|
484
498
|
|
|
499
|
+
async function raceWithTimeout<T>(work: Promise<T>, ms: number, label: string): Promise<T> {
|
|
500
|
+
let timer: ReturnType<typeof setTimeout> | null = null
|
|
501
|
+
const timeout = new Promise<never>((_, reject) => {
|
|
502
|
+
timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms)
|
|
503
|
+
})
|
|
504
|
+
try {
|
|
505
|
+
return await Promise.race([work, timeout])
|
|
506
|
+
} finally {
|
|
507
|
+
if (timer !== null) clearTimeout(timer)
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
485
511
|
function dropHint(reason: InboundDropReason): string {
|
|
486
512
|
switch (reason) {
|
|
487
513
|
case 'empty_content':
|
package/src/channels/router.ts
CHANGED
|
@@ -5,7 +5,7 @@ import type { AssistantMessage } from '@mariozechner/pi-ai'
|
|
|
5
5
|
import { SessionManager } from '@mariozechner/pi-coding-agent'
|
|
6
6
|
|
|
7
7
|
import { createSession, renderTurnRoleAnchor, renderTurnTimeAnchor, type AgentSession } from '@/agent'
|
|
8
|
-
import { applyTurnThinkingLevel } from '@/agent/attention-escalation'
|
|
8
|
+
import { applyTurnThinkingLevel, getQuestionSignal, type QuestionSignal } from '@/agent/attention-escalation'
|
|
9
9
|
import { forgetSharedLoopGuardTool } from '@/agent/plugin-tools'
|
|
10
10
|
import { subscribeProviderErrors } from '@/agent/provider-error'
|
|
11
11
|
import type { RestartHandoff } from '@/agent/restart-handoff'
|
|
@@ -578,6 +578,16 @@ type LiveSession = {
|
|
|
578
578
|
// turn moves `session.thinkingLevel` to `high`, so the live getter can't be the
|
|
579
579
|
// reset target — this preserves the real default across the session's lifetime.
|
|
580
580
|
turnThinkingDefault: AgentSession['thinkingLevel']
|
|
581
|
+
// Last COMPLETED real user turn's question shape, for cross-turn "Jeff Bezos"
|
|
582
|
+
// escalation. Read by the next turn; committed from pendingUserTurnSignal only
|
|
583
|
+
// when a logical turn finishes (no empty-turn retry queued).
|
|
584
|
+
lastQuestionSignal: QuestionSignal | null
|
|
585
|
+
// A real user turn's question shape captured at turn start but not yet
|
|
586
|
+
// committed: a `length`/`aborted` truncation spans the original batch plus
|
|
587
|
+
// reminder-only retry iterations, so the signal commits to lastQuestionSignal
|
|
588
|
+
// only when that whole logical turn completes (success or fallback), never
|
|
589
|
+
// from the truncated attempt and never leaving stale state across the turn.
|
|
590
|
+
pendingUserTurnSignal: { signal: QuestionSignal } | null
|
|
581
591
|
sessionId: string
|
|
582
592
|
dispose: () => Promise<void>
|
|
583
593
|
hooks: HookBus | undefined
|
|
@@ -788,6 +798,12 @@ type LiveSession = {
|
|
|
788
798
|
// shape as the skip lock. `null` when no disengage has been recorded.
|
|
789
799
|
// Compared by `turnSeq` so a stale value can't leak across turns.
|
|
790
800
|
disengagedTurn: number | null
|
|
801
|
+
// Stamped with the current `turnSeq` when validateChannelTurn posts the
|
|
802
|
+
// empty-turn fallback (retry exhaustion). Read by the cross-turn signal commit
|
|
803
|
+
// so a fallback turn — which produced no usable assistant reply — does not seed
|
|
804
|
+
// question escalation. Compared by `turnSeq` so a stale value can't leak across
|
|
805
|
+
// turns.
|
|
806
|
+
emptyTurnFallbackTurn: number | null
|
|
791
807
|
// Captured by drain() at batch dequeue; read+cleared by send() on the
|
|
792
808
|
// first tool-source send of the turn. The anchor decision (delay
|
|
793
809
|
// threshold + intervening-observed check) is evaluated at SEND time
|
|
@@ -1665,6 +1681,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1665
1681
|
keyId,
|
|
1666
1682
|
session: created.session,
|
|
1667
1683
|
turnThinkingDefault: created.session.thinkingLevel,
|
|
1684
|
+
lastQuestionSignal: null,
|
|
1685
|
+
pendingUserTurnSignal: null,
|
|
1668
1686
|
sessionId: created.sessionId,
|
|
1669
1687
|
dispose: created.dispose,
|
|
1670
1688
|
hooks: created.hooks,
|
|
@@ -1722,6 +1740,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1722
1740
|
skippedTurn: null,
|
|
1723
1741
|
skipLockedSendTurn: null,
|
|
1724
1742
|
disengagedTurn: null,
|
|
1743
|
+
emptyTurnFallbackTurn: null,
|
|
1725
1744
|
pendingQuoteCandidate: null,
|
|
1726
1745
|
recentEngagedPeerBotTurns: [],
|
|
1727
1746
|
consecutiveEngagedPeerBotTurns: 0,
|
|
@@ -2398,24 +2417,57 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2398
2417
|
live.successfulSendsAtTurnStart = successfulSendsBeforePrompt
|
|
2399
2418
|
live.skipLockedSendTurn = null
|
|
2400
2419
|
live.disengagedTurn = null
|
|
2420
|
+
live.emptyTurnFallbackTurn = null
|
|
2401
2421
|
live.policyDeniedToolSendsThisTurn.clear()
|
|
2402
2422
|
resetReviewTurn(live.sessionId)
|
|
2403
2423
|
const isRealUserTurn = batch.length > 0
|
|
2404
2424
|
const retrievalQuery = composeRetrievalQuery(batch)
|
|
2425
|
+
// A fresh real-user batch opens a new logical turn. Capture its question
|
|
2426
|
+
// shape as PENDING (committed only once the turn completes below). The
|
|
2427
|
+
// drain is serial and retries are reminder-only, so a prior pending must
|
|
2428
|
+
// already be resolved; a leftover here means a logical turn never
|
|
2429
|
+
// completed — fail closed by discarding it rather than misattributing.
|
|
2430
|
+
if (isRealUserTurn) {
|
|
2431
|
+
live.pendingUserTurnSignal = { signal: getQuestionSignal(retrievalQuery) }
|
|
2432
|
+
}
|
|
2405
2433
|
const retrievalContext = await fireSessionTurnStart(live, retrievalQuery)
|
|
2406
2434
|
const promptText = retrievalContext.results.length > 0 ? `${text}\n\n${retrievalContext.results}` : text
|
|
2407
|
-
applyTurnThinkingLevel(live.session, retrievalQuery, live.turnThinkingDefault)
|
|
2435
|
+
applyTurnThinkingLevel(live.session, retrievalQuery, live.turnThinkingDefault, live.lastQuestionSignal)
|
|
2408
2436
|
live.promptInFlight = true
|
|
2409
2437
|
try {
|
|
2410
2438
|
await live.session.prompt(promptText)
|
|
2411
2439
|
await validateChannelTurn(live, successfulSendsBeforePrompt)
|
|
2412
2440
|
live.consecutiveAborts = 0
|
|
2441
|
+
// Resolve the pending logical-turn signal on a binary rule: ONLY a
|
|
2442
|
+
// usable assistant reply (real model prose the user saw) seeds the next
|
|
2443
|
+
// turn's escalation. Every other terminal outcome CLEARS lastQuestionSignal
|
|
2444
|
+
// so an older question can't leak across the failed/silent turn:
|
|
2445
|
+
// - retry queued (`length`/`aborted`, budget left): turn still in
|
|
2446
|
+
// flight → leave both for the reminder-only iteration that ends it.
|
|
2447
|
+
// - usable reply → commit the pending signal.
|
|
2448
|
+
// - provider error / empty-turn fallback / NO_REPLY / skip (no usable
|
|
2449
|
+
// reply) → clear BOTH (pending and lastQuestionSignal).
|
|
2450
|
+
// A fallback sends via source:'system', which also bumps
|
|
2451
|
+
// successfulChannelSends, so it must be excluded explicitly.
|
|
2452
|
+
const retryQueuedThisTurn = live.emptyTurnRetries > emptyTurnRetriesBeforePrompt
|
|
2453
|
+
const providerErrorThisTurn = assistantLeafStopReason(live.session) === 'error'
|
|
2454
|
+
const fallbackPostedThisTurn = live.emptyTurnFallbackTurn === live.turnSeq
|
|
2455
|
+
const sentReplyThisTurn = live.successfulChannelSends > successfulSendsBeforePrompt
|
|
2456
|
+
const usableReplyThisTurn = sentReplyThisTurn && !fallbackPostedThisTurn && !providerErrorThisTurn
|
|
2457
|
+
if (live.pendingUserTurnSignal !== null && !retryQueuedThisTurn) {
|
|
2458
|
+
live.lastQuestionSignal = usableReplyThisTurn ? live.pendingUserTurnSignal.signal : null
|
|
2459
|
+
live.pendingUserTurnSignal = null
|
|
2460
|
+
}
|
|
2413
2461
|
logger.info(`[channels] ${live.keyId} prompted elapsed_ms=${now() - promptStart}`)
|
|
2414
2462
|
} catch (err) {
|
|
2415
2463
|
logger.error(`[channels] ${live.keyId}: prompt threw: ${describe(err)}`)
|
|
2416
2464
|
live.consecutiveSends.clear()
|
|
2417
2465
|
live.lastSentText.clear()
|
|
2418
2466
|
live.lastSendLeafId = null
|
|
2467
|
+
// A thrown prompt is a non-usable terminal outcome: drop pending AND
|
|
2468
|
+
// clear the prior signal so an older question can't leak across it.
|
|
2469
|
+
live.pendingUserTurnSignal = null
|
|
2470
|
+
live.lastQuestionSignal = null
|
|
2419
2471
|
} finally {
|
|
2420
2472
|
live.promptInFlight = false
|
|
2421
2473
|
const sentReplyThisTurn = live.successfulChannelSends > successfulSendsBeforePrompt
|
|
@@ -3533,6 +3585,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3533
3585
|
}
|
|
3534
3586
|
const postEmptyTurnFallback = async (cause: string): Promise<void> => {
|
|
3535
3587
|
logger.warn(`[channels] ${live.keyId} empty_turn_fallback cause=${cause}`)
|
|
3588
|
+
live.emptyTurnFallbackTurn = live.turnSeq
|
|
3536
3589
|
const result = await send(
|
|
3537
3590
|
{
|
|
3538
3591
|
adapter: live.key.adapter,
|
package/src/cli/hostd.ts
CHANGED
|
@@ -7,6 +7,7 @@ import { createKakaoRenewalManager } from '@/hostd/kakao-renewal-manager'
|
|
|
7
7
|
import { createPortbrokerManager } from '@/hostd/portbroker-manager'
|
|
8
8
|
import type { SupervisorLogEvent, SupervisorRestart } from '@/hostd/supervisor'
|
|
9
9
|
import { computeSourceVersion, resolveSrcRoot, UNVERSIONED_SENTINEL } from '@/hostd/version'
|
|
10
|
+
import { createWebexRenewalManager } from '@/hostd/webex-renewal-manager'
|
|
10
11
|
import { validateRestartDeps, type RestartDepsPreflightResult } from '@/init/restart-deps-preflight'
|
|
11
12
|
|
|
12
13
|
export const hostdCommand = defineCommand({
|
|
@@ -37,6 +38,18 @@ export const hostdCommand = defineCommand({
|
|
|
37
38
|
},
|
|
38
39
|
shouldRenew: ({ cwd }) => kakaoChannelConfigured(cwd),
|
|
39
40
|
})
|
|
41
|
+
const webexRenewal = createWebexRenewalManager({
|
|
42
|
+
onLog: (event) => writeLogLine(formatLog(event)),
|
|
43
|
+
onRenewalOk: async ({ containerName, cwd }) => {
|
|
44
|
+
// Restart so the in-memory WebexClient picks up the renewed token from
|
|
45
|
+
// secrets.json. Without this, the cron writes a fresh token but the
|
|
46
|
+
// running adapter keeps the old token in its getToken closure and still
|
|
47
|
+
// 401s on every outbound REST call + KMS key fetch.
|
|
48
|
+
const result = await hostdRestart({ containerName, cwd })
|
|
49
|
+
if (!result.ok) throw new Error(result.reason)
|
|
50
|
+
},
|
|
51
|
+
shouldRenew: ({ cwd }) => webexChannelConfigured(cwd),
|
|
52
|
+
})
|
|
40
53
|
|
|
41
54
|
const daemon = await startDaemon({
|
|
42
55
|
onLog: (e) => writeLogLine(formatLog(e)),
|
|
@@ -44,6 +57,7 @@ export const hostdCommand = defineCommand({
|
|
|
44
57
|
onShutdown: () => process.exit(0),
|
|
45
58
|
portbroker,
|
|
46
59
|
kakaoRenewal,
|
|
60
|
+
webexRenewal,
|
|
47
61
|
restartPreflight: buildHostdRestartPreflight(cliEntry, version, defaultPreflightDeps),
|
|
48
62
|
restart: hostdRestart,
|
|
49
63
|
})
|
|
@@ -53,6 +67,7 @@ export const hostdCommand = defineCommand({
|
|
|
53
67
|
.stop()
|
|
54
68
|
.then(() => portbroker.drain())
|
|
55
69
|
.then(() => kakaoRenewal.drain())
|
|
70
|
+
.then(() => webexRenewal.drain())
|
|
56
71
|
.then(() => process.exit(0))
|
|
57
72
|
}
|
|
58
73
|
process.on('SIGTERM', shutdown)
|
|
@@ -201,6 +216,22 @@ function formatLog(event: DaemonLogEvent | SupervisorLogEvent): string {
|
|
|
201
216
|
return `[hostd] kakao renewal scheduled container restart for ${event.containerName} account=${event.accountId}`
|
|
202
217
|
case 'kakao-renewal-restart-failed':
|
|
203
218
|
return `[hostd] kakao renewal container restart FAILED for ${event.containerName} account=${event.accountId}: ${event.reason}`
|
|
219
|
+
case 'webex-renewal-tick-start':
|
|
220
|
+
return `[hostd] webex renewal tick started for ${event.containerName}`
|
|
221
|
+
case 'webex-renewal-tick-skipped':
|
|
222
|
+
return `[hostd] webex renewal skipped for ${event.containerName}: ${event.reason}${event.expiresInMs !== undefined ? ` (expires in ${Math.round(event.expiresInMs / 1000 / 60 / 60)}h)` : ''}`
|
|
223
|
+
case 'webex-renewal-tick-ok':
|
|
224
|
+
return `[hostd] webex renewal OK for ${event.containerName} account=${event.accountId} (new token expires ${new Date(event.nextExpiresAt).toISOString()})`
|
|
225
|
+
case 'webex-renewal-tick-reauth-required':
|
|
226
|
+
return `[hostd] webex renewal REAUTH REQUIRED for ${event.containerName} account=${event.accountId} reason=${event.reason} — ${event.message}`
|
|
227
|
+
case 'webex-renewal-tick-transient-failure':
|
|
228
|
+
return `[hostd] webex renewal transient failure for ${event.containerName} account=${event.accountId}: ${event.reason}`
|
|
229
|
+
case 'webex-renewal-tick-error':
|
|
230
|
+
return `[hostd] webex renewal ERROR for ${event.containerName}: ${event.error}`
|
|
231
|
+
case 'webex-renewal-restart-scheduled':
|
|
232
|
+
return `[hostd] webex renewal scheduled container restart for ${event.containerName} account=${event.accountId}`
|
|
233
|
+
case 'webex-renewal-restart-failed':
|
|
234
|
+
return `[hostd] webex renewal container restart FAILED for ${event.containerName} account=${event.accountId}: ${event.reason}`
|
|
204
235
|
}
|
|
205
236
|
}
|
|
206
237
|
|
|
@@ -219,6 +250,15 @@ function kakaoChannelConfigured(cwd: string): boolean {
|
|
|
219
250
|
}
|
|
220
251
|
}
|
|
221
252
|
|
|
253
|
+
function webexChannelConfigured(cwd: string): boolean {
|
|
254
|
+
try {
|
|
255
|
+
const cfg = loadConfigSync(cwd)
|
|
256
|
+
return cfg.channels?.webex !== undefined
|
|
257
|
+
} catch {
|
|
258
|
+
return false
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
222
262
|
function formatPortForwardEvent(event: import('@/portbroker').PortForwardEvent): string {
|
|
223
263
|
switch (event.kind) {
|
|
224
264
|
case 'port-forward-opened':
|