typeclaw 0.48.11 → 0.48.13
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/package.json +7 -4
- package/src/agent/attention-escalation.ts +8 -5
- package/src/agent/auth-reloadable.ts +2 -3
- package/src/agent/auth.ts +59 -79
- package/src/agent/compaction.ts +2 -2
- package/src/agent/index.ts +42 -16
- package/src/agent/llm-replay-sanitizer.ts +1 -1
- package/src/agent/model-overrides.ts +1 -1
- package/src/agent/multimodal/look-at.ts +3 -3
- package/src/agent/multimodal/read-redirect.ts +1 -1
- package/src/agent/plugin-tools.ts +26 -31
- package/src/agent/reload-tool.ts +1 -1
- package/src/agent/subagents.ts +1 -1
- package/src/agent/tool-error-remediation.ts +1 -1
- package/src/agent/tool-result-budget.ts +2 -2
- package/src/agent/tools/channel-disengage.ts +2 -2
- package/src/agent/tools/channel-edit.ts +2 -2
- package/src/agent/tools/channel-fetch-attachment.ts +2 -2
- package/src/agent/tools/channel-history.ts +2 -2
- package/src/agent/tools/channel-react.ts +2 -2
- package/src/agent/tools/channel-read.ts +2 -2
- package/src/agent/tools/channel-reply.ts +2 -2
- package/src/agent/tools/channel-send.ts +2 -2
- package/src/agent/tools/grant-role.ts +2 -2
- package/src/agent/tools/post-github-review.ts +2 -2
- package/src/agent/tools/restart.ts +2 -2
- package/src/agent/tools/skip-response.ts +2 -2
- package/src/agent/tools/spawn-subagent.ts +2 -2
- package/src/agent/tools/stream-snapshot.ts +2 -2
- package/src/agent/tools/subagent-cancel.ts +2 -2
- package/src/agent/tools/subagent-output.ts +2 -2
- package/src/agent/tools/todo/index.ts +2 -2
- package/src/agent/tools/webfetch/tool.ts +2 -2
- package/src/agent/tools/websearch.ts +2 -2
- package/src/bundled-plugins/github-cli-auth/gh-command.ts +7 -1
- package/src/bundled-plugins/github-cli-auth/index.ts +1 -1
- package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -1
- package/src/bundled-plugins/memory/dreaming.ts +21 -6
- package/src/channels/adapters/kakaotalk-channel-resolver.ts +86 -16
- package/src/channels/adapters/kakaotalk.ts +7 -8
- package/src/channels/adapters/teams-classify.ts +21 -0
- package/src/channels/adapters/teams-edit.ts +2 -1
- package/src/channels/adapters/teams-format.ts +16 -0
- package/src/channels/adapters/teams.ts +12 -5
- package/src/channels/github-review-verdict-coordinator.ts +26 -3
- package/src/channels/router.ts +50 -25
- package/src/cli/compose.ts +3 -3
- package/src/cli/docker-preflight.ts +8 -4
- package/src/cli/model.ts +7 -5
- package/src/cli/oauth-callbacks.ts +38 -23
- package/src/cli/restart.ts +89 -23
- package/src/cli/start.ts +68 -16
- package/src/cli/status.ts +38 -6
- package/src/cli/stop.ts +5 -2
- package/src/compose/stop.ts +5 -4
- package/src/config/config.ts +62 -25
- package/src/config/providers.ts +272 -47
- package/src/container/build-cache.ts +807 -0
- package/src/container/compose-project.ts +4 -0
- package/src/container/docker-app.ts +74 -0
- package/src/container/log-archive.ts +33 -5
- package/src/container/memory-limit.ts +80 -0
- package/src/container/memory-oversubscription.ts +125 -0
- package/src/container/restart.ts +6 -1
- package/src/container/shared.ts +43 -16
- package/src/container/start.ts +280 -53
- package/src/container/stop.ts +19 -13
- package/src/container/verify-running.ts +12 -0
- package/src/cron/scheduler.ts +12 -4
- package/src/doctor/bounded-exec.ts +14 -0
- package/src/doctor/checks.ts +40 -15
- package/src/doctor/index.ts +14 -2
- package/src/doctor/plugin-bridge.ts +15 -3
- package/src/hostd/paths.ts +4 -0
- package/src/init/index.ts +4 -4
- package/src/init/oauth-login.ts +57 -17
- package/src/inspect/transcript-view.ts +6 -3
- package/src/run/channel-session-factory.ts +5 -4
- package/src/run/index.ts +27 -11
- package/src/run/resource-sample.ts +171 -0
- package/src/sandbox/index.ts +8 -1
- package/src/sandbox/session-tmp.ts +26 -1
- package/src/secrets/refresh-provider-oauth.ts +30 -76
- package/src/secrets/schema.ts +3 -4
- package/src/secrets/storage.ts +133 -234
- package/src/server/index.ts +1 -1
- package/src/sessions/index.ts +1 -1
- package/src/skills/typeclaw-config/SKILL.md +4 -4
- package/src/skills/typeclaw-plugins/SKILL.md +5 -5
- package/src/tui/index.ts +5 -3
- package/src/tui/theme.ts +1 -1
- package/typeclaw.schema.json +32 -1
- package/src/agent/adaptive-thinking-compat.ts +0 -79
- package/src/secrets/oauth-xai.ts +0 -348
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { readdirSync, readFileSync, statfsSync } from 'node:fs'
|
|
2
|
+
|
|
3
|
+
const BYTES_PER_MB = 1024 * 1024
|
|
4
|
+
|
|
5
|
+
export type ResourceSample = {
|
|
6
|
+
rssBytes: number
|
|
7
|
+
shmUsedBytes: number | null
|
|
8
|
+
shmTotalBytes: number | null
|
|
9
|
+
detachedProcesses: number | null
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// Processes reparented to PID 1 inside the container: anything the agent
|
|
13
|
+
// detached on purpose (a tmux server, a background dev server) plus anything
|
|
14
|
+
// left behind by a call that died. This count is the cheapest signal that
|
|
15
|
+
// something is accumulating across a container's life, and unlike
|
|
16
|
+
// /proc/<pid>/environ it is readable regardless of the per-tool sandbox's child
|
|
17
|
+
// user namespace — /proc/<pid>/stat is world-readable, environ is not.
|
|
18
|
+
export function countDetachedProcesses(procRoot = '/proc', selfPid = process.pid): number | null {
|
|
19
|
+
let entries: string[]
|
|
20
|
+
try {
|
|
21
|
+
entries = readdirSync(procRoot)
|
|
22
|
+
} catch {
|
|
23
|
+
return null
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
let count = 0
|
|
27
|
+
for (const entry of entries) {
|
|
28
|
+
if (!/^\d+$/.test(entry)) continue
|
|
29
|
+
const pid = Number(entry)
|
|
30
|
+
// PID 1 is the init shim itself, never its own orphan.
|
|
31
|
+
if (pid === 1) continue
|
|
32
|
+
// The agent runtime is itself a child of the init shim: the container runs
|
|
33
|
+
// with `--init` and the entrypoint execs Bun, so the agent normally sits at
|
|
34
|
+
// PID 2 with PPID 1. Counting it would give every clean container a
|
|
35
|
+
// permanent floor of 1 and bury the first real orphan in the noise.
|
|
36
|
+
if (pid === selfPid) continue
|
|
37
|
+
let raw: string
|
|
38
|
+
try {
|
|
39
|
+
raw = readFileSync(`${procRoot}/${entry}/stat`, 'utf8')
|
|
40
|
+
} catch {
|
|
41
|
+
// The process exited between readdir and read. Normal, not an error.
|
|
42
|
+
continue
|
|
43
|
+
}
|
|
44
|
+
if (parsePpidFromStat(raw) === 1) count++
|
|
45
|
+
}
|
|
46
|
+
return count
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// `/proc/<pid>/stat` is `pid (comm) state ppid ...`, and `comm` is the raw
|
|
50
|
+
// executable name — it can contain spaces AND parentheses, so neither a plain
|
|
51
|
+
// whitespace split nor a search for the FIRST ')' is correct. The kernel's own
|
|
52
|
+
// documented parse is to seek the LAST ')' and read fields after it, which is
|
|
53
|
+
// what this does: field 0 is state, field 1 is ppid.
|
|
54
|
+
export function parsePpidFromStat(raw: string): number | null {
|
|
55
|
+
const close = raw.lastIndexOf(')')
|
|
56
|
+
if (close < 0) return null
|
|
57
|
+
const fields = raw
|
|
58
|
+
.slice(close + 1)
|
|
59
|
+
.trim()
|
|
60
|
+
.split(/\s+/)
|
|
61
|
+
const ppid = Number(fields[1])
|
|
62
|
+
return Number.isInteger(ppid) && ppid >= 0 ? ppid : null
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function readShmUsage(path = '/dev/shm'): { usedBytes: number; totalBytes: number } | null {
|
|
66
|
+
try {
|
|
67
|
+
const fs = statfsSync(path)
|
|
68
|
+
const totalBytes = fs.blocks * fs.bsize
|
|
69
|
+
const usedBytes = (fs.blocks - fs.bfree) * fs.bsize
|
|
70
|
+
return { usedBytes, totalBytes }
|
|
71
|
+
} catch {
|
|
72
|
+
return null
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function collectResourceSample(
|
|
77
|
+
options: { procRoot?: string; shmPath?: string; selfPid?: number } = {},
|
|
78
|
+
): ResourceSample {
|
|
79
|
+
const shm = readShmUsage(options.shmPath)
|
|
80
|
+
return {
|
|
81
|
+
rssBytes: process.memoryUsage().rss,
|
|
82
|
+
shmUsedBytes: shm?.usedBytes ?? null,
|
|
83
|
+
shmTotalBytes: shm?.totalBytes ?? null,
|
|
84
|
+
detachedProcesses: countDetachedProcesses(options.procRoot, options.selfPid),
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function formatResourceSample(sample: ResourceSample): string {
|
|
89
|
+
const mb = (bytes: number | null): string => (bytes === null ? '?' : String(Math.round(bytes / BYTES_PER_MB)))
|
|
90
|
+
return [
|
|
91
|
+
`rss_mb=${mb(sample.rssBytes)}`,
|
|
92
|
+
`shm_used_mb=${mb(sample.shmUsedBytes)}`,
|
|
93
|
+
`shm_total_mb=${mb(sample.shmTotalBytes)}`,
|
|
94
|
+
`detached_procs=${sample.detachedProcesses ?? '?'}`,
|
|
95
|
+
].join(' ')
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export type SampleWatermark = {
|
|
99
|
+
rssBytes: number
|
|
100
|
+
shmUsedBytes: number
|
|
101
|
+
detachedProcesses: number
|
|
102
|
+
emittedAt: number
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Emit on growth, not on a clock.
|
|
106
|
+
//
|
|
107
|
+
// A steady heartbeat drowns the signal in identical lines and still misses the
|
|
108
|
+
// moment a number moved, while emitting every sample makes a 14-day log mostly
|
|
109
|
+
// noise. A leak is precisely a sequence of new high-water marks, so emitting
|
|
110
|
+
// only when one is set — with a margin so ordinary churn stays quiet — turns the
|
|
111
|
+
// log into the growth curve an OOM post-mortem actually needs. The periodic
|
|
112
|
+
// floor keeps a flat container from going completely silent, which is itself
|
|
113
|
+
// evidence.
|
|
114
|
+
export const RSS_GROWTH_MARGIN_BYTES = 128 * BYTES_PER_MB
|
|
115
|
+
export const SHM_GROWTH_MARGIN_BYTES = 64 * BYTES_PER_MB
|
|
116
|
+
export const HEARTBEAT_MS = 30 * 60 * 1000
|
|
117
|
+
|
|
118
|
+
export function shouldEmitSample(previous: SampleWatermark | null, sample: ResourceSample, now: number): boolean {
|
|
119
|
+
if (previous === null) return true
|
|
120
|
+
if (now - previous.emittedAt >= HEARTBEAT_MS) return true
|
|
121
|
+
if (sample.rssBytes >= previous.rssBytes + RSS_GROWTH_MARGIN_BYTES) return true
|
|
122
|
+
if ((sample.shmUsedBytes ?? 0) >= previous.shmUsedBytes + SHM_GROWTH_MARGIN_BYTES) return true
|
|
123
|
+
if ((sample.detachedProcesses ?? 0) > previous.detachedProcesses) return true
|
|
124
|
+
return false
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function nextWatermark(previous: SampleWatermark | null, sample: ResourceSample, now: number): SampleWatermark {
|
|
128
|
+
return {
|
|
129
|
+
rssBytes: Math.max(previous?.rssBytes ?? 0, sample.rssBytes),
|
|
130
|
+
shmUsedBytes: Math.max(previous?.shmUsedBytes ?? 0, sample.shmUsedBytes ?? 0),
|
|
131
|
+
detachedProcesses: Math.max(previous?.detachedProcesses ?? 0, sample.detachedProcesses ?? 0),
|
|
132
|
+
emittedAt: now,
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export const SAMPLE_INTERVAL_MS = 60_000
|
|
137
|
+
|
|
138
|
+
export type ResourceSamplerOptions = {
|
|
139
|
+
intervalMs?: number
|
|
140
|
+
collect?: () => ResourceSample
|
|
141
|
+
emit?: (line: string) => void
|
|
142
|
+
now?: () => number
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Returns a stop function rather than running forever so the caller owns the
|
|
146
|
+
// lifetime. `unref` keeps a container that is otherwise done from being held
|
|
147
|
+
// open by the sampler alone.
|
|
148
|
+
export function startResourceSampler(options: ResourceSamplerOptions = {}): () => void {
|
|
149
|
+
const intervalMs = options.intervalMs ?? SAMPLE_INTERVAL_MS
|
|
150
|
+
const collect = options.collect ?? (() => collectResourceSample())
|
|
151
|
+
const emit = options.emit ?? ((line: string) => console.info(line))
|
|
152
|
+
const now = options.now ?? (() => Date.now())
|
|
153
|
+
|
|
154
|
+
let watermark: SampleWatermark | null = null
|
|
155
|
+
const tick = (): void => {
|
|
156
|
+
try {
|
|
157
|
+
const sample = collect()
|
|
158
|
+
const at = now()
|
|
159
|
+
if (!shouldEmitSample(watermark, sample, at)) return
|
|
160
|
+
watermark = nextWatermark(watermark, sample, at)
|
|
161
|
+
emit(`[resource-sample] ${formatResourceSample(sample)}`)
|
|
162
|
+
} catch (err) {
|
|
163
|
+
// A sampler must never be able to take the agent down.
|
|
164
|
+
emit(`[resource-sample] failed: ${err instanceof Error ? err.message : String(err)}`)
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const timer = setInterval(tick, intervalMs)
|
|
169
|
+
timer.unref?.()
|
|
170
|
+
return () => clearInterval(timer)
|
|
171
|
+
}
|
package/src/sandbox/index.ts
CHANGED
|
@@ -46,7 +46,14 @@ export {
|
|
|
46
46
|
verifyPrivilegedSandboxRuntime,
|
|
47
47
|
type PrivilegedSandboxRuntime,
|
|
48
48
|
} from './privileged-runtime'
|
|
49
|
-
export {
|
|
49
|
+
export {
|
|
50
|
+
ensureSessionTmpDir,
|
|
51
|
+
isUnderTmp,
|
|
52
|
+
mapVirtualTmpPath,
|
|
53
|
+
SESSION_TMP_ROOT,
|
|
54
|
+
enterSubagentTmpScope,
|
|
55
|
+
sessionTmpDir,
|
|
56
|
+
} from './session-tmp'
|
|
50
57
|
export {
|
|
51
58
|
DEPENDENCY_BIN_SANDBOX_DIR,
|
|
52
59
|
DEPENDENCY_BIN_SANDBOX_PATH,
|
|
@@ -15,8 +15,33 @@ const { isAbsolute, join, relative, resolve } = posix
|
|
|
15
15
|
// anything into the project surface.
|
|
16
16
|
export const SESSION_TMP_ROOT = '/tmp/typeclaw-session'
|
|
17
17
|
|
|
18
|
+
// A subagent tree shares one scratch dir: its top-level subagent's. Runtime-
|
|
19
|
+
// owned scratch (a reviewer checkout) is handed to child subagents by `/tmp`
|
|
20
|
+
// path, and a child with its own `/tmp` cannot resolve it. The scope is anchored
|
|
21
|
+
// BELOW the spawning channel/TUI/cron session on purpose: that session persists
|
|
22
|
+
// across turns and speakers, so subagent artifacts must never land in its
|
|
23
|
+
// scratch. Unrelated sessions stay isolated. Each entry is resolved to its
|
|
24
|
+
// anchor at registration, so releasing an intermediate parent never re-routes a
|
|
25
|
+
// still-running grandchild.
|
|
26
|
+
const subagentTmpScopes = new Map<string, { scope: string; refs: number }>()
|
|
27
|
+
|
|
18
28
|
export function sessionTmpDir(sessionId: string): string {
|
|
19
|
-
return join(SESSION_TMP_ROOT, sessionId)
|
|
29
|
+
return join(SESSION_TMP_ROOT, subagentTmpScopes.get(sessionId)?.scope ?? sessionId)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function enterSubagentTmpScope(sessionId: string, parentSessionId: string): () => void {
|
|
33
|
+
const existing = subagentTmpScopes.get(sessionId)
|
|
34
|
+
const scope = existing?.scope ?? subagentTmpScopes.get(parentSessionId)?.scope ?? sessionId
|
|
35
|
+
subagentTmpScopes.set(sessionId, { scope, refs: (existing?.refs ?? 0) + 1 })
|
|
36
|
+
let released = false
|
|
37
|
+
return () => {
|
|
38
|
+
if (released) return
|
|
39
|
+
released = true
|
|
40
|
+
const entry = subagentTmpScopes.get(sessionId)
|
|
41
|
+
if (entry === undefined) return
|
|
42
|
+
if (entry.refs <= 1) subagentTmpScopes.delete(sessionId)
|
|
43
|
+
else entry.refs -= 1
|
|
44
|
+
}
|
|
20
45
|
}
|
|
21
46
|
|
|
22
47
|
export async function ensureSessionTmpDir(sessionId: string): Promise<string> {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { join } from 'node:path'
|
|
2
2
|
|
|
3
|
-
import type {
|
|
3
|
+
import type { CredentialStore } from '@earendil-works/pi-ai'
|
|
4
|
+
import { ModelRuntime } from '@earendil-works/pi-coding-agent'
|
|
4
5
|
|
|
5
6
|
import { createSecretsStoreForAgent } from './storage'
|
|
6
7
|
|
|
@@ -15,9 +16,8 @@ export type ProviderRefreshOutcome = 'valid-or-refreshed' | 'refresh-failed'
|
|
|
15
16
|
export type ProviderRefreshEntry = {
|
|
16
17
|
providerId: string
|
|
17
18
|
outcome: ProviderRefreshOutcome
|
|
18
|
-
//
|
|
19
|
-
//
|
|
20
|
-
// token endpoint, revoked refresh token, unknown OAuth provider).
|
|
19
|
+
// ModelRuntime returns the refresh rejection directly. This field is the
|
|
20
|
+
// operator-visible reason; there is no process-global error queue.
|
|
21
21
|
error?: string
|
|
22
22
|
}
|
|
23
23
|
|
|
@@ -26,103 +26,57 @@ export type RefreshProviderOAuthResult = {
|
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
export type RefreshProviderOAuthOptions = {
|
|
29
|
-
|
|
29
|
+
modelRuntime: ModelRuntime
|
|
30
|
+
credentials: CredentialStore
|
|
30
31
|
log?: (message: string) => void
|
|
31
32
|
}
|
|
32
33
|
|
|
33
|
-
//
|
|
34
|
-
//
|
|
35
|
-
//
|
|
36
|
-
//
|
|
37
|
-
// WHY THIS EXISTS. `AuthStorage.getApiKey()` is the SDK's only refresh trigger,
|
|
38
|
-
// and it is lazy: it fires on the first LLM call for a provider. A container
|
|
39
|
-
// that restarts with an already-expired access token therefore doesn't refresh
|
|
40
|
-
// until a real turn runs — and if that refresh then fails (a wedged network
|
|
41
|
-
// stack, a rotated refresh token), the failure surfaces as a generic
|
|
42
|
-
// provider-error notice posted into a live channel/PR thread. Channel-adapter
|
|
43
|
-
// OAuth already has host-side renewal crons (Kakao/Webex/Teams); provider OAuth
|
|
44
|
-
// had nothing. This closes that gap by paying the refresh cost at boot, where a
|
|
45
|
-
// failure is logged for the operator rather than shown to end users.
|
|
46
|
-
//
|
|
47
|
-
// Reuses the SDK path verbatim rather than re-implementing token refresh: a
|
|
48
|
-
// single `getApiKey()` call per provider runs the exact locked
|
|
49
|
-
// refresh-then-persist-to-secrets.json flow the runtime uses on every turn, so
|
|
50
|
-
// a boot-refreshed token is written back through the same atomic writer and no
|
|
51
|
-
// second refresh implementation can drift from it. `includeFallback: false`
|
|
52
|
-
// keeps an unrelated env var from masking an OAuth refresh failure as success.
|
|
53
|
-
//
|
|
54
|
-
// Never throws: a boot-time credential probe must not block the agent from
|
|
55
|
-
// starting. Each provider is isolated — one provider's failure doesn't stop the
|
|
56
|
-
// others from being probed — and every failure is returned for the caller to
|
|
57
|
-
// log.
|
|
34
|
+
// Container-stage boot probe: ModelRuntime owns signal-aware OAuth refresh and
|
|
35
|
+
// runs it inside CredentialStore.modify, so this shares the exact live-request
|
|
36
|
+
// lock/persist path without reimplementing provider token exchange.
|
|
58
37
|
export async function refreshProviderOAuthCredentials(
|
|
59
38
|
options: RefreshProviderOAuthOptions,
|
|
60
39
|
): Promise<RefreshProviderOAuthResult> {
|
|
61
|
-
const { authStorage } = options
|
|
62
40
|
const entries: ProviderRefreshEntry[] = []
|
|
41
|
+
const credentials = await options.credentials.list()
|
|
63
42
|
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
// Always drain so one provider's recorded error can't leak into the next
|
|
75
|
-
// provider's outcome. drainErrors clears the buffer as it reads.
|
|
76
|
-
const drained = authStorage.drainErrors()
|
|
77
|
-
|
|
78
|
-
if (apiKey !== undefined && apiKey !== '') {
|
|
79
|
-
entries.push({ providerId, outcome: 'valid-or-refreshed' })
|
|
80
|
-
continue
|
|
43
|
+
for (const credential of credentials) {
|
|
44
|
+
if (credential.type !== 'oauth') continue
|
|
45
|
+
try {
|
|
46
|
+
const auth = await options.modelRuntime.getAuth(credential.providerId)
|
|
47
|
+
if (!auth?.auth.apiKey) throw new Error('refresh returned no API key')
|
|
48
|
+
entries.push({ providerId: credential.providerId, outcome: 'valid-or-refreshed' })
|
|
49
|
+
} catch (error) {
|
|
50
|
+
const reason = error instanceof Error ? error.message : String(error)
|
|
51
|
+
options.log?.(`refreshProviderOAuth: ${credential.providerId} refresh failed: ${reason}`)
|
|
52
|
+
entries.push({ providerId: credential.providerId, outcome: 'refresh-failed', error: reason })
|
|
81
53
|
}
|
|
82
|
-
|
|
83
|
-
const error = drained.length > 0 ? drained.map((e) => e.message).join('; ') : 'refresh returned no API key'
|
|
84
|
-
options.log?.(`refreshProviderOAuth: ${providerId} refresh failed: ${error}`)
|
|
85
|
-
entries.push({ providerId, outcome: 'refresh-failed', error })
|
|
86
54
|
}
|
|
87
|
-
|
|
88
55
|
return { entries }
|
|
89
56
|
}
|
|
90
57
|
|
|
91
|
-
// getApiKey already swallows refresh errors into drainErrors and returns
|
|
92
|
-
// undefined, but guard the call itself so an unexpected throw (e.g. a corrupt
|
|
93
|
-
// credential shape the SDK doesn't expect) degrades to a failed entry instead
|
|
94
|
-
// of aborting the whole boot-time sweep.
|
|
95
|
-
async function resolveApiKeySafely(authStorage: AuthStorage, providerId: string): Promise<string | undefined> {
|
|
96
|
-
try {
|
|
97
|
-
return await authStorage.getApiKey(providerId, { includeFallback: false })
|
|
98
|
-
} catch {
|
|
99
|
-
return undefined
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
|
|
103
58
|
export type RefreshProviderOAuthForAgentOptions = {
|
|
104
59
|
agentDir: string
|
|
105
60
|
log?: (message: string) => void
|
|
106
61
|
}
|
|
107
62
|
|
|
108
|
-
//
|
|
109
|
-
//
|
|
110
|
-
//
|
|
111
|
-
// stage uses per provider (createSecretsStoreForAgent) so the refresh writes
|
|
112
|
-
// back through the bind-mounted secrets.json exactly as a live turn would.
|
|
63
|
+
// Container-stage convenience wrapper. Host CLI never calls this path; it
|
|
64
|
+
// reads the bind-mounted v2 envelope and asks ModelRuntime to refresh before
|
|
65
|
+
// the first user turn.
|
|
113
66
|
export async function refreshProviderOAuthForAgent(
|
|
114
67
|
options: RefreshProviderOAuthForAgentOptions,
|
|
115
68
|
): Promise<RefreshProviderOAuthResult> {
|
|
116
|
-
let authStorage: AuthStorage
|
|
117
69
|
try {
|
|
118
|
-
|
|
70
|
+
const credentials = createSecretsStoreForAgent(join(options.agentDir, 'secrets.json'))
|
|
71
|
+
const modelRuntime = await ModelRuntime.create({ credentials, modelsPath: null, refreshOnCreate: false })
|
|
72
|
+
return await refreshProviderOAuthCredentials({
|
|
73
|
+
credentials,
|
|
74
|
+
modelRuntime,
|
|
75
|
+
...(options.log !== undefined ? { log: options.log } : {}),
|
|
76
|
+
})
|
|
119
77
|
} catch (err) {
|
|
120
78
|
const reason = err instanceof Error ? err.message : String(err)
|
|
121
79
|
options.log?.(`refreshProviderOAuth: ${reason}`)
|
|
122
80
|
return { entries: [] }
|
|
123
81
|
}
|
|
124
|
-
return refreshProviderOAuthCredentials({
|
|
125
|
-
authStorage,
|
|
126
|
-
...(options.log !== undefined ? { log: options.log } : {}),
|
|
127
|
-
})
|
|
128
82
|
}
|
package/src/secrets/schema.ts
CHANGED
|
@@ -3,10 +3,9 @@ import { z } from 'zod'
|
|
|
3
3
|
import { secretFieldSchema } from './resolve'
|
|
4
4
|
|
|
5
5
|
// providers.<id> for api-key credentials: the `key` field is a Secret (string
|
|
6
|
-
// shorthand or `{ value?, env? }` object).
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
// are not env-injectable, so they pass through unchanged via catchall.
|
|
6
|
+
// shorthand or `{ value?, env? }` object). CredentialStore resolves this at
|
|
7
|
+
// request time; OAuth credentials carry stateful refresh/access tokens and
|
|
8
|
+
// are never env-injectable.
|
|
10
9
|
const apiKeyProviderSchema = z.object({
|
|
11
10
|
type: z.literal('api_key'),
|
|
12
11
|
key: secretFieldSchema,
|