typeclaw 0.48.8 → 0.48.9

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typeclaw",
3
- "version": "0.48.8",
3
+ "version": "0.48.9",
4
4
  "homepage": "https://github.com/typeclaw/typeclaw#readme",
5
5
  "bugs": {
6
6
  "url": "https://github.com/typeclaw/typeclaw/issues"
@@ -289,6 +289,8 @@ export type SlackBotAdapterOptions = {
289
289
  // tests and ad-hoc adapter constructions stay backwards-compatible.
290
290
  selfAliasesRef?: () => readonly string[]
291
291
  fetchImpl?: typeof fetch
292
+ createClient?: () => SlackBotClient
293
+ createListener?: (client: SlackBotClient, appToken: string) => SlackBotListener
292
294
  }
293
295
 
294
296
  export type SlackBotAdapter = {
@@ -1146,11 +1148,12 @@ function stringField(record: Record<string, unknown>, key: string): string | nul
1146
1148
 
1147
1149
  export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBotAdapter {
1148
1150
  const logger = options.logger ?? consoleLogger
1149
- const client = new SlackBotClient()
1151
+ const client = options.createClient?.() ?? new SlackBotClient()
1150
1152
  const fetchImpl = options.fetchImpl ?? fetch
1151
1153
  let listener: SlackBotListener | null = null
1152
1154
  let botUserId: string | null = null
1153
1155
  let teamId: string | null = null
1156
+ let socketConnected = false
1154
1157
  let started = false
1155
1158
  let inflightInbounds = 0
1156
1159
  let stopWaiters: Array<() => void> = []
@@ -1376,14 +1379,19 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
1376
1379
  throw err
1377
1380
  }
1378
1381
 
1379
- listener = new SlackBotListener(client, { appToken: options.appToken })
1382
+ listener =
1383
+ options.createListener?.(client, options.appToken) ??
1384
+ new SlackBotListener(client, { appToken: options.appToken })
1380
1385
  listener.on('connected', (info) => {
1386
+ socketConnected = started
1381
1387
  logger.info(`[slack-bot] connected (app_id=${info.app_id ?? 'unknown'})`)
1382
1388
  })
1383
1389
  listener.on('disconnected', () => {
1390
+ socketConnected = false
1384
1391
  logger.warn('[slack-bot] disconnected; SDK will reconnect with backoff')
1385
1392
  })
1386
1393
  listener.on('error', (err) => {
1394
+ if (recordValue(err)?.code === 'disconnect_terminal') socketConnected = false
1387
1395
  logger.error(`[slack-bot] socket-mode error: ${describeError(err)}`)
1388
1396
  })
1389
1397
  listener.on('message', ({ ack, event }) => {
@@ -1461,6 +1469,7 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
1461
1469
  listener = null
1462
1470
  botUserId = null
1463
1471
  teamId = null
1472
+ socketConnected = false
1464
1473
  started = false
1465
1474
  logger.error(`[slack-bot] listener start failed: ${describeError(err)}`)
1466
1475
  throw err
@@ -1470,6 +1479,7 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
1470
1479
  async stop(): Promise<void> {
1471
1480
  if (!started) return
1472
1481
  started = false
1482
+ socketConnected = false
1473
1483
  options.router.unregisterOutbound('slack-bot', outboundCallback)
1474
1484
  options.router.unregisterReaction('slack-bot', reactionCallback)
1475
1485
  options.router.unregisterRemoveReaction('slack-bot', removeReactionCallback)
@@ -1495,7 +1505,7 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
1495
1505
  },
1496
1506
 
1497
1507
  isConnected(): boolean {
1498
- return botUserId !== null && teamId !== null
1508
+ return started && socketConnected
1499
1509
  },
1500
1510
  }
1501
1511
  }
@@ -160,6 +160,7 @@ export function createTeamsAdapter(options: TeamsAdapterOptions): TeamsAdapter {
160
160
  let channelTeamMap = new Map<string, string>()
161
161
  let sentEchoes: SentEcho[] = []
162
162
  let started = false
163
+ let realtimeConnected = false
163
164
  let inflightInbounds = 0
164
165
  let stopWaiters: Array<() => void> = []
165
166
 
@@ -270,6 +271,7 @@ export function createTeamsAdapter(options: TeamsAdapterOptions): TeamsAdapter {
270
271
  async start(): Promise<void> {
271
272
  if (started) return
272
273
  started = true
274
+ realtimeConnected = false
273
275
  try {
274
276
  const account = await (options.credentialsStore ?? null)?.getAccount()
275
277
  if (account === null || account === undefined) {
@@ -296,6 +298,7 @@ export function createTeamsAdapter(options: TeamsAdapterOptions): TeamsAdapter {
296
298
  logger.info(`[teams] authenticated as ${self.displayName}, ${chatsById.size} chats`)
297
299
  } catch (err) {
298
300
  started = false
301
+ realtimeConnected = false
299
302
  self = null
300
303
  loadedAccount = null
301
304
  chatsById = new Map()
@@ -327,6 +330,7 @@ export function createTeamsAdapter(options: TeamsAdapterOptions): TeamsAdapter {
327
330
  // just don't get proactively woken by inbound Teams messages.
328
331
  const degradeToRestOnly = (cause: Error): void => {
329
332
  if (listener !== activeListener) return
333
+ realtimeConnected = false
330
334
  listener?.stop()
331
335
  listener = null
332
336
  logger.warn(
@@ -336,10 +340,12 @@ export function createTeamsAdapter(options: TeamsAdapterOptions): TeamsAdapter {
336
340
 
337
341
  listener.on('connected', () => {
338
342
  if (!isActive()) return
343
+ realtimeConnected = true
339
344
  logger.info('[teams] connected')
340
345
  })
341
346
  listener.on('disconnected', () => {
342
347
  if (!isActive()) return
348
+ realtimeConnected = false
343
349
  logger.warn('[teams] disconnected')
344
350
  })
345
351
  // A post-connect `error` for the unrecoverable id_token failure would
@@ -380,6 +386,7 @@ export function createTeamsAdapter(options: TeamsAdapterOptions): TeamsAdapter {
380
386
  async stop(): Promise<void> {
381
387
  if (!started) return
382
388
  started = false
389
+ realtimeConnected = false
383
390
  options.router.unregisterOutbound('teams', outboundCallback)
384
391
  options.router.unregisterSelfIdentity('teams', selfIdentityResolver)
385
392
  options.router.unregisterHistory('teams', historyCallback)
@@ -397,13 +404,8 @@ export function createTeamsAdapter(options: TeamsAdapterOptions): TeamsAdapter {
397
404
  sentEchoes = []
398
405
  },
399
406
 
400
- // REST auth being live is what makes the adapter usable (send/read); the
401
- // realtime listener is a best-effort add-on. Returning true here even in
402
- // REST-only mode is deliberate: the channel manager restarts any adapter
403
- // whose isConnected() is false, which would pointlessly churn a healthy
404
- // REST-only Teams adapter that can never get a realtime listener.
405
407
  isConnected(): boolean {
406
- return started && self !== null
408
+ return started && self !== null && realtimeConnected
407
409
  },
408
410
  }
409
411
  }
@@ -192,6 +192,8 @@ type AdapterEntry = {
192
192
  adapter: AnyAdapter
193
193
  credentialSignature: string
194
194
  disconnectedSinceMs: number | null
195
+ nextRecoveryRestartAtMs: number | null
196
+ recoveryRestartAttempts: number
195
197
  recoveryRestartQueued: boolean
196
198
  }
197
199
 
@@ -512,6 +514,8 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
512
514
  adapter,
513
515
  credentialSignature: signature,
514
516
  disconnectedSinceMs: adapter.isConnected() ? null : recoveryNow(),
517
+ nextRecoveryRestartAtMs: null,
518
+ recoveryRestartAttempts: 0,
515
519
  recoveryRestartQueued: false,
516
520
  })
517
521
  return { status: 'started' }
@@ -722,6 +726,8 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
722
726
  for (const [name, entry] of live) {
723
727
  if (entry.adapter.isConnected()) {
724
728
  entry.disconnectedSinceMs = null
729
+ entry.nextRecoveryRestartAtMs = null
730
+ entry.recoveryRestartAttempts = 0
725
731
  entry.recoveryRestartQueued = false
726
732
  continue
727
733
  }
@@ -731,7 +737,11 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
731
737
  continue
732
738
  }
733
739
  const disconnectedForMs = now - entry.disconnectedSinceMs
734
- if (disconnectedForMs < recoveryDisconnectedGraceMs || entry.recoveryRestartQueued) continue
740
+ const nextRestartAtMs = Math.max(
741
+ entry.disconnectedSinceMs + recoveryDisconnectedGraceMs,
742
+ entry.nextRecoveryRestartAtMs ?? Number.NEGATIVE_INFINITY,
743
+ )
744
+ if (now < nextRestartAtMs || entry.recoveryRestartQueued) continue
735
745
  entry.recoveryRestartQueued = true
736
746
  logger.warn(
737
747
  `[channels] adapter "${name}" disconnected for ${Math.round(disconnectedForMs)}ms; restarting adapter`,
@@ -756,6 +766,12 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
756
766
  return running && queuedEpoch === lifecycleEpoch && cfg !== undefined && cfg.enabled !== false
757
767
  })
758
768
  applyStartResult(name, latestCfg, result)
769
+ const replacement = live.get(name)
770
+ if (replacement !== undefined && !replacement.adapter.isConnected()) {
771
+ const attempts = entry.recoveryRestartAttempts + 1
772
+ replacement.recoveryRestartAttempts = attempts
773
+ replacement.nextRecoveryRestartAtMs = recoveryNow() + retryDelayMs(attempts)
774
+ }
759
775
  } catch (err) {
760
776
  const cfg = options.channelsConfigRef()[name]
761
777
  if (running && queuedEpoch === lifecycleEpoch && cfg !== undefined && cfg.enabled !== false) {
@@ -8,6 +8,7 @@ import {
8
8
  containerNameFromCwd,
9
9
  defaultDockerExec,
10
10
  type DockerExec,
11
+ isGenuineMissingContainer,
11
12
  parseContainerInspectOutput,
12
13
  sanitizeDockerStderr,
13
14
  waitForRemoval,
@@ -58,7 +59,7 @@ async function runStop({
58
59
  // `docker inspect` exits non-zero both when the container does not
59
60
  // exist AND when it exists but is in a transient state docker cannot
60
61
  // inspect (Removal In Progress, Dead, daemon hiccup). Discriminate by
61
- if (inspect.stderr.toLowerCase().includes('no such container')) {
62
+ if (isGenuineMissingContainer(inspect.stderr)) {
62
63
  return { ok: true, containerName, running: false }
63
64
  }
64
65
  return {
@@ -24,10 +24,22 @@ export type SandboxedCommand = {
24
24
  spawnEnv: Record<string, string>
25
25
  }
26
26
 
27
- // Fixed fd the rendered commandString opens to /dev/null for --ro-bind-data
27
+ // First fd the rendered commandString opens to /dev/null for --ro-bind-data
28
28
  // file masks. 3 is the first fd above stdio; the bash tool's spawn does not
29
29
  // inherit it, so the redirect is part of the command string itself.
30
- const MASK_DATA_FD = 3
30
+ //
31
+ // Each masked file gets its OWN fd counting up from here. bwrap copies a
32
+ // --ro-bind-data op's content out of the fd and then close()s it, so a second
33
+ // op naming an already-consumed fd aborts the whole invocation with
34
+ // "Can't write data to file <dest>: Bad file descriptor" — taking every
35
+ // sandboxed bash call down, not just the mask. Upstream defines no reuse
36
+ // semantics for the operand fd (bwrap.xml: "Copy from the file descriptor FD"),
37
+ // and bubblewrap's own demo plus flatpak both allocate a distinct fd per op.
38
+ const FIRST_MASK_DATA_FD = 3
39
+
40
+ function maskDataFd(index: number): number {
41
+ return FIRST_MASK_DATA_FD + index
42
+ }
31
43
 
32
44
  // Pure: no I/O, no bwrap availability probe (that is `ensureBwrapAvailable`'s
33
45
  // job). Given a bash command and a policy, returns the bwrap-wrapped argv plus
@@ -40,8 +52,9 @@ export function buildSandboxedCommand(command: string, policy: SandboxPolicy = {
40
52
  applyCommandFilter(command, policy.commandFilter)
41
53
  }
42
54
  const argv = buildArgv(command, policy)
43
- const needsMaskFd = (policy.masks?.files?.length ?? 0) > 0
44
- const commandString = needsMaskFd ? `${formatCommand(argv)} ${MASK_DATA_FD}</dev/null` : formatCommand(argv)
55
+ const maskRedirects = (policy.masks?.files ?? []).map((_, i) => `${maskDataFd(i)}</dev/null`)
56
+ const commandString =
57
+ maskRedirects.length > 0 ? `${formatCommand(argv)} ${maskRedirects.join(' ')}` : formatCommand(argv)
45
58
  return { argv, commandString, spawnEnv: resolveSpawnEnv(policy.env) }
46
59
  }
47
60
 
@@ -222,9 +235,9 @@ function appendMasks(argv: string[], policy: SandboxPolicy): void {
222
235
  for (const dir of policy.masks?.dirs ?? []) {
223
236
  argv.push('--tmpfs', dir)
224
237
  }
225
- for (const file of policy.masks?.files ?? []) {
226
- argv.push('--ro-bind-data', String(MASK_DATA_FD), file)
227
- }
238
+ ;(policy.masks?.files ?? []).forEach((file, i) => {
239
+ argv.push('--ro-bind-data', String(maskDataFd(i)), file)
240
+ })
228
241
  }
229
242
 
230
243
  function appendWritable(argv: string[], policy: SandboxPolicy): void {
@@ -60,8 +60,11 @@ export type SandboxProcessPolicy = {
60
60
  // bwrap primitive that masks a single FILE (--tmpfs is dir-only). --ro-bind-data
61
61
  // reads its empty content from a file descriptor, and the bash tool spawns with
62
62
  // stdio ["ignore","pipe","pipe"] — no inherited extra fds — so the rendered
63
- // commandString self-opens fd MASK_DATA_FD via a `<fd>< /dev/null` redirection
64
- // appended after `bash -c <command>`. Masks MUST render after the broad parent
63
+ // commandString self-opens ONE fd PER masked file (counting up from
64
+ // FIRST_MASK_DATA_FD) via `<fd></dev/null` redirections appended after
65
+ // `bash -c <command>`. The fds cannot be shared: bwrap close()s each after
66
+ // copying it, so a reused fd aborts the entire invocation with EBADF and kills
67
+ // every sandboxed bash call. Masks MUST render after the broad parent
65
68
  // mounts: bwrap applies mount ops in command-line order and the last op on a
66
69
  // path wins, so a mask emitted before its parent bind would be re-exposed.
67
70
  export type SandboxMaskPolicy = {