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
@@ -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,
@@ -0,0 +1,88 @@
1
+ import { constants } from 'node:fs'
2
+ import { access, realpath } from 'node:fs/promises'
3
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path'
4
+
5
+ export const TRUSTED_BASELINE_BIN_DIRS = ['/usr/local/bin', '/usr/bin', '/bin'] as const
6
+ export const DEPENDENCY_BIN_DENYLIST: ReadonlySet<string> = new Set(['typeclaw'])
7
+
8
+ export type DependencyBinDeclaration = {
9
+ package: string
10
+ bin: string
11
+ entry: string
12
+ workspace?: boolean
13
+ }
14
+
15
+ export type ResolvedDependencyBin =
16
+ | { kind: 'baseline'; declaration: DependencyBinDeclaration; executable: string }
17
+ | { kind: 'package'; declaration: DependencyBinDeclaration; entrypoint: string; containerEntrypoint: string }
18
+ | { kind: 'unavailable'; declaration: DependencyBinDeclaration; reason: string }
19
+ | { kind: 'denied'; declaration: DependencyBinDeclaration; reason: string }
20
+
21
+ export async function resolveDependencyBin(
22
+ agentDir: string,
23
+ declaration: DependencyBinDeclaration,
24
+ baselineDirs: readonly string[] = TRUSTED_BASELINE_BIN_DIRS,
25
+ deniedBins: ReadonlySet<string> = DEPENDENCY_BIN_DENYLIST,
26
+ ): Promise<ResolvedDependencyBin> {
27
+ if (deniedBins.has(declaration.bin)) {
28
+ return { kind: 'denied', declaration, reason: 'bin is denied by runtime policy' }
29
+ }
30
+ for (const dir of baselineDirs) {
31
+ const executable = join(dir, declaration.bin)
32
+ if (await isExecutable(executable)) return { kind: 'baseline', declaration, executable }
33
+ }
34
+
35
+ const agentRoot = await realpath(agentDir).catch(() => undefined)
36
+ const nodeModulesRoot = await realpath(join(agentDir, 'node_modules')).catch(() => undefined)
37
+ const packageRoot = join(agentDir, 'node_modules', ...declaration.package.split('/'))
38
+ const resolvedRoot = await realpath(packageRoot).catch(() => undefined)
39
+ if (agentRoot === undefined || nodeModulesRoot === undefined || resolvedRoot === undefined) {
40
+ return {
41
+ kind: 'unavailable',
42
+ declaration,
43
+ reason: `direct dependency ${declaration.package} is not installed`,
44
+ }
45
+ }
46
+ const resolvedEntry = await realpath(resolve(resolvedRoot, declaration.entry)).catch(() => undefined)
47
+ const packageRootAllowed =
48
+ isInside(nodeModulesRoot, resolvedRoot) || (declaration.workspace === true && isInside(agentRoot, resolvedRoot))
49
+ if (resolvedEntry === undefined || !packageRootAllowed || !isInside(resolvedRoot, resolvedEntry)) {
50
+ return {
51
+ kind: 'unavailable',
52
+ declaration,
53
+ reason: `direct dependency ${declaration.package} bin entry is missing or escapes its package`,
54
+ }
55
+ }
56
+ return {
57
+ kind: 'package',
58
+ declaration,
59
+ entrypoint: resolvedEntry,
60
+ // The agent directory is bound into bwrap at its original absolute path.
61
+ // /bin/sh consumes this path, so keep POSIX separators even in Windows tests;
62
+ // production sandbox execution itself is Linux-only.
63
+ containerEntrypoint: resolvedEntry.split(sep).join('/'),
64
+ }
65
+ }
66
+
67
+ export async function resolveDependencyBins(
68
+ agentDir: string,
69
+ declarations: readonly DependencyBinDeclaration[],
70
+ baselineDirs: readonly string[] = TRUSTED_BASELINE_BIN_DIRS,
71
+ deniedBins: ReadonlySet<string> = DEPENDENCY_BIN_DENYLIST,
72
+ ): Promise<ResolvedDependencyBin[]> {
73
+ return Promise.all(
74
+ declarations.map((declaration) => resolveDependencyBin(agentDir, declaration, baselineDirs, deniedBins)),
75
+ )
76
+ }
77
+
78
+ async function isExecutable(path: string): Promise<boolean> {
79
+ return access(path, constants.X_OK).then(
80
+ () => true,
81
+ () => false,
82
+ )
83
+ }
84
+
85
+ function isInside(parent: string, child: string): boolean {
86
+ const rel = relative(parent, child)
87
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
88
+ }
@@ -0,0 +1,227 @@
1
+ import { readFile, realpath } from 'node:fs/promises'
2
+ import { basename, isAbsolute, join, relative } from 'node:path'
3
+
4
+ import type { PluginLogger, PluginRegistry } from '@/plugin'
5
+
6
+ import {
7
+ DEPENDENCY_BIN_DENYLIST,
8
+ resolveDependencyBins,
9
+ type DependencyBinDeclaration,
10
+ type ResolvedDependencyBin,
11
+ } from './bin-resolver'
12
+
13
+ export { DEPENDENCY_BIN_DENYLIST } from './bin-resolver'
14
+
15
+ export type DependencyBinIssue = {
16
+ package?: string
17
+ message: string
18
+ }
19
+
20
+ export type DependencyBinDiscovery = {
21
+ declarations: DependencyBinDeclaration[]
22
+ issues: DependencyBinIssue[]
23
+ protectedFiles: string[]
24
+ }
25
+
26
+ export type DependencyBinValidation = DependencyBinDiscovery & {
27
+ resolutions: ResolvedDependencyBin[]
28
+ unavailable: Extract<ResolvedDependencyBin, { kind: 'unavailable' }>[]
29
+ }
30
+
31
+ const PACKAGE_PATTERN = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i
32
+ const BIN_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
33
+
34
+ export async function discoverDependencyBins(agentDir: string): Promise<DependencyBinDiscovery> {
35
+ const rootManifestPath = join(agentDir, 'package.json')
36
+ const resolvedRootManifest = await realpath(rootManifestPath).catch(() => undefined)
37
+ const rootManifest = await readManifest(rootManifestPath)
38
+ if (!rootManifest.ok) {
39
+ return {
40
+ declarations: [],
41
+ issues: [{ message: rootManifest.message }],
42
+ protectedFiles: resolvedRootManifest === undefined ? [] : [resolvedRootManifest],
43
+ }
44
+ }
45
+ if (!isRecord(rootManifest.value)) {
46
+ return {
47
+ declarations: [],
48
+ issues: [{ message: 'agent package.json must contain an object' }],
49
+ protectedFiles: [resolvedRootManifest ?? rootManifestPath],
50
+ }
51
+ }
52
+ const dependencies = rootManifest.value.dependencies
53
+ if (dependencies === undefined) {
54
+ return { declarations: [], issues: [], protectedFiles: [resolvedRootManifest ?? rootManifestPath] }
55
+ }
56
+ if (!isRecord(dependencies)) {
57
+ return {
58
+ declarations: [],
59
+ issues: [{ message: 'agent package.json dependencies must be an object' }],
60
+ protectedFiles: [resolvedRootManifest ?? rootManifestPath],
61
+ }
62
+ }
63
+
64
+ const declarations: DependencyBinDeclaration[] = []
65
+ const issues: DependencyBinIssue[] = []
66
+ const protectedFiles = [resolvedRootManifest ?? rootManifestPath]
67
+ const agentRoot = await realpath(agentDir).catch(() => undefined)
68
+ const nodeModulesRoot = await realpath(join(agentDir, 'node_modules')).catch(() => undefined)
69
+ for (const packageName of Object.keys(dependencies).sort()) {
70
+ if (!PACKAGE_PATTERN.test(packageName)) {
71
+ issues.push({ package: packageName, message: 'direct dependency has an unsafe package name' })
72
+ continue
73
+ }
74
+ const workspace =
75
+ typeof dependencies[packageName] === 'string' && dependencies[packageName].startsWith('workspace:')
76
+ const packageRoot = join(agentDir, 'node_modules', ...packageName.split('/'))
77
+ const resolvedRoot = await realpath(packageRoot).catch(() => undefined)
78
+ const packageRootAllowed =
79
+ resolvedRoot !== undefined &&
80
+ ((nodeModulesRoot !== undefined && isInside(nodeModulesRoot, resolvedRoot)) ||
81
+ (workspace && agentRoot !== undefined && isInside(agentRoot, resolvedRoot)))
82
+ if (!packageRootAllowed) {
83
+ issues.push({ package: packageName, message: 'direct dependency is not installed in an allowed agent path' })
84
+ continue
85
+ }
86
+ const packageManifestPath = join(resolvedRoot, 'package.json')
87
+ const packageManifest = await readManifest(packageManifestPath)
88
+ if (!packageManifest.ok) {
89
+ issues.push({ package: packageName, message: packageManifest.message })
90
+ continue
91
+ }
92
+ if (!isRecord(packageManifest.value)) {
93
+ issues.push({ package: packageName, message: 'dependency package.json must contain an object' })
94
+ continue
95
+ }
96
+ const binEntries = packageBinEntries(packageManifest.value, packageName)
97
+ if (binEntries === undefined) continue
98
+ for (const [bin, entry] of binEntries) {
99
+ if (!BIN_PATTERN.test(bin) || typeof entry !== 'string') {
100
+ issues.push({ package: packageName, message: 'dependency package.json#bin contains an unsafe entry' })
101
+ continue
102
+ }
103
+ if (DEPENDENCY_BIN_DENYLIST.has(bin)) continue
104
+ declarations.push({ package: packageName, bin, entry, ...(workspace ? { workspace: true } : {}) })
105
+ }
106
+ }
107
+ const packagesByBin = new Map<string, string[]>()
108
+ for (const declaration of declarations) {
109
+ const packages = packagesByBin.get(declaration.bin) ?? []
110
+ packages.push(declaration.package)
111
+ packagesByBin.set(declaration.bin, packages)
112
+ }
113
+ const ambiguousBins = new Set<string>()
114
+ for (const [bin, packages] of packagesByBin) {
115
+ if (packages.length < 2) continue
116
+ ambiguousBins.add(bin)
117
+ issues.push({
118
+ message: `direct dependencies ${packages.join(', ')} expose duplicate bin ${bin}; no wrapper generated`,
119
+ })
120
+ }
121
+ return {
122
+ declarations: declarations.filter((entry) => !ambiguousBins.has(entry.bin)),
123
+ issues,
124
+ protectedFiles: [...new Set(protectedFiles)],
125
+ }
126
+ }
127
+
128
+ export async function validateDependencyBins(
129
+ agentDir: string,
130
+ baselineDirs?: readonly string[],
131
+ ): Promise<DependencyBinValidation> {
132
+ const discovery = await discoverDependencyBins(agentDir)
133
+ const resolutions = await resolveDependencyBins(
134
+ agentDir,
135
+ discovery.declarations,
136
+ baselineDirs,
137
+ DEPENDENCY_BIN_DENYLIST,
138
+ )
139
+ return {
140
+ ...discovery,
141
+ resolutions,
142
+ unavailable: resolutions.filter(
143
+ (resolution): resolution is Extract<ResolvedDependencyBin, { kind: 'unavailable' }> =>
144
+ resolution.kind === 'unavailable',
145
+ ),
146
+ }
147
+ }
148
+
149
+ export function registerDependencyBinDoctorCheck(
150
+ registry: PluginRegistry,
151
+ agentDir: string,
152
+ logger: PluginLogger,
153
+ ): void {
154
+ registry.doctorChecks.push({
155
+ pluginName: 'typeclaw',
156
+ checkName: 'dependency-bins',
157
+ pluginConfig: undefined,
158
+ logger,
159
+ check: {
160
+ description: 'direct dependency CLI binaries resolve inside the container',
161
+ category: 'runtime',
162
+ async run() {
163
+ const validation = await validateDependencyBins(agentDir)
164
+ const problems = dependencyBinProblemDetails(validation)
165
+ if (problems.length === 0) {
166
+ return { status: 'ok', message: `${validation.declarations.length} direct dependency bin(s) resolvable` }
167
+ }
168
+ return {
169
+ status: 'error',
170
+ message: `${problems.length} dependency bin problem(s)`,
171
+ details: problems,
172
+ fix: {
173
+ description:
174
+ 'On the host stage, run `bun install` in the agent folder and fix malformed dependency manifests, then restart TypeClaw.',
175
+ },
176
+ }
177
+ },
178
+ },
179
+ })
180
+ }
181
+
182
+ export function logDependencyBinProblems(validation: DependencyBinValidation, logger: PluginLogger): void {
183
+ for (const detail of dependencyBinProblemDetails(validation)) logger.warn(`[dependency-bin] ${detail}`)
184
+ }
185
+
186
+ function packageBinEntries(manifest: Record<string, unknown>, packageName: string): [string, unknown][] | undefined {
187
+ if (typeof manifest.bin === 'string') {
188
+ const manifestName = typeof manifest.name === 'string' ? manifest.name : packageName
189
+ return [[basename(manifestName), manifest.bin]]
190
+ }
191
+ return isRecord(manifest.bin) ? Object.entries(manifest.bin) : undefined
192
+ }
193
+
194
+ async function readManifest(path: string): Promise<{ ok: true; value: unknown } | { ok: false; message: string }> {
195
+ let text: string
196
+ try {
197
+ text = await readFile(path, 'utf8')
198
+ } catch {
199
+ return { ok: false, message: 'package.json is missing or unreadable' }
200
+ }
201
+ try {
202
+ return { ok: true, value: JSON.parse(text) }
203
+ } catch {
204
+ return { ok: false, message: 'package.json is malformed' }
205
+ }
206
+ }
207
+
208
+ function dependencyBinProblemDetails(validation: DependencyBinValidation): string[] {
209
+ return [
210
+ ...validation.issues.map((issue) =>
211
+ issue.package === undefined ? issue.message : `direct dependency ${issue.package}: ${issue.message}`,
212
+ ),
213
+ ...validation.unavailable.map(
214
+ (entry) =>
215
+ `direct dependency ${entry.declaration.package}: bin ${entry.declaration.bin} unavailable (${entry.reason})`,
216
+ ),
217
+ ]
218
+ }
219
+
220
+ function isInside(parent: string, child: string): boolean {
221
+ const rel = relative(parent, child)
222
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
223
+ }
224
+
225
+ function isRecord(value: unknown): value is Record<string, unknown> {
226
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
227
+ }
@@ -0,0 +1,17 @@
1
+ export {
2
+ discoverDependencyBins,
3
+ logDependencyBinProblems,
4
+ registerDependencyBinDoctorCheck,
5
+ validateDependencyBins,
6
+ type DependencyBinDiscovery,
7
+ type DependencyBinIssue,
8
+ type DependencyBinValidation,
9
+ } from './bins'
10
+ export {
11
+ DEPENDENCY_BIN_DENYLIST,
12
+ resolveDependencyBin,
13
+ resolveDependencyBins,
14
+ TRUSTED_BASELINE_BIN_DIRS,
15
+ type DependencyBinDeclaration,
16
+ type ResolvedDependencyBin,
17
+ } from './bin-resolver'
@@ -24,6 +24,7 @@ import { detectWsl, isWindows, isWindowsDriveMount, type WslInfo } from '@/share
24
24
 
