typeclaw 0.47.2 → 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.
Files changed (129) hide show
  1. package/package.json +1 -1
  2. package/src/agent/index.ts +1 -2
  3. package/src/agent/loop-guard.ts +71 -41
  4. package/src/agent/plugin-tools.ts +234 -58
  5. package/src/agent/system-prompt.ts +1 -1
  6. package/src/agent/turn-runner.ts +12 -2
  7. package/src/agent-messenger/config-dir.ts +131 -0
  8. package/src/agent-messenger/host-config-dir.ts +121 -0
  9. package/src/bundled-plugins/agent-browser/index.ts +0 -38
  10. package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +1 -1
  11. package/src/bundled-plugins/guard/policies/non-workspace-write.ts +16 -1
  12. package/src/bundled-plugins/memory/append-tool.ts +75 -2
  13. package/src/bundled-plugins/memory/frontmatter.ts +13 -2
  14. package/src/bundled-plugins/memory/load-memory.ts +1 -1
  15. package/src/bundled-plugins/memory/memory-logger.ts +5 -1
  16. package/src/bundled-plugins/memory/secret-detector.ts +7 -0
  17. package/src/bundled-plugins/memory/vector/hybrid.ts +3 -1
  18. package/src/bundled-plugins/memory/vector/passages.ts +5 -1
  19. package/src/bundled-plugins/security/index.ts +148 -98
  20. package/src/bundled-plugins/security/policies/private-surface-read.ts +43 -28
  21. package/src/channels/adapters/discord-bot-edit.ts +3 -5
  22. package/src/channels/adapters/discord-bot-reactions.ts +4 -6
  23. package/src/channels/adapters/discord-bot-slash-commands.ts +3 -1
  24. package/src/channels/adapters/discord-bot.ts +20 -23
  25. package/src/channels/adapters/discord-edit.ts +3 -5
  26. package/src/channels/adapters/discord-reactions.ts +4 -6
  27. package/src/channels/adapters/discord.ts +1 -1
  28. package/src/channels/adapters/github/decoy-reviewer.ts +2 -1
  29. package/src/channels/adapters/github/history.ts +2 -1
  30. package/src/channels/adapters/github/inbound.ts +4 -11
  31. package/src/channels/adapters/github/index.ts +6 -9
  32. package/src/channels/adapters/github/outbound.ts +3 -6
  33. package/src/channels/adapters/github/reactions.ts +3 -2
  34. package/src/channels/adapters/github/reconcile-cooldown-store.ts +4 -6
  35. package/src/channels/adapters/github/reconcile-open-prs.ts +5 -4
  36. package/src/channels/adapters/github/recover-failed-deliveries.ts +2 -5
  37. package/src/channels/adapters/github/review-state.ts +3 -2
  38. package/src/channels/adapters/github/review-thread-resolver.ts +3 -2
  39. package/src/channels/adapters/github/webhook-register.ts +5 -8
  40. package/src/channels/adapters/instagram-channel-resolver.ts +3 -5
  41. package/src/channels/adapters/instagram.ts +1 -1
  42. package/src/channels/adapters/kakaotalk-author-resolver.ts +2 -5
  43. package/src/channels/adapters/kakaotalk-channel-resolver.ts +3 -5
  44. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +2 -1
  45. package/src/channels/adapters/kakaotalk-membership.ts +2 -5
  46. package/src/channels/adapters/kakaotalk-typing.ts +1 -1
  47. package/src/channels/adapters/kakaotalk.ts +1 -1
  48. package/src/channels/adapters/line-channel-resolver.ts +3 -5
  49. package/src/channels/adapters/line.ts +1 -1
  50. package/src/channels/adapters/slack-bot-edit.ts +1 -1
  51. package/src/channels/adapters/slack-bot-reactions.ts +4 -6
  52. package/src/channels/adapters/slack-bot.ts +8 -8
  53. package/src/channels/adapters/slack-edit.ts +3 -5
  54. package/src/channels/adapters/slack-reactions.ts +4 -6
  55. package/src/channels/adapters/slack.ts +1 -1
  56. package/src/channels/adapters/teams-edit.ts +2 -5
  57. package/src/channels/adapters/teams.ts +1 -1
  58. package/src/channels/adapters/telegram-bot-edit.ts +4 -7
  59. package/src/channels/adapters/telegram-bot.ts +1 -1
  60. package/src/channels/adapters/webex-bot.ts +1 -1
  61. package/src/channels/adapters/webex-edit.ts +3 -5
  62. package/src/channels/adapters/webex.ts +1 -1
  63. package/src/channels/github-review-claim.ts +89 -4
  64. package/src/channels/github-token-bridge.ts +2 -1
  65. package/src/channels/manager.ts +478 -64
  66. package/src/channels/membership-cache.ts +2 -5
  67. package/src/channels/persistence.ts +3 -6
  68. package/src/channels/reloadable.ts +23 -6
  69. package/src/channels/router.ts +134 -56
  70. package/src/channels/tunnel-bridge.ts +2 -1
  71. package/src/channels/types.ts +6 -3
  72. package/src/cli/channel.ts +15 -16
  73. package/src/cli/hostd.ts +61 -38
  74. package/src/cli/init.ts +21 -7
  75. package/src/cli/model.ts +6 -3
  76. package/src/cli/restart.ts +13 -15
  77. package/src/compose/restart.ts +14 -6
  78. package/src/config/config.ts +10 -0
  79. package/src/config/providers.ts +68 -0
  80. package/src/container/agent-operation-lock.ts +85 -0
  81. package/src/container/controller.ts +6 -0
  82. package/src/container/index.ts +8 -0
  83. package/src/container/restart.ts +55 -0
  84. package/src/container/shared.ts +5 -0
  85. package/src/container/start.ts +70 -4
  86. package/src/container/stop.ts +17 -1
  87. package/src/dependencies/bin-resolver.ts +88 -0
  88. package/src/dependencies/bins.ts +227 -0
  89. package/src/dependencies/index.ts +17 -0
  90. package/src/doctor/checks.ts +2 -0
  91. package/src/doctor/operational-incidents.ts +32 -0
  92. package/src/hostd/credential-rotation-apply.ts +94 -0
  93. package/src/hostd/daemon.ts +1 -1
  94. package/src/hostd/paths.ts +17 -0
  95. package/src/hostd/supervisor.ts +27 -10
  96. package/src/init/dockerfile.ts +6 -5
  97. package/src/init/env-file.ts +42 -18
  98. package/src/init/instagram-auth.ts +55 -31
  99. package/src/init/kakaotalk-auth.ts +1 -5
  100. package/src/init/line-auth.ts +45 -29
  101. package/src/init/models-dev.ts +131 -10
  102. package/src/init/opengateway-catalog.ts +120 -0
  103. package/src/init/validate-api-key.ts +26 -4
  104. package/src/operations/classify-tool-outcome.ts +151 -0
  105. package/src/operations/incidents.ts +274 -0
  106. package/src/operations/index.ts +3 -0
  107. package/src/operations/remediations.ts +41 -0
  108. package/src/reload/client.ts +8 -2
  109. package/src/reload/docker-exec-client.ts +10 -2
  110. package/src/reload/index.ts +1 -1
  111. package/src/reload/recover.ts +5 -3
  112. package/src/reload/registry.ts +5 -5
  113. package/src/reload/types.ts +9 -1
  114. package/src/run/index.ts +5 -0
  115. package/src/sandbox/canonical-secrets.ts +10 -1
  116. package/src/sandbox/dependency-bins.ts +125 -0
  117. package/src/sandbox/hidden-paths.ts +4 -1
  118. package/src/sandbox/index.ts +8 -0
  119. package/src/sandbox/policy.ts +1 -1
  120. package/src/sandbox/privileged-runtime.ts +7 -12
  121. package/src/sandbox/runtime-private.ts +4 -0
  122. package/src/sandbox/writable-zones.ts +4 -4
  123. package/src/server/index.ts +7 -5
  124. package/src/shared/protocol.ts +6 -1
  125. package/src/test-helpers/fake-agent-operation-lock.ts +66 -0
  126. package/typeclaw.schema.json +10 -5
  127. package/src/bundled-plugins/agent-browser/shim-install.ts +0 -179
  128. package/src/bundled-plugins/agent-browser/shim.ts +0 -108
  129. /package/src/channels/{adapters/describe-error.ts → describe-error.ts} +0 -0
