typeclaw 0.48.0 → 0.48.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.
@@ -1048,25 +1048,13 @@ export const KNOWN_PROVIDERS = {
1048
1048
  // `providerForModelRef()` matches on the registered provider prefix, the same
1049
1049
  // mechanism that already handles the slash-heavy Fireworks router ids.
1050
1050
  //
1051
- // Curation rule (why only six of the ~56 live chat models): every curated
1052
- // entry mirrors a model THIS registry already prices natively, so the numbers
1053
- // below are copied from a sibling entry rather than invented. Models with no
1054
- // in-repo price (google/*, qwen/*) and models whose native reasoning contract
1055
- // is NOT plain OpenAI `reasoning_effort` (deepseek's `thinking:{type}`,
1056
- // z-ai/qwen's `enable_thinking`) are deliberately left out: pi-ai picks
1057
- // thinkingFormat from the baseUrl, and `apis.opengateway.ai` resolves to
1058
- // "openai", so routing those here would silently send the wrong reasoning
1059
- // field. They all remain reachable as custom `opengateway/...` refs — curation
1060
- // only drives the picker, JSON-schema enum, and autocomplete.
1061
- //
1062
- // Costs are UPSTREAM LIST PRICES in USD per 1M tokens, pinned to the sibling
1063
- // entry by a guard test in providers.test.ts. OpenGateway bills upstream usage
1064
- // plus a platform fee and exposes no pricing in /v1/models, so `typeclaw usage`
1065
- // is an estimate that reads LOW against the real invoice. Do NOT "fix" these
1066
- // to zero: zero means "no attributable per-token charge" in this registry
1067
- // (flat-subscription products like the Fireworks Fire Pass router), and
1068
- // OpenGateway is metered. Replace with gateway-billed rates only if
1069
- // OpenGateway ever publishes them.
1051
+ // The live picker gets ids and modalities from OpenGateway's public catalog,
1052
+ // then best-effort joins its rate card. This registry intentionally keeps one
1053
+ // anchor only: `resolveModel()` uses `Object.keys(provider.models)[0]` as the
1054
+ // transport/limits template for every uncurated ref, so entries 2..N buy
1055
+ // nothing. An empty map would make custom refs throw, making one the true
1056
+ // floor. Nano is the cheapest conservative context/limit donor and keeps
1057
+ // `curatedOptions()` useful as the offline fallback.
1070
1058
  //
1071
1059
  // Every model carries an explicit `compat` for the same reason Upstage does:
1072
1060
  // pi-ai auto-detects compatibility from the baseUrl, and `apis.opengateway.ai`
@@ -1077,13 +1065,12 @@ export const KNOWN_PROVIDERS = {
1077
1065
  // defaults it true) — turning it off would break token and cost reporting.
1078
1066
  opengateway: {
1079
1067
  id: 'opengateway',
1080
- name: 'OpenGateway.ai',
1068
+ name: 'OpenGateway',
1081
1069
  baseUrl: 'https://apis.opengateway.ai/v1',
1082
1070
  auth: ['api-key'],
1083
1071
  apiKeyEnv: 'OPENGATEWAY_API_KEY',
1084
1072
  oauthProviderId: null,
1085
1073
  models: {
1086
- // Mirrors openai/gpt-5.4-nano.
1087
1074
  'openai/gpt-5.4-nano': {
1088
1075
  id: 'openai/gpt-5.4-nano',
1089
1076
  name: 'GPT-5.4 nano',
@@ -1099,113 +1086,15 @@ export const KNOWN_PROVIDERS = {
1099
1086
  maxTokensField: 'max_tokens',
1100
1087
  },
1101
1088
  input: ['text', 'image'],
1089
+ // Offline snapshot of OpenGateway's published rate for this model, NOT
1090
+ // the upstream OpenAI list price. Every other model is priced live from
1091
+ // the rate card, so this is the one number that can go stale; it is the
1092
+ // fallback used when the card is unreachable. Re-check it against
1093
+ // https://opengateway.ai/api/model-prices if you touch it.
1102
1094
  cost: { input: 0.2, output: 1.25, cacheRead: 0.02, cacheWrite: 0 },
1103
1095
  contextWindow: 400000,
1104
1096
  maxTokens: 128000,
1105
1097
  },
1106
- // Mirrors openai/gpt-5.5.
1107
- 'openai/gpt-5.5': {
1108
- id: 'openai/gpt-5.5',
1109
- name: 'GPT-5.5',
1110
- api: 'openai-completions',
1111
- provider: 'opengateway',
1112
- baseUrl: 'https://apis.opengateway.ai/v1',
1113
- reasoning: true,
1114
- compat: {
1115
- supportsStore: false,
1116
- supportsDeveloperRole: false,
1117
- supportsReasoningEffort: false,
1118
- supportsStrictMode: false,
1119
- maxTokensField: 'max_tokens',
1120
- },
1121
- input: ['text', 'image'],
1122
- cost: { input: 5, output: 30, cacheRead: 0.5, cacheWrite: 0 },
1123
- contextWindow: 1050000,
1124
- maxTokens: 128000,
1125
- },
1126
- // Mirrors anthropic/claude-sonnet-5. Note the transport differs from the
1127
- // native entry: Anthropic is `anthropic-messages` first-party, but the
1128
- // gateway only speaks OpenAI chat-completions.
1129
- 'anthropic/claude-sonnet-5': {
1130
- id: 'anthropic/claude-sonnet-5',
1131
- name: 'Claude Sonnet 5',
1132
- api: 'openai-completions',
1133
- provider: 'opengateway',
1134
- baseUrl: 'https://apis.opengateway.ai/v1',
1135
- reasoning: true,
1136
- compat: {
1137
- supportsStore: false,
1138
- supportsDeveloperRole: false,
1139
- supportsReasoningEffort: false,
1140
- supportsStrictMode: false,
1141
- maxTokensField: 'max_tokens',
1142
- },
1143
- input: ['text', 'image'],
1144
- cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
1145
- contextWindow: 1000000,
1146
- maxTokens: 128000,
1147
- },
1148
- // Mirrors anthropic/claude-opus-4-8.
1149
- 'anthropic/claude-opus-4-8': {
1150
- id: 'anthropic/claude-opus-4-8',
1151
- name: 'Claude Opus 4.8',
1152
- api: 'openai-completions',
1153
- provider: 'opengateway',
1154
- baseUrl: 'https://apis.opengateway.ai/v1',
1155
- reasoning: true,
1156
- compat: {
1157
- supportsStore: false,
1158
- supportsDeveloperRole: false,
1159
- supportsReasoningEffort: false,
1160
- supportsStrictMode: false,
1161
- maxTokensField: 'max_tokens',
1162
- },
1163
- input: ['text', 'image'],
1164
- cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 },
1165
- contextWindow: 1000000,
1166
- maxTokens: 128000,
1167
- },
1168
- // Mirrors moonshot/kimi-k2.6. The gateway namespaces Moonshot as
1169
- // `moonshotai`, so the id is NOT the native `kimi-k2.6`.
1170
- 'moonshotai/kimi-k2.6': {
1171
- id: 'moonshotai/kimi-k2.6',
1172
- name: 'Kimi K2.6',
1173
- api: 'openai-completions',
1174
- provider: 'opengateway',
1175
- baseUrl: 'https://apis.opengateway.ai/v1',
1176
- reasoning: true,
1177
- compat: {
1178
- supportsStore: false,
1179
- supportsDeveloperRole: false,
1180
- supportsReasoningEffort: false,
1181
- supportsStrictMode: false,
1182
- maxTokensField: 'max_tokens',
1183
- },
1184
- input: ['text', 'image'],
1185
- cost: { input: 0.6, output: 2.5, cacheRead: 0.15, cacheWrite: 0 },
1186
- contextWindow: 256000,
1187
- maxTokens: 64000,
1188
- },
1189
- // Mirrors minimax/MiniMax-M3.
1190
- 'minimax/MiniMax-M3': {
1191
- id: 'minimax/MiniMax-M3',
1192
- name: 'MiniMax M3',
1193
- api: 'openai-completions',
1194
- provider: 'opengateway',
1195
- baseUrl: 'https://apis.opengateway.ai/v1',
1196
- reasoning: true,
1197
- compat: {
1198
- supportsStore: false,
1199
- supportsDeveloperRole: false,
1200
- supportsReasoningEffort: false,
1201
- supportsStrictMode: false,
1202
- maxTokensField: 'max_tokens',
1203
- },
1204
- input: ['text', 'image'],
1205
- cost: { input: 0.3, output: 1.2, cacheRead: 0.06, cacheWrite: 0 },
1206
- contextWindow: 1000000,
1207
- maxTokens: 524288,
1208
- },
1209
1098
  },
1210
1099
  },
1211
1100
  } as const satisfies Record<string, KnownProvider>
