typeclaw 0.35.0 → 0.36.0

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.
@@ -138,6 +138,27 @@ export function _resetRealProcProbeCacheForTests(): void {
138
138
  // future bwrap flag change, would turn this strategy into a secret leak. So we
139
139
  // PROBE it directly before ever selecting it — plant a real secret in a sibling
140
140
  // process's env and assert the sandbox cannot read it back.
141
+ // The probe has THREE outcomes, not two — collapsing them to a boolean is what
142
+ // caused the silent-degrade bug this verdict type fixes. 'safe'/'unsafe' are definitive capability
143
+ // facts (the userns block held / a leak was observed); 'inconclusive' is a
144
+ // transient local failure (probe timeout under CPU/IO contention, sentinel dying
145
+ // mid-probe, a bwrap startup hiccup) that proves NOTHING about the host. A caller
146
+ // deciding the /proc strategy must tell these apart: an inconclusive probe must
147
+ // trigger a RETRY, never a fall-through to tmpfs that breaks the whole bash call
148
+ // on a host that is actually capable. 'unsafe' must still fail closed with no
149
+ // retry. canBindProcSafely() keeps the old boolean shape for callers that only
150
+ // need "is proc-bind selectable right now"; getProcBindSafetyVerdict() exposes
151
+ // the third state for the retry-owning strategy resolver.
152
+ export type ProcBindSafetyVerdict = 'safe' | 'unsafe' | 'inconclusive'
153
+
154
+ // Only DEFINITIVE verdicts are process-global facts worth caching. Caching
155
+ // 'inconclusive' (i.e. its boolean `false`) would PERMANENTLY disable proc-bind
156
+ // for the process — a single slow first bash call would silently break every
157
+ // later bunx until container restart (the exact "works after restart" symptom
158
+ // this whole machinery exists to kill). So the cache type structurally excludes
159
+ // it.
160
+ type CacheableProcBindSafetyVerdict = Exclude<ProcBindSafetyVerdict, 'inconclusive'>
161
+
141
162
  // Keyed by resolved bwrapPath, like ensureBwrapAvailable: the safety answer is a
142
163
  // fact about a SPECIFIC bwrap binary, so a caller pinning a non-default path
143
164
  // (tests, or a future deployment) must re-probe rather than inherit the default
@@ -145,19 +166,21 @@ export function _resetRealProcProbeCacheForTests(): void {
145
166
  // concurrent first callers for one path share a single probe. Both cached
146
167
  // process-globally (the answer is a per-container capability fact). Not abortable
147
168
  // (see canMountRealProc).
148
- const procBindProbeCache = new Map<string, boolean>()
149
- const procBindProbeInFlight = new Map<string, Promise<boolean>>()
150
-
151
- // `safe` is the answer; `cacheable` is false for INCONCLUSIVE outcomes (a probe
152
- // timeout under load, or the sentinel dying mid-probe). Those are transient
153
- // failure modes, not capability facts, so caching their `safe=false` would
154
- // PERMANENTLY disable proc-bind for the process — a single slow first bash call
155
- // would silently break every later bunx until container restart (the exact
156
- // "works after restart" symptom this whole fix exists to kill). Only a probe that
157
- // ran to a verdict (definitively safe OR definitively leaking) is cached.
158
- type ProcBindProbe = { safe: boolean; cacheable: boolean }
169
+ const procBindProbeCache = new Map<string, CacheableProcBindSafetyVerdict>()
170
+ const procBindProbeInFlight = new Map<string, Promise<ProcBindSafetyVerdict>>()
159
171
 
160
- export function canBindProcSafely(options?: { bwrapPath?: string }): Promise<boolean> {
172
+ // `verdict` is the answer; only definitive verdicts are `cacheable`. INCONCLUSIVE
173
+ // outcomes (a probe timeout under load, or the sentinel dying mid-probe) are
174
+ // transient failure modes, not capability facts — see the cache rationale above.
175
+ type ProcBindProbe =
176
+ | { verdict: CacheableProcBindSafetyVerdict; cacheable: true }
177
+ | { verdict: 'inconclusive'; cacheable: false }
178
+
179
+ // The three-state probe, deduped + cached like canBindProcSafely. The strategy
180
+ // resolver (resolveProcStrategy in plugin-tools.ts) consumes this so it can RETRY
181
+ // an 'inconclusive' result before degrading the bash call to tmpfs, while still
182
+ // failing closed on 'unsafe'.
183
+ export function getProcBindSafetyVerdict(options?: { bwrapPath?: string }): Promise<ProcBindSafetyVerdict> {
161
184
  const bwrap = options?.bwrapPath ?? 'bwrap'
162
185
  const cached = procBindProbeCache.get(bwrap)
163
186
  if (cached !== undefined) return Promise.resolve(cached)
@@ -165,9 +188,9 @@ export function canBindProcSafely(options?: { bwrapPath?: string }): Promise<boo
165
188
  if (existing !== undefined) return existing
166
189
 
167
190
  const promise = probeProcBind(bwrap)
168
- .then(({ safe, cacheable }) => {
169
- if (cacheable) procBindProbeCache.set(bwrap, safe)
170
- return safe
191
+ .then(({ verdict, cacheable }) => {
192
+ if (cacheable) procBindProbeCache.set(bwrap, verdict)
193
+ return verdict
171
194
  })
172
195
  .finally(() => {
173
196
  procBindProbeInFlight.delete(bwrap)
@@ -176,9 +199,53 @@ export function canBindProcSafely(options?: { bwrapPath?: string }): Promise<boo
176
199
  return promise
177
200
  }
178
201
 
202
+ // Boolean convenience wrapper: 'safe' is the ONLY verdict that makes proc-bind
203
+ // selectable. 'unsafe' AND 'inconclusive' both map to false — callers that only
204
+ // take a boolean (and do not own a retry budget) must fail closed on either.
205
+ // Derives from the deduped verdict probe, so concurrent callers still share one
206
+ // spawn even though this wrapper's own promise identity differs per call.
207
+ export function canBindProcSafely(options?: { bwrapPath?: string }): Promise<boolean> {
208
+ return getProcBindSafetyVerdict(options).then((verdict) => verdict === 'safe')
209
+ }
210
+
211
+ // Default backoff between proc-bind safety re-probes, in ms. Array length = retry
212
+ // count (2 retries after the initial attempt = 3 probes total). The probe is
213
+ // normally sub-ms; it only returns 'inconclusive' under transient CPU/IO
214
+ // contention (e.g. a boot-time storm of concurrent LLM calls saturating the box
215
+ // and tripping the probe's own timeout), so a short staggered wait lets the spike
216
+ // pass before re-proving.
217
+ export const PROC_BIND_RETRY_BACKOFF_MS = [250, 1_000] as const
218
+
219
+ // proc-bind selection must distinguish "definitely unavailable" from "couldn't
220
+ // verify right now". A DEFINITIVE verdict is final: 'safe'→true; a real userns
221
+ // leak ('unsafe')→false with NO retry. Only an 'inconclusive' verdict (transient
222
+ // probe failure that proves nothing about the host) is retried, because degrading
223
+ // the bash call to tmpfs over a transient hiccup is what silently broke
224
+ // external-package runs on capable hosts. 'inconclusive' is never cached
225
+ // (see the cache type), so each retry re-probes from scratch. After the backoff
226
+ // budget is exhausted we fail CLOSED — an unverified leak-block is never treated
227
+ // as safe. Pure and dependency-injected (probe + sleep) so the retry policy is
228
+ // unit-testable without spawning processes; production passes
229
+ // getProcBindSafetyVerdict and Bun.sleep.
230
+ export async function resolveProcBindSafetyWithRetry(
231
+ probe: () => Promise<ProcBindSafetyVerdict>,
232
+ sleep: (ms: number) => Promise<void>,
233
+ backoffMs: readonly number[] = PROC_BIND_RETRY_BACKOFF_MS,
234
+ ): Promise<boolean> {
235
+ for (let attempt = 0; ; attempt++) {
236
+ const verdict = await probe()
237
+ if (verdict === 'safe') return true
238
+ if (verdict === 'unsafe') return false
239
+
240
+ const backoff = backoffMs[attempt]
241
+ if (backoff === undefined) return false
242
+ await sleep(backoff)
243
+ }
244
+ }
245
+
179
246
  const PROC_BIND_PROBE_SECRET = 'TYPECLAW_PROCBIND_PROBE_SECRET'
180
247
 
181
- const INCONCLUSIVE: ProcBindProbe = { safe: false, cacheable: false }
248
+ const INCONCLUSIVE: ProcBindProbe = { verdict: 'inconclusive', cacheable: false }
182
249
 
183
250
  async function probeProcBind(bwrap: string): Promise<ProcBindProbe> {
184
251
  // The sentinel must model the REAL threat geometry: the agent runtime holds
@@ -277,13 +344,13 @@ async function probeProcBind(bwrap: string): Promise<ProcBindProbe> {
277
344
  // "non-zero" — a non-zero exit also covers script setup failures (a bwrap that
278
345
  // started but couldn't read /proc/self/fd), bwrap startup failures (missing
279
346
  // lib, transient mount EBUSY → bwrap's own exit), and an external SIGKILL.
280
- // Caching any of those transient failures as a definitive safe=false would
347
+ // Caching any of those transient failures as a definitive 'unsafe' would
281
348
  // PERMANENTLY disable proc-bind — the same cache-poisoning class as the
282
349
  // timeout bug. So only the script's two designated codes are cacheable:
283
350
  // PROC_BIND_SAFE (clean run, every open blocked) and PROC_BIND_LEAK (an open
284
351
  // SUCCEEDED — a real leak). Setup failures use PROC_BIND_SETUP_FAILED, and any
285
352
  // other code (bwrap startup, signals, 127) is treated as inconclusive.
286
- if (proc.exitCode === PROC_BIND_LEAK) return { safe: false, cacheable: true }
353
+ if (proc.exitCode === PROC_BIND_LEAK) return { verdict: 'unsafe', cacheable: true }
287
354
  if (proc.exitCode !== PROC_BIND_SAFE) return INCONCLUSIVE
288
355
  // Final liveness: the in-sandbox blocked-open assertions are only meaningful
289
356
  // if the sentinel was alive throughout. Re-read its MARKER from the PARENT —
@@ -293,12 +360,13 @@ async function probeProcBind(bwrap: string): Promise<ProcBindProbe> {
293
360
  // kernel liveness, so this marker re-read is the stronger postcondition. A
294
361
  // failure here means the sentinel vanished mid-probe → inconclusive.
295
362
  if (!(await parentReadsSentinelMarker(sentinelPid))) return INCONCLUSIVE
296
- return { safe: true, cacheable: true }
363
+ return { verdict: 'safe', cacheable: true }
297
364
  } catch {
298
365
  return INCONCLUSIVE
299
366
  } finally {
300
367
  try {
301
368
  sentinel?.kill()
369
+ await sentinel?.exited.catch(() => {})
302
370
  } catch {
303
371
  // killing an already-exited sentinel can throw on some runtimes; cleanup
304
372
  // must never propagate out of the probe.
@@ -4,7 +4,11 @@ export {
4
4
  canBindProcSafely,
5
5
  canMountRealProc,
6
6
  ensureBwrapAvailable,
7
+ getProcBindSafetyVerdict,
8
+ PROC_BIND_RETRY_BACKOFF_MS,
9
+ resolveProcBindSafetyWithRetry,
7
10
  resolveProcSelfExe,
11
+ type ProcBindSafetyVerdict,
8
12
  _resetBwrapAvailabilityCacheForTests,
9
13
  _resetProcBindProbeCacheForTests,
10
14
  _resetRealProcProbeCacheForTests,
@@ -243,6 +243,33 @@ export class SecretsBackend implements AuthStorageBackend {
243
243
  }
244
244
  }
245
245
 
246
+ // Removes `channels.<kind>` from the envelope. Returns `true` when the
247
+ // adapter slot was present and removed, `false` when nothing changed
248
+ // (idempotent on the CLI side — `channel remove discord-bot` twice should
249
+ // not error on the second call). Mirrors `removeProviderCredentialSync`:
250
+ // rewrites the file only when something changed so canonical-shape reads
251
+ // pay zero cost.
252
+ removeChannelSync(kind: string): boolean {
253
+ if (!existsSync(this.secretsPath)) return false
254
+ let release: (() => void) | undefined
255
+ try {
256
+ release = this.acquireSyncLockWithRetry()
257
+ const envelope = this.readEnvelope()
258
+ if (!(kind in envelope.channels)) return false
259
+ const { [kind]: _removed, ...rest } = envelope.channels
260
+ const next: SecretsFile = {
261
+ ...envelope,
262
+ $schema: envelope.$schema ?? SCHEMA_REL,
263
+ version: SECRETS_FILE_VERSION,
264
+ channels: rest,
265
+ }
266
+ this.writeEnvelopeAtomic(next)
267
+ return true
268
+ } finally {
269
+ release?.()
270
+ }
271
+ }
272
+
246
273
  writeChannelsSync(next: Channels): void {
247
274
  this.ensureParentDir()
248
275
  this.ensureFileExists()
@@ -1265,6 +1265,10 @@ function handleInspectMessage(
1265
1265
  ws.close()
1266
1266
  return
1267
1267
  }
1268
+ if (msg.type === 'ping') {
1269
+ sendInspect(ws, { type: 'pong', id: msg.id })
1270
+ return
1271
+ }
1268
1272
  if (msg.type !== 'subscribe' || typeof msg.sessionId !== 'string' || msg.sessionId === '') {
1269
1273
  sendInspect(ws, { type: 'error', message: 'invalid inspect subscription' })
1270
1274
  ws.close()
@@ -1314,7 +1318,7 @@ function handleInspectMessage(
1314
1318
  })
1315
1319
  }
1316
1320
 
1317
- sendInspect(ws, { type: 'subscribed', sessionId: msg.sessionId, sessionLive: live !== undefined })
1321
+ sendInspect(ws, { type: 'subscribed', sessionId: msg.sessionId, sessionLive: live !== undefined, supportsPing: true })
1318
1322
  }
1319
1323
 
1320
1324
  function extractJobId(target: StreamMessage['target']): string {
@@ -44,16 +44,22 @@ export type TunnelLogsServerMessage =
44
44
  | { type: 'error'; message: string }
45
45
  | { type: 'end' }
46
46
 
47
- export type InspectClientMessage = {
48
- type: 'subscribe'
49
- sessionId: string
50
- // sinceMs is a wall-clock cutoff for backfilling broadcasts from the
51
- // in-process Stream ring buffer. The client uses Date.now() - duration;
52
- // omit to skip broadcast backfill. AgentSession events are NEVER
53
- // backfilled (the session's pi-coding-agent subscribe API delivers
54
- // future events only).
55
- sinceMs?: number
56
- }
47
+ export type InspectClientMessage =
48
+ | {
49
+ type: 'subscribe'
50
+ sessionId: string
51
+ // sinceMs is a wall-clock cutoff for backfilling broadcasts from the
52
+ // in-process Stream ring buffer. The client uses Date.now() - duration;
53
+ // omit to skip broadcast backfill. AgentSession events are NEVER
54
+ // backfilled (the session's pi-coding-agent subscribe API delivers
55
+ // future events only).
56
+ sinceMs?: number
57
+ }
58
+ // Steady-state liveness probe echoed back as a pong. A live tail is
59
+ // legitimately quiet for long stretches, so absence of inbound frames cannot
60
+ // distinguish "idle" from "dead"; a missed pong can. Guards a wedged
61
+ // WebSocket that stays ESTABLISHED yet never fires 'close'/'error'.
62
+ | { type: 'ping'; id: number }
57
63
 
58
64
  export type InspectFramePayload =
59
65
  | { kind: 'text_delta'; sessionId: string; delta: string }
@@ -123,9 +129,14 @@ export type InspectFramePayload =
123
129
  }
124
130
 
125
131
  export type InspectServerMessage =
126
- | { type: 'subscribed'; sessionId: string; sessionLive: boolean }
132
+ // supportsPing is the heartbeat capability flag. A pre-heartbeat server omits
133
+ // it; the client must treat its absence as "no ping support" and never send a
134
+ // ping (an old server answers an unknown ping with an error + close, killing
135
+ // the tail). Strict opt-in: only an explicit true arms round-trip probing.
136
+ | { type: 'subscribed'; sessionId: string; sessionLive: boolean; supportsPing?: true }
127
137
  | { type: 'frame'; ts: number; payload: InspectFramePayload }
128
138
  | { type: 'error'; message: string }
139
+ | { type: 'pong'; id: number }
129
140
 
130
141
  export type ClientMessage =
131
142
  | { type: 'prompt'; text: string; delivery?: PromptDelivery }