package/src/cli/hostd.ts CHANGED
@@ -1,7 +1,18 @@
1
1
  import { defineCommand } from 'citty'
2
2
 
3
3
  import { loadConfigSync, validateConfig, type Config, type ValidateConfigResult } from '@/config'
4
- import { resolveController, type StartOptions, type StartResult, type StopResult } from '@/container'
4
+ import {
5
+ resolveController,
6
+ resolveHostPort,
7
+ resolveTuiToken,
8
+ type RestartOptions,
9
+ type RestartResult,
10
+ } from '@/container'
11
+ import {
12
+ applyCredentialRotation,
13
+ type CredentialRotationApplyResult,
14
+ type RenewableAdapter,
15
+ } from '@/hostd/credential-rotation-apply'
5
16
  import { createCurrentHostDaemonHolder } from '@/hostd/current-host-daemon'
6
17
  import { startDaemon, type DaemonLogEvent, type RestartPreflight } from '@/hostd/daemon'
7
18
  import { createKakaoRenewalManager } from '@/hostd/kakao-renewal-manager'
@@ -11,6 +22,7 @@ import { createTeamsRenewalManager } from '@/hostd/teams-renewal-manager'
11
22
  import { computeSourceVersion, resolveSrcRoot, UNVERSIONED_SENTINEL } from '@/hostd/version'