25
25
  import { buildChannelChecks } from './channel-checks'
26
26
  import { agentFileOwnership, type FileOwnershipDeps } from './file-ownership'
27
+ import { buildOperationalIncidentChecks } from './operational-incidents'
27
28
  import type { DoctorCheck } from './types'
28
29
 
29
30
  export function buildStaticChecks(opts: { dockerExec?: DockerExec } & FileOwnershipDeps = {}): DoctorCheck[] {
@@ -47,6 +48,7 @@ export function buildStaticChecks(opts: { dockerExec?: DockerExec } & FileOwners
47
48
  windowsBindMount(),
48
49
  containerState(dockerExec),
49
50
  containerHostPort(),
51
+ ...buildOperationalIncidentChecks(),
50
52
  ...buildChannelChecks(),
51
53
  ]
52
54
  }
@@ -0,0 +1,32 @@
1
+ import { readIncidentLedger } from '@/operations'
2
+
3
+ import type { DoctorCheck } from './types'
4
+
5
+ export function buildOperationalIncidentChecks(): DoctorCheck[] {
6
+ return [
7
+ {
8
+ name: 'operations.incidents',
9
+ category: 'operations',
10
+ description: 'deterministic operational incidents are resolved',
11
+ applies: (ctx) => ctx.hasAgentFolder,
12
+ async run(ctx) {
13
+ const ledger = await readIncidentLedger(ctx.cwd)
14
+ const unresolved = ledger.incidents.filter((incident) => incident.status === 'unresolved')
15
+ if (unresolved.length === 0) return { status: 'ok', message: 'no unresolved operational incidents' }
16
+ const recurrent = unresolved.filter((incident) => incident.recurrent)
17
+ return {
18
+ status: recurrent.length > 0 ? 'error' : 'warning',
19
+ message:
20
+ recurrent.length > 0
21
+ ? `${recurrent.length} recurrent TypeClaw environment issue(s) require operator repair`
22
+ : `${unresolved.length} unresolved operational incident(s)`,
23
+ details: unresolved.map(
24
+ (incident) =>
25
+ `${incident.fingerprint} count=${incident.count} first=${incident.firstSeenAt} last=${incident.lastSeenAt}`,
26
+ ),
27
+ fix: { description: 'Repair the TypeClaw environment defect, then retry the failed operation.' },
28
+ }
29
+ },
30
+ },
31
+ ]
32
+ }
@@ -0,0 +1,94 @@
1
+ import type { requestReloadWithFallback as RequestReloadWithFallback, ReloadResult } from '@/reload'
2
+
3
+ export type RenewableAdapter = 'kakaotalk' | 'webex' | 'teams'
4
+
5
+ export type CredentialRotationApplyInput = {
6
+ containerName: string
7
+ cwd: string
8
+ adapter: RenewableAdapter
9
+ }
10
+
11
+ export type CredentialRotationApplyDeps = {
12
+ resolveHostPort: (options: { cwd: string }) => Promise<number>
13
+ resolveTuiToken: (options: { cwd: string }) => Promise<string | null>
14
+ requestReloadWithFallback: typeof RequestReloadWithFallback
15
+ restartContainer: (input: { containerName: string; cwd: string }) => Promise<{ ok: boolean; reason?: string }>
16
+ timeoutMs?: number
17
+ }
18
+
19
+ export type CredentialRotationApplyResult =
20
+ | { kind: 'reloaded'; transport: 'host' | 'container-local' }
21
+ | { kind: 'restarted'; reloadError: string }
22
+ | { kind: 'failed'; reloadError: string; restartError: string }
23
+
24
+ const DEFAULT_TIMEOUT_MS = 30_000
25
+
26
+ // Applying a renewed credential used to stop, remove and recreate the whole
27
+ // container, which killed every in-flight session, cron job and subagent on
28
+ // every OTHER channel too. Teams tokens expire every ~6h, so that fired ~4x a
29
+ // day. Bounce just the one adapter over the existing reload transport instead,
30
+ // and keep the container restart only as the fallback for when neither
31
+ // transport can reach the container at all.
32
+ export async function applyCredentialRotation(
33
+ input: CredentialRotationApplyInput,
34
+ deps: CredentialRotationApplyDeps,
35
+ ): Promise<CredentialRotationApplyResult> {
36
+ const reload = await requestAdapterReload(input, deps)
37
+ if (reload.error === null) return { kind: 'reloaded', transport: reload.transport }
38
+
39
+ const restart = await deps.restartContainer({ containerName: input.containerName, cwd: input.cwd })
40
+ if (restart.ok) return { kind: 'restarted', reloadError: reload.error }
41
+ return { kind: 'failed', reloadError: reload.error, restartError: restart.reason ?? 'restart failed' }
42
+ }
43
+
44
+ type AdapterReloadAttempt = { transport: 'host' | 'container-local'; error: string | null }
45
+
46
+ async function requestAdapterReload(
47
+ { cwd, adapter }: CredentialRotationApplyInput,
48
+ deps: CredentialRotationApplyDeps,
49
+ ): Promise<AdapterReloadAttempt> {
50
+ try {
51
+ const port = await deps.resolveHostPort({ cwd })
52
+ const token = await deps.resolveTuiToken({ cwd })
53
+ const url = new URL(`ws://127.0.0.1:${port}`)
54
+ if (token !== null) url.searchParams.set('token', token)
55
+
56
+ const response = await deps.requestReloadWithFallback({
57
+ url: url.toString(),
58
+ cwd,
59
+ token,
60
+ scope: 'channels',
61
+ cause: { kind: 'credential-rotation', adapter },
62
+ timeoutMs: deps.timeoutMs ?? DEFAULT_TIMEOUT_MS,
63
+ })
64
+ return { transport: response.transport, error: describeUnapplied(response.results, adapter) }
65
+ } catch (err) {
66
+ return { transport: 'host', error: err instanceof Error ? err.message : String(err) }
67
+ }
68
+ }
69
+
70
+ // Only `stop-failed` warrants the fallback: the adapter is still live on the
71
+ // superseded credential, so nothing was applied. Every other outcome means the
72
+ // rotation landed or is landing — including `recovery-pending`, where the
73
+ // adapter is already down holding no stale token and supervision is retrying it
74
+ // on backoff. Recreating the container cannot fix a credential the platform
75
+ // rejected, so falling back there would destroy unrelated work for nothing.
76
+ function describeUnapplied(results: ReloadResult[], adapter: RenewableAdapter): string | null {
77
+ const channels = results.find((result) => result.scope === 'channels')
78
+ if (channels === undefined) return 'channels scope missing from reload result'
79
+ if (!channels.ok) return channels.reason
80
+
81
+ const applied = readCredentialApply(channels.details)
82
+ if (applied === null || applied.adapter !== adapter) return `reload did not apply the ${adapter} credential`
83
+ if (applied.outcome === 'stop-failed') return `${adapter} adapter could not be stopped to apply the credential`
84
+ return null
85
+ }
86
+
87
+ function readCredentialApply(details: unknown): { adapter: string; outcome: string } | null {
88
+ if (typeof details !== 'object' || details === null) return null
89
+ const candidate = (details as { credentialApply?: unknown }).credentialApply
90
+ if (typeof candidate !== 'object' || candidate === null) return null
91
+ const { adapter, outcome } = candidate as { adapter?: unknown; outcome?: unknown }
92
+ if (typeof adapter !== 'string' || typeof outcome !== 'string') return null
93
+ return { adapter, outcome }
94
+ }
@@ -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,