typeclaw 0.39.5 → 0.39.7

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/src/run/index.ts CHANGED
@@ -19,7 +19,7 @@ import {
19
19
  type SubagentRegistry,
20
20
  type SubagentShared,
21
21
  } from '@/agent/subagents'
22
- import { clearTodosForOrigin } from '@/agent/todo/continuation-wiring'
22
+ import { clearTodosForOrigin, markRestartAbortPendingForOrigin } from '@/agent/todo/continuation-wiring'
23
23
  import { vectorEnabledFromMemoryConfig } from '@/bundled-plugins/memory/vector/config'
24
24
  import { embed, warmEmbedder } from '@/bundled-plugins/memory/vector/embedder'
25
25
  import { buildStartupVectorIndex } from '@/bundled-plugins/memory/vector/startup'
@@ -80,6 +80,7 @@ import { createTunnelManager, type TunnelManager, type TunnelManagerOptions } fr
80
80
  import { BUNDLED_PLUGINS } from './bundled-plugins'
81
81
  import { buildChannelSessionFactory } from './channel-session-factory'
82
82
  import { installCodexFetchObserver } from './codex-fetch-observer'
83
+ import { installFatalGuard } from './fatal-guard'
83
84
  import { createPluginRuntime, type PluginRuntime, type PluginSubagentEntry } from './plugin-runtime'
84
85
 
85
86
  type BunServer = ReturnType<Server['start']>
@@ -124,19 +125,44 @@ export type StartAgentResult = {
124
125
  stop: () => void | Promise<void>
125
126
  }
126
127
 