@@ -1299,7 +1188,7 @@ export const KNOWN_PROVIDER_VENDORS = {
1299
1188
  // Anthropic should land on the Anthropic row, not the gateway that proxies it.
1300
1189
  opengateway: {
1301
1190
  id: 'opengateway',
1302
- name: 'OpenGateway.ai (multi-vendor gateway)',
1191
+ name: 'OpenGateway',
1303
1192
  providers: ['opengateway'],
1304
1193
  },
1305
1194
  } as const satisfies Record<string, KnownProviderVendor>
@@ -0,0 +1,85 @@
1
+ import { resolve } from 'node:path'
2
+
3
+ import lockfile from 'proper-lockfile'
4
+
5
+ import { agentOperationLockPath, ensureAgentOperationLocksDir } from '@/hostd/paths'
6
+
7
+ import { containerNameFromCwd } from './shared'
8
+
9
+ export type AgentOperation = 'start' | 'stop' | 'restart' | 'line-auth' | 'instagram-auth'
10
+ export type AgentOperationLease = { readonly containerName: string; readonly agentDir: string }
11
+ export type AgentOperationReservation =
12
+ | { ok: true; lease: AgentOperationLease; release: () => Promise<void> }
13
+ | { ok: false; reason: string }
14
+ export type ReserveAgentOperationLock = (input: {
15
+ agentDir: string
16
+ operation: AgentOperation
17
+ }) => Promise<AgentOperationReservation>
18
+ export type AgentOperationLockResult<T> = { ok: true; value: T } | { ok: false; reason: string }
19
+ export type WithAgentOperationLock = <T>(
20
+ input: { agentDir: string; operation: AgentOperation; lease?: AgentOperationLease },
21
+ run: (lease: AgentOperationLease) => Promise<T>,
22
+ ) => Promise<AgentOperationLockResult<T>>
23
+
24
+ export const withAgentOperationLock: WithAgentOperationLock = async (input, run) => {
25
+ const agentDir = resolve(input.agentDir)
26
+ const containerName = containerNameFromCwd(agentDir)
27
+
28
+ if (input.lease !== undefined) {
29
+ if (input.lease.containerName !== containerName || resolve(input.lease.agentDir) !== agentDir) {
30
+ return {
31
+ ok: false,
32
+ reason: `Agent operation lease does not match agent ${containerName} at ${agentDir}.`,
33
+ }
34
+ }
35
+ return { ok: true, value: await run(input.lease) }
36
+ }
37
+
38
+ // Acquisition is deliberately outside the try that runs the operation: an
39
+ // ELOCKED thrown from inside `run` (a nested lifecycle call) must not be
40
+ // reported as contention for THIS lock.
41
+ const reservation = await reserveAgentOperationLock(input)
42
+ if (!reservation.ok) return reservation
43
+
44
+ try {
45
+ return { ok: true, value: await run(reservation.lease) }
46
+ } finally {
47
+ await reservation.release()
48
+ }
49
+ }
50
+
51
+ export const reserveAgentOperationLock: ReserveAgentOperationLock = async (input) => {
52
+ const agentDir = resolve(input.agentDir)
53
+ const containerName = containerNameFromCwd(agentDir)
54
+ const lease = { containerName, agentDir }
55
+ await ensureAgentOperationLocksDir()
56
+ const path = agentOperationLockPath(containerName)
57
+
58
+ let releaseLock: () => Promise<void>
59
+ try {
60
+ // Interactive QR and checkpoint prompts can hold this lease for minutes, so
61
+ // contenders fail after a bounded wait instead of queueing behind a human.
62
+ releaseLock = await lockfile.lock(path, {
63
+ lockfilePath: path,
64
+ realpath: false,
65
+ stale: 30_000,
66
+ retries: { retries: 20, factor: 1, minTimeout: 100, maxTimeout: 100, randomize: false },
67
+ })
68
+ } catch (error) {
69
+ if (errorCode(error) === 'ELOCKED') {
70
+ return {
71
+ ok: false,
72
+ reason: `Another TypeClaw lifecycle or channel-auth operation is already in progress for agent \`${containerName}\`. Wait for it to finish, then retry. If the previous process was killed, the lock is reclaimed within 30 seconds.`,
73
+ }
74
+ }
75
+ throw error
76
+ }
77
+
78
+ return { ok: true, lease, release: async () => await releaseLock().catch(() => {}) }
79
+ }
80
+
81
+ function errorCode(error: unknown): string | undefined {
82
+ return typeof error === 'object' && error !== null && 'code' in error
83
+ ? String((error as { code?: unknown }).code)
84
+ : undefined
85
+ }
@@ -1,4 +1,5 @@
1
1
  import { logs, type LogsOptions, type LogsResult } from './logs'