12
23
  import { createWebexRenewalManager } from '@/hostd/webex-renewal-manager'
13
24
  import { validateRestartDeps, type RestartDepsPreflightResult } from '@/init/restart-deps-preflight'
25
+ import { requestReloadWithFallback } from '@/reload'
14
26
 
15
27
  export const hostdCommand = defineCommand({
16
28
  meta: {
@@ -32,43 +44,43 @@ export const hostdCommand = defineCommand({
32
44
  // they must thread currentHostDaemon themselves to get the in-process
33
45
  // registration path. The daemon populates this holder once booted.
34
46
  const currentHostDaemonHolder = createCurrentHostDaemonHolder()
47
+ // The renewal cron writes a fresh credential to secrets.json, but the
48
+ // running adapter captured the old one in a client closure at start(). It
49
+ // has to be told to pick the new one up; bouncing that single adapter is
50
+ // enough, and leaves the rest of the agent's work untouched.
51
+ const applyRenewedCredential = async (
52
+ adapter: RenewableAdapter,
53
+ { containerName, cwd }: { containerName: string; cwd: string },
54
+ ): Promise<void> => {
55
+ const result = await applyCredentialRotation(
56
+ { containerName, cwd, adapter },
57
+ {
58
+ resolveHostPort,
59
+ resolveTuiToken,
60
+ requestReloadWithFallback,
61
+ restartContainer: async (input) => {
62
+ const currentHostDaemon = await currentHostDaemonHolder.ready()
63
+ return await hostdRestart({ ...input, currentHostDaemon })
64
+ },
65
+ },
66
+ )
67
+ writeLogLine(formatCredentialApply(adapter, containerName, result))
68
+ if (result.kind === 'failed') throw new Error(result.restartError)
69
+ }
70
+
35
71
  const kakaoRenewal = createKakaoRenewalManager({
36
72
  onLog: (event) => writeLogLine(formatLog(event)),
37
- onRenewalOk: async ({ containerName, cwd }) => {
38
- // Restart the container so the in-memory KakaoTalk LOCO client picks
39
- // up the renewed tokens from secrets.json. Without this, the cron
40
- // would write fresh tokens but the running adapter would keep using
41
- // the old token in its closure and still 401 at the ~7-day wall.
42
- const currentHostDaemon = await currentHostDaemonHolder.ready()
43
- const result = await hostdRestart({ containerName, cwd, currentHostDaemon })
44
- if (!result.ok) throw new Error(result.reason)
45
- },
73
+ onRenewalOk: async (input) => await applyRenewedCredential('kakaotalk', input),
46
74
  shouldRenew: ({ cwd }) => kakaoChannelConfigured(cwd),
47
75
  })
48
76
  const webexRenewal = createWebexRenewalManager({
49
77
  onLog: (event) => writeLogLine(formatLog(event)),
50
- onRenewalOk: async ({ containerName, cwd }) => {
51
- // Restart so the in-memory WebexClient picks up the renewed token from
52
- // secrets.json. Without this, the cron writes a fresh token but the
53
- // running adapter keeps the old token in its getToken closure and still
54
- // 401s on every outbound REST call + KMS key fetch.
55
- const currentHostDaemon = await currentHostDaemonHolder.ready()
56
- const result = await hostdRestart({ containerName, cwd, currentHostDaemon })
57
- if (!result.ok) throw new Error(result.reason)
58
- },
78
+ onRenewalOk: async (input) => await applyRenewedCredential('webex', input),
59
79
  shouldRenew: ({ cwd }) => webexChannelConfigured(cwd),
60
80
  })
61
81
  const teamsRenewal = createTeamsRenewalManager({
62
82
  onLog: (event) => writeLogLine(formatLog(event)),
63
- onRenewalOk: async ({ containerName, cwd }) => {
64
- // Restart so the in-memory TeamsClient picks up the renewed token from
65
- // secrets.json. Without this, the cron writes a fresh token but the
66
- // running adapter keeps the old token in its login closure and still
67
- // cannot obtain an id_token for the realtime listener.
68
- const currentHostDaemon = await currentHostDaemonHolder.ready()
69
- const result = await hostdRestart({ containerName, cwd, currentHostDaemon })
70
- if (!result.ok) throw new Error(result.reason)
71
- },
83
+ onRenewalOk: async (input) => await applyRenewedCredential('teams', input),
72
84
  shouldRenew: ({ cwd }) => teamsChannelConfigured(cwd),
73
85
  })
74
86
 
@@ -103,17 +115,15 @@ export const hostdCommand = defineCommand({
103
115
 
104
116
  export type HostdRestartDeps = {
105
117
  validateConfig: (cwd: string) => ValidateConfigResult
106
- stop: (opts: { cwd: string }) => Promise<StopResult>
107
118
  loadConfigSync: (cwd: string) => Config
108
- start: (opts: StartOptions) => Promise<StartResult>
119
+ restart: (opts: RestartOptions) => Promise<RestartResult>
109
120
  }
110
121
 
111
122
  const controller = resolveController()
112
123
  const defaultRestartDeps: HostdRestartDeps = {
113
124
  validateConfig,
114
- stop: (opts) => controller.stop(opts),
115
125
  loadConfigSync,
116
- start: (opts) => controller.start(opts),
126
+ restart: (opts) => controller.restart(opts),
117
127
  }
118
128
 
119
129
  export function buildHostdRestart(
@@ -121,7 +131,7 @@ export function buildHostdRestart(
121
131
  deps: HostdRestartDeps = defaultRestartDeps,
122
132
  daemonVersion?: string,
123
133
  ): SupervisorRestart {
124
- return async ({ containerName, cwd, build = false, currentHostDaemon }) => {
134
+ return async ({ containerName, cwd, build = false, currentHostDaemon, operationLease }) => {
125
135
  const drift = await detectSourceDrift(cliEntry, daemonVersion)
126
136
  if (drift) return { ok: false, reason: drift }
127
137
 
@@ -129,19 +139,17 @@ export function buildHostdRestart(
129
139
  if (!validated.ok) {
130
140
  return { ok: false, reason: `invalid config for ${containerName}: ${validated.reason}` }
131
141
  }
132
- const stopResult = await deps.stop({ cwd })
133
- if (!stopResult.ok) return { ok: false, reason: `stop failed: ${stopResult.reason}` }
134
-
135
142
  const cfg = deps.loadConfigSync(cwd)
136
- const startResult = await deps.start({
143
+ const restartResult = await deps.restart({
137
144
  cwd,
138
145
  preferredHostPort: cfg.port,
139
146
  forceBuild: build,
140
147
  cliEntry,
141
148
  reuseCurrentHostDaemon: true,
149
+ operationLease,
142
150
  ...(currentHostDaemon ? { currentHostDaemon } : {}),
143
151
  })
144
- if (!startResult.ok) return { ok: false, reason: `start failed: ${startResult.reason}` }
152
+ if (!restartResult.ok) return restartResult
145
153
  return { ok: true }
146
154
  }
147
155
  }
@@ -198,6 +206,21 @@ function writeLogLine(msg: string): void {
198
206
  console.log(`${new Date().toISOString()} ${msg}`)
199
207
  }
200
208
 
209
+ function formatCredentialApply(
210
+ adapter: RenewableAdapter,
211
+ containerName: string,
212
+ result: CredentialRotationApplyResult,
213
+ ): string {
214
+ const prefix = `[hostd] ${adapter} renewal`
215
+ if (result.kind === 'reloaded') {
216
+ return `${prefix} applied to ${containerName} via ${result.transport} reload (no container restart)`
217
+ }
218
+ if (result.kind === 'restarted') {
219
+ return `${prefix} fell back to a container restart for ${containerName}: ${result.reloadError}`
220
+ }
221
+ return `${prefix} could not be applied to ${containerName}: ${result.reloadError}; restart also failed: ${result.restartError}`
222
+ }
223
+
201
224
  function formatLog(event: DaemonLogEvent | SupervisorLogEvent): string {
202
225
  switch (event.kind) {
203
226
  case 'daemon-listening':
package/src/cli/init.ts CHANGED
@@ -64,7 +64,12 @@ import {
64
64
  type WizardCheckpointStore,
65
65
  } from '@/init/checkpoint'
66
66
  import { runKakaotalkBootstrap } from '@/init/kakaotalk-auth'
67
- import { customModelMetaFromOption, fetchModelOptions, type ModelOption } from '@/init/models-dev'
67
+ import {
68
+ customModelMetaFromOption,
69
+ fetchModelOptions,
70
+ type FetchModelsResult,
71
+ type ModelOption,
72
+ } from '@/init/models-dev'
68
73
  import { makeOAuthLoginRunner, type OAuthLoginResult } from '@/init/oauth-login'
69
74
  import { detectInitProgress } from '@/init/progress'
70
75
  import { runTeamsBootstrap } from '@/init/teams-auth'
@@ -1223,14 +1228,23 @@ function oauthDiscoveryRef(providerId: KnownProviderId): KnownModelRef {
1223
1228
 
1224
1229
  async function loadCatalog(): Promise<NonNullable<WizardState['catalog']>> {
1225
1230
  const s = spinner()
1226
- s.start('Loading model catalog from models.dev...')
1227
- const { options, source, warning } = await fetchModelOptions()
1228
- if (source === 'curated') {
1229
- s.stop(`Using built-in catalog (models.dev unavailable: ${warning ?? 'unknown'})`)
1231
+ s.start('Loading model catalogs...')
1232
+ const result = await fetchModelOptions()
1233
+ const unavailable = catalogFallbackLabels(result)
1234
+ if (unavailable.length > 0) {
1235
+ s.stop(`Loaded model catalog with fallback for ${unavailable.join(', ')}.`)
1230
1236
  } else {
1231
- s.stop('Loaded model catalog.')
1237
+ s.stop('Loaded model catalogs.')
1232
1238
  }
1233
- return warning !== undefined ? { options, source, warning } : { options, source }
1239
+ return result
1240
+ }
1241
+
1242
+ function catalogFallbackLabels(result: FetchModelsResult): string[] {
1243
+ const labels: string[] = []
1244
+ if (result.sources.modelsDev === 'unavailable') labels.push('native providers')
1245
+ if (result.sources.openGatewayCatalog === 'unavailable') labels.push('OpenGateway models')
1246
+ else if (result.sources.openGatewayPrices === 'unavailable') labels.push('OpenGateway prices')
1247
+ return labels
1234
1248
  }
1235
1249
 
1236
1250
  async function pickVendor(
package/src/cli/model.ts CHANGED
@@ -541,15 +541,18 @@ function describeRef(ref: string): string {
541
541
  }
542
542
 
543
543
  async function printAvailableRefs(): Promise<void> {
544
- const { options, source, warning } = await fetchModelOptions()
544
+ const { options, sources, warnings } = await fetchModelOptions()
545
545
  if (options.length === 0) {
546
546
  console.log(c.dim('No models registered.'))
547
547
  return
548
548
  }
549
549
  console.log(c.dim('Use `typeclaw model set <profile> <ref>` to apply.'))
550
- if (source === 'curated' && warning !== undefined) {
551
- console.log(c.dim(`Using built-in catalog (models.dev unavailable: ${warning}).`))
550
+ if (sources.modelsDev === 'unavailable') console.log(c.dim('Using built-in models for native providers.'))
551
+ if (sources.openGatewayCatalog === 'unavailable') console.log(c.dim('Using the built-in OpenGateway anchor.'))
552
+ else if (sources.openGatewayPrices === 'unavailable') {
553
+ console.log(c.dim('OpenGateway models loaded without live pricing.'))
552
554
  }
555
+ if (warnings.length > 0) console.log(c.dim(`Catalog warnings: ${warnings.join('; ')}`))
553
556
  for (const providerId of Object.keys(KNOWN_PROVIDERS) as KnownProviderId[]) {
554
557
  const providerOptions = options.filter((option) => option.providerId === providerId)
555
558
  if (providerOptions.length === 0) continue
@@ -74,28 +74,26 @@ export const restartCommand = defineCommand({
74
74
 
75
75
  const stopSpin = spinner()
76
76
  stopSpin.start('Stopping container...')
77
- const stopped = await controller.stop({ cwd })
78
- if (!stopped.ok) {
79
- stopSpin.error(stopped.reason)
80
- process.exit(1)
81
- }
82
- stopSpin.stop(stopped.running ? `Stopped ${c.cyan(stopped.containerName)}.` : 'Already stopped.')
83
-
84
- const startSpin = spinner()
85
- startSpin.start('Starting container...')
86
- const started = await controller.start({
77
+ let startSpin: ReturnType<typeof spinner> | undefined
78
+ const restarted = await controller.restart({
87
79
  cwd,
88
80
  preferredHostPort: Number(args.port),
89
81
  forceBuild: args.build,
90
82
  cliEntry: process.argv[1],
83
+ onStopped: (stopped) => {
84
+ stopSpin.stop(stopped.running ? `Stopped ${c.cyan(stopped.containerName)}.` : 'Already stopped.')
85
+ startSpin = spinner()
86
+ startSpin.start('Starting container...')
87
+ },
91
88
  })
92
- if (!started.ok) {
93
- startSpin.error(started.reason)
89
+ if (!restarted.ok) {
90
+ if (startSpin === undefined) stopSpin.error(restarted.reason)
91
+ else startSpin.error(restarted.reason)
94
92
  process.exit(1)
95
93
  }
96
- startSpin.stop('Started.')
94
+ startSpin?.stop('Started.')
97
95
 
98
- reportConfigWarnings(started.dockerfileWarnings)
99
- console.log(renderStartSuccess(started))
96
+ reportConfigWarnings(restarted.start.dockerfileWarnings)
97
+ console.log(renderStartSuccess(restarted.start))
100
98
  },
101
99
  })
@@ -58,12 +58,20 @@ async function runOne(
58
58
  if (!validated.ok) return { name, ok: false, reason: validated.reason }
59
59
  try {
60
60
  const controller = resolveController()
61
- const stopped = await controller.stop({ cwd })
62
- if (!stopped.ok) return { name, ok: false, reason: stopped.reason }
63
- onStopped()
64
- const started = await controller.start({ cwd, preferredHostPort, forceBuild, cliEntry })
65
- if (!started.ok) return { name, ok: false, reason: started.reason }
66
- return { name, ok: true, data: { stop: stopped, start: started }, warnings: validated.warnings }
61
+ const restarted = await controller.restart({
62
+ cwd,
63
+ preferredHostPort,
64
+ forceBuild,
65
+ cliEntry,
66
+ onStopped,
67
+ })
68
+ if (!restarted.ok) return { name, ok: false, reason: restarted.reason }
69
+ return {
70
+ name,
71
+ ok: true,
72
+ data: { stop: restarted.stop, start: restarted.start },
73
+ warnings: validated.warnings,
74
+ }
67
75
  } catch (error) {
68
76
  return { name, ok: false, reason: error instanceof Error ? error.message : String(error) }
69
77
  }
@@ -839,6 +839,16 @@ export function resolveModel(ref: KnownModelRef | ModelRef | string): Model<Know
839
839
  provider: providerId,
840
840
  baseUrl: provider.baseUrl ?? template.baseUrl,
841
841
  api: template.api,
842
+ // Carried from the template for the same reason `api` and `baseUrl` are:
843
+ // it describes the PROVIDER's wire dialect, not the model. pi-ai infers
844
+ // compat from the baseUrl and only recognises first-party hosts, so a
845
+ // custom ref on a provider that pins compat (OpenGateway, Upstage) would
846
+ // otherwise fall back to OpenAI-native defaults and send `store`, the
847
+ // `developer` role, `strict` tool schemas and `max_completion_tokens` to
848
+ // an endpoint that never accepts them. `thinkingLevelMap` is deliberately
849
+ // NOT carried: it varies per model even within one provider, so copying
850
+ // the template's would be a guess.
851
+ ...(template.compat !== undefined ? { compat: template.compat } : {}),
842
852
  name: meta?.name ?? modelId,
843
853
  reasoning: meta?.reasoning ?? false,
844
854
  input: resolveCustomModelInput(meta?.input),
@@ -1036,6 +1036,67 @@ export const KNOWN_PROVIDERS = {
1036
1036
  },
1037
1037
  },
1038
1038
  },
1039
+ // OpenGateway.ai (Sionic AI) — a multi-vendor LLM GATEWAY, not a lab. One
1040
+ // OpenAI-compatible surface (Bearer + /chat/completions) fronts OpenAI,
1041
+ // Anthropic, Google, Moonshot, MiniMax, DeepSeek, Z.AI, xAI, and Qwen, so by
1042
+ // the granularity rule above it is ONE provider id: one endpoint, one wire
1043
+ // transport, one key.
1044
+ //
1045
+ // Model ids are creator-qualified (`openai/gpt-5.5`, not `gpt-5.5`) — the
1046
+ // namespace is mandatory upstream. TypeClaw refs therefore carry two slashes:
1047
+ // `opengateway/anthropic/claude-sonnet-5`. That parses fine because
1048
+ // `providerForModelRef()` matches on the registered provider prefix, the same
1049
+ // mechanism that already handles the slash-heavy Fireworks router ids.
1050
+ //
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.
1058
+ //
1059
+ // Every model carries an explicit `compat` for the same reason Upstage does:
1060
+ // pi-ai auto-detects compatibility from the baseUrl, and `apis.opengateway.ai`
1061
+ // matches none of its known hosts, so it would otherwise assume a first-party
1062
+ // OpenAI endpoint and send `store`, the `developer` role, `strict` tool
1063
+ // schemas, and `max_completion_tokens` to a gateway fronting Anthropic and
1064
+ // Moonshot. `supportsUsageInStreaming` is deliberately left unset (pi-ai
1065
+ // defaults it true) — turning it off would break token and cost reporting.
1066
+ opengateway: {
1067
+ id: 'opengateway',
1068
+ name: 'OpenGateway',
1069
+ baseUrl: 'https://apis.opengateway.ai/v1',
1070
+ auth: ['api-key'],
1071
+ apiKeyEnv: 'OPENGATEWAY_API_KEY',
1072
+ oauthProviderId: null,
1073
+ models: {
1074
+ 'openai/gpt-5.4-nano': {
1075
+ id: 'openai/gpt-5.4-nano',
1076
+ name: 'GPT-5.4 nano',
1077
+ api: 'openai-completions',
1078
+ provider: 'opengateway',
1079
+ baseUrl: 'https://apis.opengateway.ai/v1',
1080
+ reasoning: true,
1081
+ compat: {
1082
+ supportsStore: false,
1083
+ supportsDeveloperRole: false,
1084
+ supportsReasoningEffort: false,
1085
+ supportsStrictMode: false,
1086
+ maxTokensField: 'max_tokens',
1087
+ },
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.
1094
+ cost: { input: 0.2, output: 1.25, cacheRead: 0.02, cacheWrite: 0 },
1095
+ contextWindow: 400000,
1096
+ maxTokens: 128000,
1097
+ },
1098
+ },
1099
+ },
1039
1100
  } as const satisfies Record<string, KnownProvider>
1040
1101
 
1041
1102
  export type KnownProviderId = keyof typeof KNOWN_PROVIDERS
@@ -1123,6 +1184,13 @@ export const KNOWN_PROVIDER_VENDORS = {
1123
1184
  'moonshot-coding': { label: 'Coding Plan', hint: 'Kimi Code subscription' },
1124
1185
  },
1125
1186
  },
1187
+ // Listed last because it is a reseller, not a lab: a user who knows they want
1188
+ // Anthropic should land on the Anthropic row, not the gateway that proxies it.
1189
+ opengateway: {
1190
+ id: 'opengateway',
1191
+ name: 'OpenGateway',
1192
+ providers: ['opengateway'],
1193
+ },
1126
1194
  } as const satisfies Record<string, KnownProviderVendor>
1127
1195
 
1128
1196
  export type KnownProviderVendorId = keyof typeof KNOWN_PROVIDER_VENDORS
@@ -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