127
- export async function startAgent({
128
- port,
129
- attachTui,
130
- initialPrompt,
131
- cwd = process.cwd(),
132
- createTui = createTuiDefault,
133
- loadCron = loadCronDefault,
134
- createSchedulerFor,
135
- sessionFactory = createSessionFactory({ agentDir: cwd }),
136
- stream = createStream(),
137
- createChannelManager: createChannelManagerFor = createChannelManager,
138
- createTunnelManager: createTunnelManagerFor = createTunnelManager,
139
- }: StartAgentOptions): Promise<StartAgentResult> {
128
+ // Thin wrapper that owns ONLY the boot-failure cleanup of process-global
129
+ // installs. `installCodexFetchObserver` and `installFatalGuard` attach
130
+ // process-wide listeners before the fallible boot work; if any boot step throws
131
+ // before `startAgentRuntime` returns, the caller never receives a
132
+ // `StartAgentResult` and can never call `stop()`, so those listeners would
133
+ // strand and double-fire into the next `startAgent`. The runtime hands its
134
+ // disposer back via `onProcessGlobalsInstalled`; on a boot throw we dispose and
135
+ // rethrow, on success ownership transfers to the returned `stop()`. `return
136
+ // await` is load-bearing — without it an async boot rejection would escape this
137
+ // try. Dispose is idempotent, so the success path's `stop()` never double-fires.
138
+ export async function startAgent(options: StartAgentOptions): Promise<StartAgentResult> {
139
+ const captured: { dispose: (() => void) | null } = { dispose: null }
140
+ try {
141
+ return await startAgentRuntime(options, (dispose) => {
142
+ captured.dispose = dispose
143
+ })
144
+ } catch (err) {
145
+ captured.dispose?.()
146
+ throw err
147
+ }
148
+ }
149
+
150
+ async function startAgentRuntime(
151
+ {
152
+ port,
153
+ attachTui,
154
+ initialPrompt,
155
+ cwd = process.cwd(),
156
+ createTui = createTuiDefault,
157
+ loadCron = loadCronDefault,
158
+ createSchedulerFor,
159
+ sessionFactory = createSessionFactory({ agentDir: cwd }),
160
+ stream = createStream(),
161
+ createChannelManager: createChannelManagerFor = createChannelManager,
162
+ createTunnelManager: createTunnelManagerFor = createTunnelManager,
163
+ }: StartAgentOptions,
164
+ onProcessGlobalsInstalled: (dispose: () => void) => void,
165
+ ): Promise<StartAgentResult> {
140
166
  const reloadRegistry = new ReloadRegistry()
141
167
 
142
168
  // Wrap globalThis.fetch BEFORE any plugin/session/manager construction so
@@ -157,6 +183,41 @@ export async function startAgent({
157
183
  const tuiToken = process.env.TYPECLAW_TUI_TOKEN
158
184
  const tuiTokenOpt = tuiToken !== undefined && tuiToken !== '' ? { tuiToken } : {}
159
185
 
186
+ // Install the crash guard FIRST, before any plugin/channel/session
187
+ // construction, so an `unhandledRejection` escaping a channel SDK during boot
188
+ // or steady-state cannot terminate the container. Restart goes through the
189
+ // host daemon only when there is a container to bounce; outside Docker the
190
+ // guard logs and continues degraded (requestContainerRestart returns ok=false
191
+ // when the hostd control endpoint is absent, never throws).
192
+ const fatalGuard = installFatalGuard({
193
+ ...(containerName !== undefined
194
+ ? {
195
+ requestRestart: async (reason: string) => {
196
+ console.warn(`[fatal-guard] requesting container restart: ${reason}`)
197
+ const result = await requestContainerRestart({ containerName })
198
+ return result.ok ? { ok: true } : { ok: false, reason: result.reason }
199
+ },
200
+ }
201
+ : {}),
202
+ onDegrade: (scope, reason) => console.warn(`[fatal-guard] ${scope} degraded: ${reason}`),
203
+ })
204
+
205
+ // Both process-global disposers are surrendered to the wrapper as one unit the
206
+ // instant they exist, so a throw anywhere below detaches them; `stop()` calls
207
+ // the same disposer on the success path.
208
+ let processGlobalsDisposed = false
209
+ const disposeProcessGlobals = (): void => {
210
+ if (processGlobalsDisposed) return
211
+ processGlobalsDisposed = true
212
+ uninstallCodexFetchObserver()
213
+ fatalGuard.dispose()
214
+ // onSigterm is defined later in this scope but only ever invoked after init;
215
+ // removing it here keeps a restarted startAgent() from stacking listeners.
216
+ if (sigtermHandler !== null) process.removeListener('SIGTERM', sigtermHandler)
217
+ }
218
+ let sigtermHandler: (() => void) | null = null
219
+ onProcessGlobalsInstalled(disposeProcessGlobals)
220
+
160
221
  const { config: cwdConfig, pluginConfigs: pluginConfigsByName } = loadConfigBundleSync(cwd)
161
222
  // Vector agents omit the system-prompt `# Memory` section and inject memory
162
223
  // per-turn instead. Derived once here: `memory.vector.enabled` is
@@ -875,20 +936,55 @@ export async function startAgent({
875
936
  const stop = async () => {
876
937
  if (stopped) return
877
938
  stopped = true
878
- scheduler?.stop()
879
- cronConsumer.stop()
880
- subagentConsumer.stop()
881
- server.stop(true)
882
- void disposeMaterializedSkills(pluginRuntime)
883
- tunnelBridge.stop()
884
- subagentCompletionBridge.stop()
885
- prVerdictActivityBridge.stop()
886
- setReviewObserver(null)
887
- await tunnelManager.stop()
888
- await channelManager.stop()
889
- await mcpManager?.closeAll()
890
- uninstallCodexFetchObserver()
939
+ // The crash-guard and codex-observer disposers run in `finally` so an
940
+ // earlier async teardown rejection (tunnel/channel/mcp stop) cannot strand
941
+ // the process-global listeners they removed — a stranded fatal-guard
942
+ // listener would survive into the next `startAgent` and double-fire.
943
+ try {
944
+ scheduler?.stop()
945
+ cronConsumer.stop()
946
+ subagentConsumer.stop()
947
+ server.stop(true)
948
+ void disposeMaterializedSkills(pluginRuntime)
949
+ tunnelBridge.stop()
950
+ subagentCompletionBridge.stop()
951
+ prVerdictActivityBridge.stop()
952
+ setReviewObserver(null)
953
+ await tunnelManager.stop()
954
+ await channelManager.stop()
955
+ await mcpManager?.closeAll()
956
+ } finally {
957
+ disposeProcessGlobals()
958
+ }
959
+ }
960
+
961
+ // Graceful shutdown on host-initiated restart (`typeclaw restart` → docker
962
+ // stop → SIGTERM, ~10s before SIGKILL). Mark every live session's todo scope
963
+ // so the turn this restart aborts does not arm the durable user-abort block —
964
+ // each scope's incomplete todos then auto-continue after the new container
965
+ // boots. Then run best-effort teardown. A hard deadline force-exits well
966
+ // inside Docker's grace window so a hung turn can't get the process SIGKILL'd
967
+ // mid-flush. Only meaningful inside a container; outside Docker SIGTERM is an
968
+ // ordinary stop with nothing to resume.
969
+ const SHUTDOWN_DEADLINE_MS = 8_000
970
+ let shuttingDown = false
971
+ const onSigterm = (): void => {
972
+ if (shuttingDown) return
973
+ shuttingDown = true
974
+ const forceExit = setTimeout(() => process.exit(0), SHUTDOWN_DEADLINE_MS)
975
+ forceExit.unref()
976
+ void (async () => {
977
+ if (containerName !== undefined) {
978
+ await markRestartAbortPendingForOrigin(cwd, { kind: 'tui', sessionId: 'tui' }).catch(() => undefined)
979
+ await channelManager.router.markRestartAbortForAllLive().catch(() => undefined)
980
+ }
981
+ await stop().catch(() => undefined)
982
+ clearTimeout(forceExit)
983
+ process.exit(0)
984
+ })()
891
985
  }
986
+ sigtermHandler = onSigterm
987
+ process.on('SIGTERM', onSigterm)
892
988
 
893
989
  if (!attachTui) {
894
990
  return {
@@ -221,9 +221,15 @@ async function exchangeAuthorizationCode(
221
221
  return toCredentials(token)
222
222
  }
223
223
 
224
- export async function loginXai(callbacks: OAuthLoginCallbacks, fetchImpl: FetchFn = fetch): Promise<OAuthCredentials> {
224
+ type StartCallbackServerFn = (expectedState: string) => Promise<CallbackServer | null>
225
+
226
+ export async function loginXai(
227
+ callbacks: OAuthLoginCallbacks,
228
+ fetchImpl: FetchFn = fetch,
229
+ startServer: StartCallbackServerFn = startCallbackServer,
230
+ ): Promise<OAuthCredentials> {
225
231
  const { verifier, challenge } = await generatePkce()
226
- const server = await startCallbackServer(verifier)
232
+ const server = await startServer(verifier)
227
233
  let code: string | undefined
228
234
  try {
229
235
  const authParams = new URLSearchParams({
@@ -83,6 +83,9 @@ export async function decideRenewal(block: WebexChannelBlock, ctx: WebexRenewalC
83
83
  plaintextPassword = decrypt(account.encryptedPassword, key, {
84
84
  containerName: ctx.containerName,
85
85
  accountId: account.account_id,
86
+ // Must match the AAD `runWebexBootstrap` seals with (init/webex-auth.ts);
87
+ // the default 'kakaotalk-password' never authenticates a webex blob.
88
+ purpose: 'webex-password',
86
89
  })
87
90
  } catch (err) {
88
91
  return classifyDecryptFailure(err, accountId)
@@ -25,6 +25,7 @@ import type { CreateSessionForSubagent } from '@/agent/subagents'
25
25
  import { TODO_CONTINUATION_SOURCE } from '@/agent/todo/continuation'
26
26
  import {
27
27
  armRestartKickForOrigin,
28
+ clearAbortSuppressionForOrigin,
28
29
  extractTurnUsage,
29
30
  recordTurnOutcome,
30
31
  recordTurnStart,
@@ -620,6 +621,13 @@ export function createServer({
620
621
  await armRestartKickForOrigin(agentDir, origin).catch((err) =>
621
622
  logger.error(`[server] ${sessionFileId}: arm restart-kick suppression failed: ${describeErr(err)}`),
622
623
  )
624
+ // The restart may have aborted an in-flight turn, arming the
625
+ // durable user-abort block. This resume IS the restart, so
626
+ // clear it — otherwise the resumed session never auto-continues
627
+ // its incomplete todos. Gated to this restart-handoff path.
628
+ await clearAbortSuppressionForOrigin(agentDir, origin).catch((err) =>
629
+ logger.error(`[server] ${sessionFileId}: clear abort suppression failed: ${describeErr(err)}`),
630
+ )
623
631
  }
624
632
  stream.publish({
625
633
  target: { kind: 'session', sessionId: sessionFileId },