2
+ import { restart, type RestartOptions, type RestartResult } from './restart'
2
3
  import { containerNameFromCwd, imageTagFromCwd } from './shared'
3
4
  import { shell, type ShellResult } from './shell'
4
5
  import { start, type StartOptions, type StartResult } from './start'
@@ -17,6 +18,7 @@ import { stop, type StopOptions, type StopResult } from './stop'
17
18
  export interface Controller {
18
19
  start(options: StartOptions): Promise<StartResult>
19
20
  stop(options: StopOptions): Promise<StopResult>
21
+ restart(options: RestartOptions): Promise<RestartResult>
20
22
  status(options: StatusOptions): Promise<ContainerStatus>
21
23
  stats(options: StatsOptions): Promise<ContainerStats>
22
24
  logs(options: LogsOptions): Promise<LogsResult>
@@ -31,6 +33,7 @@ export function createLocalDockerController(): Controller {
31
33
  return {
32
34
  start: (options) => start(options),
33
35
  stop: (options) => stop(options),
36
+ restart: (options) => restart(options),
34
37
  status: (options) => status(options),
35
38
  stats: (options) => stats(options),
36
39
  logs: (options) => logs(options),
@@ -53,6 +56,9 @@ export function createNoopController(): Controller {
53
56
  async stop({ cwd }) {
54
57
  return { ok: false, reason: unsupported('stop', cwd) }
55
58
  },
59
+ async restart({ cwd }) {
60
+ return { ok: false, reason: unsupported('restart', cwd) }
61
+ },
56
62
  async status({ cwd }) {
57
63
  return { kind: 'missing', containerName: containerNameFromCwd(cwd), imageTag: imageTagFromCwd(cwd) }
58
64
  },
@@ -54,3 +54,11 @@ export {
54
54
  type StartResult,
55
55
  } from './start'
56
56
  export { planStop, stop, type StopOptions, type StopPlan, type StopResult } from './stop'
57
+ export { restart, type RestartOptions, type RestartResult } from './restart'
58
+ export {
59
+ type AgentOperation,
60
+ type AgentOperationLease,
61
+ type AgentOperationLockResult,
62
+ type WithAgentOperationLock,
63
+ withAgentOperationLock,
64
+ } from './agent-operation-lock'
@@ -0,0 +1,55 @@
1
+ import { type AgentOperationLease, type WithAgentOperationLock, withAgentOperationLock } from './agent-operation-lock'
2
+ import { type CurrentHostDaemon, start, type StartResult } from './start'
3
+ import { stop, type StopResult } from './stop'
4
+
5
+ export type RestartOptions = {
6
+ cwd: string
7
+ preferredHostPort: number
8
+ forceBuild?: boolean
9
+ cliEntry?: string
10
+ reuseCurrentHostDaemon?: boolean
11
+ currentHostDaemon?: CurrentHostDaemon
12
+ onStopped?: (result: Extract<StopResult, { ok: true }>) => void
13
+ operationLock?: WithAgentOperationLock
14
+ operationLease?: AgentOperationLease
15
+ }
16
+
17
+ export type RestartResult =
18
+ | { ok: true; stop: Extract<StopResult, { ok: true }>; start: Extract<StartResult, { ok: true }> }
19
+ | { ok: false; reason: string }
20
+
21
+ export async function restart(options: RestartOptions): Promise<RestartResult> {
22
+ const operationLock = options.operationLock ?? withAgentOperationLock
23
+ try {
24
+ const locked = await operationLock(
25
+ { agentDir: options.cwd, operation: 'restart', lease: options.operationLease },
26
+ async (lease) => await restartWithLease(options, lease, operationLock),
27
+ )
28
+ return locked.ok ? locked.value : { ok: false, reason: locked.reason }
29
+ } catch (error) {
30
+ return { ok: false, reason: error instanceof Error ? error.message : String(error) }
31
+ }
32
+ }
33
+
34
+ async function restartWithLease(
35
+ options: RestartOptions,
36
+ lease: AgentOperationLease,
37
+ operationLock: WithAgentOperationLock,
38
+ ): Promise<RestartResult> {
39
+ const stopped = await stop({ cwd: options.cwd, operationLock, operationLease: lease })
40
+ if (!stopped.ok) return { ok: false, reason: `stop failed: ${stopped.reason}` }
41
+ options.onStopped?.(stopped)
42
+
43
+ const started = await start({
44
+ cwd: options.cwd,
45
+ preferredHostPort: options.preferredHostPort,
46
+ forceBuild: options.forceBuild,
47
+ cliEntry: options.cliEntry,
48
+ reuseCurrentHostDaemon: options.reuseCurrentHostDaemon,
49
+ currentHostDaemon: options.currentHostDaemon,
50
+ operationLock,
51
+ operationLease: lease,
52
+ })
53
+ if (!started.ok) return { ok: false, reason: `start failed: ${started.reason}` }
54
+ return { ok: true, stop: stopped, start: started }
55
+ }
@@ -379,6 +379,11 @@ export function classifyRmStderr(stderr: string): BenignRmKind {
379
379
  return null
380
380
  }
381
381
 
382
+ export function isGenuineMissingContainer(stderr: string): boolean {
383
+ const normalized = stderr.toLowerCase()
384
+ return normalized.includes('no such container') || normalized.includes('no such object')
385
+ }
386
+
382
387
  // Detects Docker's name-conflict response from `docker run --name <X>`:
383
388
  // docker: Error response from daemon: Conflict. The container name
384
389
  // "/<X>" is already in use by container "<id>". You have to remove
@@ -4,6 +4,7 @@ import { cp, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
4
4
  import { tmpdir } from 'node:os'
5
5
  import { isAbsolute, join, relative, resolve } from 'node:path'
6
6
 
7
+ import { migrateAgentMessengerConfigDir, resolveAgentMessengerConfigPolicy } from '@/agent-messenger/config-dir'
7
8
  import { expandMountPath, loadConfigSync, withDefaultPlugins, type Config, type PortForward } from '@/config'
8
9
  import { applyBoundGcConfig } from '@/git/bound-gc-config'
9
10
  import { commitGitignoreWithUntracks, untrackTrulyIgnoredFiles } from '@/git/reconcile-ignored'
@@ -32,6 +33,7 @@ import { linkWindowsDevTypeclaw, resolveBunLinkedPackage, type RunBunLink } from
32
33
  import { isWindows } from '@/shared'
33
34
  import { hostLocaleIsCjk } from '@/shared/host-locale'
34
35
 
36
+ import { type AgentOperationLease, type WithAgentOperationLock, withAgentOperationLock } from './agent-operation-lock'
35
37
  import { archiveContainerLogs, type DockerLogArchiver } from './log-archive'
36
38
  import { CONTAINER_PORT, TUI_TOKEN_LABEL, findFreePort, isPortAllocatedError, resolveTuiToken } from './port'
37
39
  import {
@@ -45,6 +47,7 @@ import {
45
47
  dockerConfigDir,
46
48
  imageTagFromCwd,
47
49
  isContainerNameConflict,
50
+ isGenuineMissingContainer,
48
51
  isMissingDockerCredentialHelper,
49
52
  parseContainerInspectOutput,
50
53
  sanitizeDockerConfigJson,
@@ -176,6 +179,8 @@ export type StartOptions = {
176
179
  // Test seam for the host-stage writable-config preflight.
177
180
  assertConfigWritable?: (cwd: string) => void
178
181
  archiveLogs?: DockerLogArchiver
182
+ operationLock?: WithAgentOperationLock
183
+ operationLease?: AgentOperationLease
179
184
  }
180
185
 
181
186
  export type HostDaemonStatus =
@@ -210,7 +215,20 @@ export type StartResult =
210
215
  }
211
216
  | { ok: false; reason: string }
212
217
 
213
- export async function start({
218
+ export async function start(options: StartOptions): Promise<StartResult> {
219
+ const operationLock = options.operationLock ?? withAgentOperationLock
220
+ try {
221
+ const locked = await operationLock(
222
+ { agentDir: options.cwd, operation: 'start', lease: options.operationLease },
223
+ async () => await runStart(options),
224
+ )
225
+ return locked.ok ? locked.value : { ok: false, reason: locked.reason }
226
+ } catch (error) {
227
+ return { ok: false, reason: error instanceof Error ? error.message : String(error) }
228
+ }
229
+ }
230
+
231
+ async function runStart({
214
232
  cwd,
215
233
  preferredHostPort,
216
234
  forceBuild = false,
@@ -246,7 +264,7 @@ export async function start({
246
264
  // side effects (template writes, .gitignore commits, package.json migration)
247
265
  // that would surprise a user invoking `compose start` against a partially-up
248
266
  // tree.
249
- const state = await inspectContainer(exec, containerName)
267
+ let state = await inspectContainer(exec, containerName)
250
268
 
251
269
  // Bound gc/repack memory even when start() is an already-running no-op below:
252
270
  // the running agent's backup keeps committing, so it must not keep using the
@@ -263,12 +281,44 @@ export async function start({
263
281
  }
264
282
  }
265
283
 
284
+ if (state.kind === 'indeterminate') {
285
+ return {
286
+ ok: false,
287
+ reason: `Docker state could not be determined for container ${containerName}; TypeClaw is refusing to migrate or launch while the container may be live. Resolve Docker access and retry. ${state.reason}`,
288
+ }
289
+ }
290
+
266
291
  if (state.kind === 'present' && state.running) {
267
292
  return await reportAlreadyRunning(exec, cwd, containerName)
268
293
  }
269
294
 
270
295
  assertConfigWritable(cwd)
271
296
 
297
+ const agentMessengerPolicy = resolveAgentMessengerConfigPolicy(cwd)
298
+ state = await inspectContainer(exec, containerName)
299
+ if (state.kind === 'malformed') {
300
+ return {
301
+ ok: false,
302
+ reason: `docker inspect returned malformed container identity/state (${state.reason}); preserving container ${containerName} and its logs.`,
303
+ }
304
+ }
305
+ if (state.kind === 'indeterminate') {
306
+ return {
307
+ ok: false,
308
+ reason: `Docker state could not be determined for container ${containerName}; TypeClaw is refusing to migrate or launch while the container may be live. Resolve Docker access and retry. ${state.reason}`,
309
+ }
310
+ }
311
+ if (state.kind === 'present' && state.running) {
312
+ return {
313
+ ok: false,
314
+ reason: `Container ${containerName} became running during start preflight; refusing to migrate agent-messenger credentials or launch a replacement.`,
315
+ }
316
+ }
317
+ if (agentMessengerPolicy.migrate) {
318
+ const agentMessengerMigration = await migrateAgentMessengerConfigDir(cwd)
319
+ if (!agentMessengerMigration.ok) return { ok: false, reason: agentMessengerMigration.reason }
320
+ }
321
+
272
322
  // TypeClaw owns Dockerfile, .gitignore, and the bun-workspaces shape of
273
323
  // package.json. Refresh them from the current CLI templates on every fresh
274
324
  // start (not just --build) so version drift between the agent folder and
@@ -764,6 +814,10 @@ export async function planStart({
764
814
  if (existsSync(join(cwd, ENV_FILE))) {
765
815
  runArgs.push('--env-file', join(cwd, ENV_FILE))
766
816
  }
817
+ const agentMessengerPolicy = resolveAgentMessengerConfigPolicy(cwd)
818
+ if (agentMessengerPolicy.override === null) {
819
+ runArgs.push('-e', `AGENT_MESSENGER_CONFIG_DIR=${agentMessengerPolicy.containerDir}`)
820
+ }
767
821
 
768
822
  // Propagate the host timezone so cron schedules in typeclaw.json (and
769
823
  // cron.json jobs without an explicit `timezone`) fire at wall-clock times
@@ -1003,10 +1057,22 @@ type InspectedState =
1003
1057
  | { kind: 'missing' }
1004
1058
  | { kind: 'present'; running: boolean; containerId: string }
1005
1059
  | { kind: 'malformed'; reason: string }
1060
+ | { kind: 'indeterminate'; reason: string }
1006
1061
 
1007
1062
  async function inspectContainer(exec: DockerExec, name: string): Promise<InspectedState> {
1008
- const result = await exec(['inspect', '--format', '{{.Id}}|{{.State.Running}}', name])
1009
- if (result.exitCode !== 0) return { kind: 'missing' }
1063
+ let result: DockerExecResult
1064
+ try {
1065
+ result = await exec(['inspect', '--format', '{{.Id}}|{{.State.Running}}', name])
1066
+ } catch (error) {
1067
+ return { kind: 'indeterminate', reason: error instanceof Error ? error.message : String(error) }
1068
+ }
1069
+ if (result.exitCode !== 0) {
1070
+ if (isGenuineMissingContainer(result.stderr)) return { kind: 'missing' }
1071
+ return {
1072
+ kind: 'indeterminate',
1073
+ reason: result.stderr.trim() || `docker inspect exited with code ${result.exitCode}`,
1074
+ }
1075
+ }
1010
1076
  const parsed = parseContainerInspectOutput(result.stdout)
1011
1077
  if (!parsed.ok) return { kind: 'malformed', reason: parsed.reason }
1012
1078
  return { kind: 'present', running: parsed.running, containerId: parsed.containerId }
@@ -1,6 +1,7 @@
1
1
  import { DEFAULT_LOG_RETENTION_DAYS, loadConfigSync } from '@/config'
2
2
  import { isDaemonReachable, send as sendToDaemon } from '@/hostd/client'
3
3
 
4
+ import { type AgentOperationLease, type WithAgentOperationLock, withAgentOperationLock } from './agent-operation-lock'
4
5
  import { archiveContainerLogs, type DockerLogArchiver } from './log-archive'
5
6
  import {
6
7
  classifyRmStderr,
@@ -22,9 +23,24 @@ export type StopOptions = {
22
23
  cwd: string
23
24
  exec?: DockerExec
24
25
  archiveLogs?: DockerLogArchiver
26
+ operationLock?: WithAgentOperationLock
27
+ operationLease?: AgentOperationLease
25
28
  }
26
29
 
27
- export async function stop({
30
+ export async function stop(options: StopOptions): Promise<StopResult> {
31
+ const operationLock = options.operationLock ?? withAgentOperationLock
32
+ try {
33
+ const locked = await operationLock(
34
+ { agentDir: options.cwd, operation: 'stop', lease: options.operationLease },
35
+ async () => await runStop(options),
36
+ )
37
+ return locked.ok ? locked.value : { ok: false, reason: locked.reason }
38
+ } catch (error) {
39
+ return { ok: false, reason: error instanceof Error ? error.message : String(error) }
40
+ }
41
+ }
42
+
43
+ async function runStop({
28
44
  cwd,
29
45
  exec = defaultDockerExec,
30
46
  archiveLogs = archiveContainerLogs,
@@ -527,7 +527,7 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
527
527
  ? await opts.restartPreflight({ containerName: req.containerName, cwd, build: req.build })
528
528
  : null
529
529
  if (preflight) return preflight
530
- const ack = supervisor.scheduleRestart({
530
+ const ack = await supervisor.scheduleRestart({
531
531
  containerName: req.containerName,
532
532
  cwd,
533
533
  build: req.build,
@@ -8,6 +8,7 @@ import { isWindows } from '@/shared'
8
8
  const SOCKET_FILE = 'hostd.sock'
9
9
  const REGISTRATIONS_DIR = 'registrations'
10
10
  const KEYS_DIR = 'keys'
11
+ const AGENT_OPERATION_LOCKS_DIR = 'agent-locks'
11
12
 
12
13
  // Defense-in-depth: containerName arrives from RPC payloads (some of which
13
14
  // originate inside the container). Docker already forbids slashes and most
@@ -67,6 +68,17 @@ export function registrationsDir(): string {
67
68
  return join(runDir(), REGISTRATIONS_DIR)
68
69
  }
69
70
 
71
+ export function agentOperationLocksDir(): string {
72
+ return join(runDir(), AGENT_OPERATION_LOCKS_DIR)
73
+ }
74
+
75
+ export function agentOperationLockPath(containerName: string): string {
76
+ if (!SAFE_NAME.test(containerName)) {
77
+ throw new Error(`invalid container name for agent operation lock: ${JSON.stringify(containerName)}`)
78
+ }
79
+ return join(agentOperationLocksDir(), `${containerName}.lock`)
80
+ }
81
+
70
82
  export function keysDir(): string {
71
83
  return join(homeRoot(), KEYS_DIR)
72
84
  }
@@ -101,3 +113,8 @@ export async function ensureDirs(): Promise<void> {
101
113
  await chmod(keysDir(), 0o700).catch(() => {})
102
114
  await chmod(modelsDir(), 0o700).catch(() => {})
103
115
  }
116
+
117
+ export async function ensureAgentOperationLocksDir(): Promise<void> {
118
+ await mkdir(agentOperationLocksDir(), { recursive: true })
119
+ await chmod(agentOperationLocksDir(), 0o700).catch(() => {})
120
+ }