typeclaw 0.48.0 → 0.48.2

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 (41) hide show
  1. package/package.json +1 -1
  2. package/src/agent/plugin-tools.ts +68 -9
  3. package/src/agent/system-prompt.ts +8 -0
  4. package/src/agent-messenger/config-dir.ts +131 -0
  5. package/src/agent-messenger/host-config-dir.ts +121 -0
  6. package/src/bundled-plugins/guard/policies/managed-config.ts +7 -20
  7. package/src/bundled-plugins/guard/policies/non-workspace-write.ts +7 -20
  8. package/src/bundled-plugins/guard/policies/skill-authoring.ts +8 -20
  9. package/src/bundled-plugins/memory/README.md +2 -0
  10. package/src/bundled-plugins/memory/dreaming.ts +2 -0
  11. package/src/bundled-plugins/security/policies/private-surface-read.ts +10 -23
  12. package/src/cli/channel.ts +15 -16
  13. package/src/cli/hostd.ts +8 -13
  14. package/src/cli/init.ts +21 -7
  15. package/src/cli/model.ts +6 -3
  16. package/src/cli/restart.ts +13 -15
  17. package/src/compose/restart.ts +14 -6
  18. package/src/config/providers.ts +106 -143
  19. package/src/container/agent-operation-lock.ts +85 -0
  20. package/src/container/controller.ts +6 -0
  21. package/src/container/index.ts +8 -0
  22. package/src/container/restart.ts +55 -0
  23. package/src/container/shared.ts +5 -0
  24. package/src/container/start.ts +112 -4
  25. package/src/container/stop.ts +17 -1
  26. package/src/hostd/daemon.ts +1 -1
  27. package/src/hostd/paths.ts +17 -0
  28. package/src/hostd/supervisor.ts +27 -10
  29. package/src/init/dockerfile.ts +6 -5
  30. package/src/init/env-file.ts +42 -18
  31. package/src/init/instagram-auth.ts +55 -31
  32. package/src/init/kakaotalk-auth.ts +1 -5
  33. package/src/init/line-auth.ts +45 -29
  34. package/src/init/models-dev.ts +114 -7
  35. package/src/init/opengateway-catalog.ts +120 -0
  36. package/src/path-safety/real-intended-path.ts +111 -0
  37. package/src/sandbox/canonical-secrets.ts +10 -1
  38. package/src/sandbox/errors.ts +0 -32
  39. package/src/sandbox/privileged-runtime.ts +8 -94
  40. package/src/test-helpers/fake-agent-operation-lock.ts +66 -0
  41. package/typeclaw.schema.json +10 -30
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typeclaw",
3
- "version": "0.48.0",
3
+ "version": "0.48.2",
4
4
  "homepage": "https://github.com/typeclaw/typeclaw#readme",
5
5
  "bugs": {
6
6
  "url": "https://github.com/typeclaw/typeclaw/issues"
@@ -1,6 +1,6 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks'
2
2
  import { mkdir } from 'node:fs/promises'
3
- import { join } from 'node:path'
3
+ import { join, relative, sep } from 'node:path'
4
4
 
5
5
  import {
6
6
  createBashToolDefinition as piCreateBashToolDefinition,
@@ -633,7 +633,11 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
633
633
  args: attemptArgs,
634
634
  agentDir: opts.agentDir,
635
635
  ...(opts.permissions !== undefined
636
- ? { hidden: resolveHiddenPaths(opts.permissions, liveOrigin, opts.agentDir) }
636
+ ? {
637
+ hidden:
638
+ preparedSandboxRuntime?.withheld.paths ??
639
+ resolveHiddenPaths(opts.permissions, liveOrigin, opts.agentDir),
640
+ }
637
641
  : {}),
638
642
  signal,
639
643
  })
@@ -717,8 +721,18 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
717
721
  }
718
722
  }
719
723
  }
720
- const finalError = executionError ?? cleanupError
724
+ let finalError = executionError ?? cleanupError
721
725
  if (finalError !== undefined) {
726
+ // The builtin reports command failures as execution errors rather than
727
+ // result details. Once the sandbox was prepared, annotate every such
728
+ // error without parsing its arbitrary or localized text. Cleanup-only
729
+ // failures are not command failures and remain unchanged.
730
+ if (executionError !== undefined && preparedSandboxRuntime !== undefined) {
731
+ finalError = appendErrorText(
732
+ finalError,
733
+ renderSandboxPolicyNote(preparedSandboxRuntime.withheld, opts.agentDir),
734
+ )
735
+ }
722
736
  await runToolAfterSafely(opts, tool.name, toolCallId, toErrorResult(finalError))
723
737
  throw finalError
724
738
  }
@@ -734,6 +748,9 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
734
748
  const hint = dependencyBinUnavailableHint(originalBashCommand, preparedSandboxRuntime.dependencyBins)
735
749
  if (hint !== undefined) result = appendTextResult(result, hint)
736
750
  }
751
+ if (preparedSandboxRuntime !== undefined && bashResultHasNonzeroExit(result)) {
752
+ result = appendTextResult(result, renderSandboxPolicyNote(preparedSandboxRuntime.withheld, opts.agentDir))
753
+ }
737
754
  const resolved = loopGate.resolve({ content: result.content as ContentPart[], details: result.details })
738
755
  if ('deferredBlock' in resolved) {
739
756
  fireLoopAbort(opts.getAbort, 'loop_guard:deferred_block')
@@ -801,6 +818,10 @@ type PreparedBashSandbox = {
801
818
  cleanup: () => Promise<void>
802
819
  spawnEnv?: Record<string, string>
803
820
  dependencyBins?: DependencyBinReconciliation
821
+ withheld: {
822
+ paths: { dirs: string[]; files: string[] }
823
+ envNames: string[]
824
+ }
804
825
  }
805
826
 
806
827
  export function buildBashFilesystemPolicy(options: BashFilesystemPolicyOptions) {
@@ -826,9 +847,16 @@ async function applyBashSandbox(
826
847
  boundary: BashSandboxBoundary,
827
848
  ): Promise<PreparedBashSandbox> {
828
849
  const command = mutableArgs.command
829
- if (typeof command !== 'string') return { verify: async () => {}, cleanup: async () => {} }
850
+ if (typeof command !== 'string') {
851
+ return {
852
+ verify: async () => {},
853
+ cleanup: async () => {},
854
+ withheld: { paths: { dirs: [], files: [] }, envNames: [] },
855
+ }
856
+ }
830
857
 
831
858
  const { dirs, files } = resolveHiddenPaths(permissions, origin, agentDir)
859
+ const envNames = resolveExposableBashEnvNames(agentDir)
832
860
  const sandboxEnvOverlay = buildRoleScopedConfigEnv(agentDir, dirs, envOverlay)
833
861
  const maskTargets = await ensureHiddenMaskTargets({ dirs, files })
834
862
  await boundary.ensureAvailable()
@@ -883,9 +911,7 @@ async function applyBashSandbox(
883
911
  cwd: agentDir,
884
912
  proc,
885
913
  procSelfExe: resolveProcSelfExe(),
886
- ...spreadSandboxEnv(
887
- buildSandboxEnvPolicy(sandboxEnvOverlay, privilegedRuntime?.env, resolveExposableBashEnvNames(agentDir)),
888
- ),
914
+ ...spreadSandboxEnv(buildSandboxEnvPolicy(sandboxEnvOverlay, privilegedRuntime?.env, envNames.exposable)),
889
915
  })
890
916
  mutableArgs.command = commandString
891
917
  // The overlay carries command-scoped secret VALUES (e.g. a per-repo GH_TOKEN)
@@ -899,6 +925,7 @@ async function applyBashSandbox(
899
925
  cleanup,
900
926
  spawnEnv: mergedSpawnEnv,
901
927
  dependencyBins,
928
+ withheld: { paths: maskTargets, envNames: envNames.withheld },
902
929
  }
903
930
  } catch (error) {
904
931
  await cleanup()
@@ -913,6 +940,32 @@ function bashResultIsCommandNotFound(result: ToolResult): boolean {
913
940
  )
914
941
  }
915
942
 
943
+ function bashResultHasNonzeroExit(result: ToolResult): boolean {
944
+ // A numeric nonzero exit is the command's tool-agnostic failure signal. Do
945
+ // not infer failure from arbitrary or localized output text.
946
+ return isRecord(result.details) && typeof result.details.exitCode === 'number' && result.details.exitCode !== 0
947
+ }
948
+
949
+ function renderSandboxPolicyNote(withheld: PreparedBashSandbox['withheld'], agentDir: string): string {
950
+ const maskedPaths = [...withheld.paths.dirs, ...withheld.paths.files].map(
951
+ (target) => `agent/${relative(agentDir, target).split(sep).join('/')}`,
952
+ )
953
+ return (
954
+ `[TypeClaw sandbox policy (LOCAL): masked credential/private paths: ${maskedPaths.join(', ') || 'none'}; ` +
955
+ `withheld env names: ${withheld.envNames.join(', ') || 'none'}. This may be unrelated to this failure; ` +
956
+ 'it is NOT evidence about authentication of any account, workspace, or upstream service and must not be ' +
957
+ 'reported as such.]'
958
+ )
959
+ }
960
+
961
+ function appendErrorText(error: unknown, text: string): Error {
962
+ if (error instanceof Error) {
963
+ error.message = `${error.message}\n\n${text}`
964
+ return error
965
+ }
966
+ return new Error(`${String(error)}\n\n${text}`)
967
+ }
968
+
916
969
  function appendTextResult(result: ToolResult, text: string): ToolResult {
917
970
  return { ...result, content: [...(result.content as ContentPart[]), { type: 'text', text }] }
918
971
  }
@@ -962,8 +1015,14 @@ function spreadSandboxEnv(policy: ReturnType<typeof buildSandboxEnvPolicy>): {
962
1015
  return Object.keys(policy).length > 0 ? { env: policy } : {}
963
1016
  }
964
1017
 
965
- function resolveExposableBashEnvNames(agentDir: string): string[] {
966
- return resolveExposableEnvNames(readEnvFile(agentDir))
1018
+ function resolveExposableBashEnvNames(agentDir: string): { exposable: string[]; withheld: string[] } {
1019
+ const declaredEnv = readEnvFile(agentDir)
1020
+ const exposable = resolveExposableEnvNames(declaredEnv)
1021
+ const exposableSet = new Set(exposable)
1022
+ const withheld = [...declaredEnv]
1023
+ .filter(([name, value]) => value.length > 0 && !exposableSet.has(name))
1024
+ .map(([name]) => name)
1025
+ return { exposable, withheld }
967
1026
  }
968
1027
 
969
1028
  function buildRoleScopedConfigEnv(
@@ -67,6 +67,12 @@ When the user asks you to build, run, fix, or verify something, the deliverable
67
67
 
68
68
  If a tool, install, or network call fails and blocks the real path, say so directly and try an alternative (different approach, different package, ask the user). Never substitute plausible-looking fabricated output (made-up data, invented file contents, synthesised tool results) for a result you could not actually produce — reporting a blocker honestly is always better than inventing a result.
69
69
 
70
+ A change is not done because it compiled. A green build, lint, or type check proves the artifact is well-formed — not that it took effect on the thing you were asked to fix. Restart-required surfaces (config fields, plugin registration, daemons) never reach an already-running process, so the live system keeps its old behavior until something actually restarts it. Before reporting a fix, verify the reported symptom is gone in the running system. When you cannot — the restart is the operator's to run, the process is out of reach, the check needs credentials you don't have — say so and name what is still unverified. "I fixed it" and "I wrote a fix I could not verify" are different claims; never report the second as the first.
71
+
72
+ Never say you performed an action you did not perform, and never promise one you cannot perform from where you run. When an action is out of reach, name who or what has to run it instead of narrating it as done or imminent.
73
+
74
+ Separate what a tool returned from why you think it happened. Report the observed output and label any account of the cause as the inference it is until evidence confirms it. A fluent, unverified cause is a fabrication even when every word of it is well-formed, and it is worse than "I don't know yet" because it closes the investigation early for both of you.
75
+
70
76
  ## Parallel tool calls
71
77
 
72
78
  When you need several pieces of information that don't depend on each other, request them in a single response instead of one tool call per turn. Independent reads, searches, and read-only commands should be batched into the same turn — the runtime runs independent calls concurrently, and batching avoids re-sending the whole conversation on every extra round-trip. Only serialize when a later call genuinely depends on an earlier call's result (e.g. read a file before patching it).
@@ -313,6 +319,8 @@ Never echo secrets from \`secrets.json\` or \`.env\`, or any credential you see
313
319
 
314
320
  Never suppress errors to make things "work", and never fabricate results. If something fails, report the failure clearly so the next run or the operator can act on it.
315
321
 
322
+ A green build or lint proves the artifact is well-formed, not that the change took effect — restart-required surfaces (config, plugins) never reach an already-running process. Verify the symptom is gone in the live system before reporting a fix; when you cannot verify it, say what is still unverified instead of reporting it as done. Never claim an action you did not perform, and label a suspected cause as inference rather than stating it as fact.
323
+
316
324
  Do not narrate routine, low-risk tool calls — just call the tool. Do not over-explain what you did unless asked.
317
325
 
318
326
  ${PACKAGE_JSON_INSTALL_RULE}
@@ -0,0 +1,131 @@
1
+ import { lstat, mkdir, readdir, rename, rmdir } from 'node:fs/promises'
2
+ import { dirname, join, posix } from 'node:path'
3
+
4
+ import { readEnvFile } from '@/init/env-file'
5
+
6
+ export const AGENT_MESSENGER_CONFIG_RELATIVE_DIR = 'workspace/.config/agent-messenger'
7
+ export const LEGACY_AGENT_MESSENGER_CONFIG_RELATIVE_DIR = 'workspace/.agent-messenger'
8
+
9
+ const CONTAINER_AGENT_DIR = '/agent'
10
+
11
+ // posix.join, not join: this path is baked into the Dockerfile ENV and the
12
+ // `docker run -e` override, so it must stay `/agent/...` even when the host
13
+ // stage runs on native Windows (where join would emit backslashes).
14
+ export const CONTAINER_AGENT_MESSENGER_CONFIG_DIR = posix.join(CONTAINER_AGENT_DIR, AGENT_MESSENGER_CONFIG_RELATIVE_DIR)
15
+
16
+ export type MigrationResult = { ok: true; migrated: boolean } | { ok: false; reason: string }
17
+
18
+ export type AgentMessengerConfigPolicy = {
19
+ override: string | null
20
+ containerDir: string
21
+ migrate: boolean
22
+ }
23
+
24
+ export function agentMessengerConfigDir(agentDir: string): string {
25
+ return join(agentDir, AGENT_MESSENGER_CONFIG_RELATIVE_DIR)
26
+ }
27
+
28
+ export function legacyAgentMessengerConfigDir(agentDir: string): string {
29
+ return join(agentDir, LEGACY_AGENT_MESSENGER_CONFIG_RELATIVE_DIR)
30
+ }
31
+
32
+ export function resolveAgentMessengerConfigPolicy(agentDir: string): AgentMessengerConfigPolicy {
33
+ const value = readEnvFile(agentDir).get('AGENT_MESSENGER_CONFIG_DIR')
34
+ if (value === undefined || value.length === 0) {
35
+ return { override: null, containerDir: CONTAINER_AGENT_MESSENGER_CONFIG_DIR, migrate: true }
36
+ }
37
+
38
+ const containerDir = posix.resolve(CONTAINER_AGENT_DIR, value)
39
+ return {
40
+ override: value,
41
+ containerDir,
42
+ migrate: containerDir === CONTAINER_AGENT_MESSENGER_CONFIG_DIR,
43
+ }
44
+ }
45
+
46
+ export async function migrateAgentMessengerConfigDir(agentDir: string): Promise<MigrationResult> {
47
+ const legacyDir = legacyAgentMessengerConfigDir(agentDir)
48
+ const configDir = agentMessengerConfigDir(agentDir)
49
+
50
+ const legacy = await inspectDirectory(legacyDir)
51
+ const current = await inspectDirectory(configDir)
52
+ if (legacy.exists && !legacy.directory) return invalidDirectoryResult(legacyDir, legacy.kind)
53
+ if (current.exists && !current.directory) return invalidDirectoryResult(configDir, current.kind)
54
+
55
+ // Validated before the nothing-to-migrate return below: callers use the
56
+ // destination for host-stage credential writes even when no legacy tree
57
+ // exists, and lstat on the leaf follows a symlinked parent. Checking this
58
+ // only on the migrating path would leave the common post-migration state
59
+ // writing E2EE key material through an unvalidated symlink.
60
+ const configParent = await inspectDirectory(dirname(configDir))
61
+ if (configParent.exists && !configParent.directory) {
62
+ return invalidDirectoryResult(dirname(configDir), configParent.kind)
63
+ }
64
+
65
+ if (!legacy.exists) return { ok: true, migrated: false }
66
+
67
+ if (!current.exists) {
68
+ await mkdir(dirname(configDir), { recursive: true })
69
+ return renameForMigration(legacyDir, configDir)
70
+ }
71
+
72
+ if (legacy.empty) {
73
+ await rmdir(legacyDir)
74
+ return { ok: true, migrated: false }
75
+ }
76
+ if (current.empty) {
77
+ await rmdir(configDir)
78
+ return renameForMigration(legacyDir, configDir)
79
+ }
80
+
81
+ return {
82
+ ok: false,
83
+ reason: `Agent-messenger config exists in both ${legacyDir} and ${configDir}. Merge them manually, then remove the legacy directory before starting TypeClaw.`,
84
+ }
85
+ }
86
+
87
+ type DirectoryInspection =
88
+ | { exists: false }
89
+ | { exists: true; directory: false; kind: 'symbolic link' | 'non-directory' }
90
+ | { exists: true; directory: true; empty: boolean }
91
+
92
+ async function inspectDirectory(path: string): Promise<DirectoryInspection> {
93
+ try {
94
+ const entry = await lstat(path)
95
+ if (entry.isSymbolicLink()) return { exists: true, directory: false, kind: 'symbolic link' }
96
+ if (!entry.isDirectory()) return { exists: true, directory: false, kind: 'non-directory' }
97
+ return { exists: true, directory: true, empty: (await readdir(path)).length === 0 }
98
+ } catch (error) {
99
+ if (isErrorCode(error, 'ENOENT')) return { exists: false }
100
+ throw error
101
+ }
102
+ }
103
+
104
+ function invalidDirectoryResult(path: string, kind: 'symbolic link' | 'non-directory'): { ok: false; reason: string } {
105
+ return {
106
+ ok: false,
107
+ reason: `Agent-messenger config path ${path} is a ${kind}; refusing to migrate. Resolve it manually before starting TypeClaw.`,
108
+ }
109
+ }
110
+
111
+ async function renameForMigration(legacyDir: string, configDir: string): Promise<MigrationResult> {
112
+ try {
113
+ await rename(legacyDir, configDir)
114
+ return { ok: true, migrated: true }
115
+ } catch (error) {
116
+ if (isErrorCode(error, 'EXDEV')) {
117
+ return {
118
+ ok: false,
119
+ reason: `Cannot move agent-messenger config from ${legacyDir} to ${configDir} across filesystems. Move it manually before starting TypeClaw; TypeClaw will not copy credential data.`,
120
+ }
121
+ }
122
+ return {
123
+ ok: false,
124
+ reason: `Could not move agent-messenger config from ${legacyDir} to ${configDir}: ${error instanceof Error ? error.message : String(error)}`,
125
+ }
126
+ }
127
+ }
128
+
129
+ function isErrorCode(error: unknown, code: string): boolean {
130
+ return error instanceof Error && 'code' in error && error.code === code
131
+ }
@@ -0,0 +1,121 @@
1
+ import { join, posix } from 'node:path'
2
+
3
+ import type { WithAgentOperationLock } from '@/container/agent-operation-lock'
4
+ import { containerNameFromCwd, defaultDockerExec, type DockerExec, isGenuineMissingContainer } from '@/container/shared'
5
+
6
+ import { migrateAgentMessengerConfigDir, resolveAgentMessengerConfigPolicy } from './config-dir'
7
+
8
+ const CONTAINER_AGENT_DIR = '/agent'
9
+ const CONFIG_ENV_PREFIX = 'AGENT_MESSENGER_CONFIG_DIR='
10
+
11
+ export type HostAgentMessengerConfigResult = { ok: true; hostDir: string } | { ok: false; reason: string }
12
+
13
+ export type HostAgentMessengerConfigDeps = { exec?: DockerExec; operationLock?: WithAgentOperationLock }
14
+
15
+ export async function prepareAgentMessengerHostConfigDir(
16
+ agentDir: string,
17
+ deps: HostAgentMessengerConfigDeps = {},
18
+ ): Promise<HostAgentMessengerConfigResult> {
19
+ const exec = deps.exec ?? defaultDockerExec
20
+ const containerName = containerNameFromCwd(agentDir)
21
+ const inspected = await inspectRunningConfig(exec, containerName)
22
+ if (!inspected.ok) return inspected
23
+
24
+ if (inspected.state === 'running') {
25
+ return mapContainerDirToHost(agentDir, inspected.containerDir)
26
+ }
27
+
28
+ try {
29
+ const policy = resolveAgentMessengerConfigPolicy(agentDir)
30
+ if (policy.migrate) {
31
+ const reprobed = await inspectRunningConfig(exec, containerName)
32
+ if (!reprobed.ok) return reprobed
33
+ if (reprobed.state === 'running') {
34
+ return {
35
+ ok: false,
36
+ reason: `Container ${containerName} became running while authentication was being prepared. No credentials were written; retry authentication.`,
37
+ }
38
+ }
39
+ const migration = await migrateAgentMessengerConfigDir(agentDir)
40
+ if (!migration.ok) return migration
41
+ }
42
+ return mapContainerDirToHost(agentDir, policy.containerDir)
43
+ } catch (error) {
44
+ return {
45
+ ok: false,
46
+ reason: `Could not prepare the host agent-messenger config directory: ${error instanceof Error ? error.message : String(error)}`,
47
+ }
48
+ }
49
+ }
50
+
51
+ type RunningConfigInspection =
52
+ | { ok: true; state: 'running'; containerDir: string }
53
+ | { ok: true; state: 'stopped-or-missing' }
54
+ | { ok: false; reason: string }
55
+
56
+ async function inspectRunningConfig(exec: DockerExec, containerName: string): Promise<RunningConfigInspection> {
57
+ let result
58
+ try {
59
+ result = await exec(['inspect', '--format', '{{.State.Running}}\n{{json .Config.Env}}', containerName])
60
+ } catch (error) {
61
+ return indeterminateDockerState(error instanceof Error ? error.message : String(error))
62
+ }
63
+
64
+ if (result.exitCode !== 0) {
65
+ if (isGenuineMissingContainer(result.stderr)) return { ok: true, state: 'stopped-or-missing' }
66
+ return indeterminateDockerState(result.stderr.trim() || `docker inspect exited with code ${result.exitCode}`)
67
+ }
68
+
69
+ const parsed = parseInspectOutput(result.stdout)
70
+ if (!parsed.ok) return indeterminateDockerState(parsed.reason)
71
+ if (!parsed.running) return { ok: true, state: 'stopped-or-missing' }
72
+
73
+ const activeEnv = parsed.env.find((entry) => entry.startsWith(CONFIG_ENV_PREFIX))
74
+ const activeDir = activeEnv?.slice(CONFIG_ENV_PREFIX.length)
75
+ // Empty means unset here to mirror the SDK's `override && override.length > 0` check.
76
+ if (activeDir === undefined || activeDir.length === 0) {
77
+ return {
78
+ ok: false,
79
+ reason:
80
+ 'The running TypeClaw container has no non-empty AGENT_MESSENGER_CONFIG_DIR and is using its in-container HOME fallback, which the host cannot write. Set AGENT_MESSENGER_CONFIG_DIR to a path under /agent or stop the container before authenticating.',
81
+ }
82
+ }
83
+ return { ok: true, state: 'running', containerDir: posix.resolve(CONTAINER_AGENT_DIR, activeDir) }
84
+ }
85
+
86
+ function indeterminateDockerState(detail: string): { ok: false; reason: string } {
87
+ return {
88
+ ok: false,
89
+ reason: `Could not determine whether the TypeClaw container is running; refusing to migrate or authenticate. Resolve Docker access and retry. ${detail}`,
90
+ }
91
+ }
92
+
93
+ type ParsedInspectOutput = { ok: true; running: boolean; env: string[] } | { ok: false; reason: string }
94
+
95
+ function parseInspectOutput(stdout: string): ParsedInspectOutput {
96
+ const lines = stdout.trimEnd().split('\n')
97
+ if (lines.length !== 2 || (lines[0] !== 'true' && lines[0] !== 'false')) {
98
+ return { ok: false, reason: 'docker inspect returned malformed running-state/config output' }
99
+ }
100
+ try {
101
+ const env: unknown = JSON.parse(lines[1]!)
102
+ if (!Array.isArray(env) || !env.every((entry) => typeof entry === 'string')) {
103
+ return { ok: false, reason: 'docker inspect returned a malformed container environment' }
104
+ }
105
+ return { ok: true, running: lines[0] === 'true', env }
106
+ } catch {
107
+ return { ok: false, reason: 'docker inspect returned malformed environment JSON' }
108
+ }
109
+ }
110
+
111
+ function mapContainerDirToHost(agentDir: string, containerDir: string): HostAgentMessengerConfigResult {
112
+ const resolved = posix.resolve(CONTAINER_AGENT_DIR, containerDir)
113
+ const relative = posix.relative(CONTAINER_AGENT_DIR, resolved)
114
+ if (relative === '..' || relative.startsWith('../') || posix.isAbsolute(relative)) {
115
+ return {
116
+ ok: false,
117
+ reason: `AGENT_MESSENGER_CONFIG_DIR resolves outside /agent (${resolved}) and cannot be mapped to the host agent directory. Set it to /agent or a path beneath /agent before authenticating.`,
118
+ }
119
+ }
120
+ return { ok: true, hostDir: relative === '' ? agentDir : join(agentDir, ...relative.split('/')) }
121
+ }
@@ -3,6 +3,7 @@ import path from 'node:path'
3
3
 
4
4
  import { parseConfigJson } from '@/config'
5
5
  import { validateCronEdit } from '@/cron'
6
+ import { RECOVER_MISSING, realIntendedPath } from '@/path-safety/real-intended-path'
6
7
 
7
8
  import type { GuardBlock } from '../policy'
8
9
 
@@ -161,25 +162,11 @@ function blockReason(tool: string, targetPath: string, reason: string): GuardBlo
161
162
  }
162
163
  }
163
164
 
165
+ // RECOVER_MISSING only: this policy decides whether a write is ALLOWED, so an
166
+ // ancestor that cannot be resolved must never widen the permitted surface.
164
167
  async function resolveRealIntendedPath(absolutePath: string): Promise<string> {
165
- const pending: string[] = []
166
- let current = absolutePath
167
-
168
- while (true) {
169
- try {
170
- const realCurrent = await realpath(current)
171
- return path.join(realCurrent, ...pending.reverse())
172
- } catch (err) {
173
- if (!isNotFoundError(err)) throw err
174
- }
175
-
176
- const parent = path.dirname(current)
177
- if (parent === current) throw new Error(`could not resolve existing parent for ${absolutePath}`)
178
- pending.push(path.basename(current))
179
- current = parent
180
- }
181
- }
182
-
183
- function isNotFoundError(err: unknown): boolean {
184
- return err instanceof Error && 'code' in err && err.code === 'ENOENT'
168
+ return await realIntendedPath(absolutePath, realpath, {
169
+ recoverable: RECOVER_MISSING,
170
+ onExhausted: 'throw',
171
+ })
185
172
  }
@@ -2,6 +2,7 @@ import { realpath } from 'node:fs/promises'
2
2
  import path from 'node:path'
3
3
 
4
4
  import type { SessionOrigin } from '@/agent/session-origin'
5
+ import { RECOVER_MISSING, realIntendedPath } from '@/path-safety/real-intended-path'
5
6
 
6
7
  import { ACKNOWLEDGE_GUARDS, type GuardBlock, isGuardAcknowledged } from '../policy'
7
8
  import { isMemoryTopicsWriteAllowed } from './memory-topics-write'
@@ -132,25 +133,11 @@ function isInside(parent: string, child: string): boolean {
132
133
  return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
133
134
  }
134
135
 
136
+ // RECOVER_MISSING only: this policy decides whether a write is ALLOWED, so an
137
+ // ancestor that cannot be resolved must never widen the permitted surface.
135
138
  async function resolveRealIntendedPath(absolutePath: string): Promise<string> {
136
- const pending: string[] = []
137
- let current = absolutePath
138
-
139
- while (true) {
140
- try {
141
- const realCurrent = await realpath(current)
142
- return path.join(realCurrent, ...pending.reverse())
143
- } catch (err) {
144
- if (!isNotFoundError(err)) throw err
145
- }
146
-
147
- const parent = path.dirname(current)
148
- if (parent === current) throw new Error(`could not resolve existing parent for ${absolutePath}`)
149
- pending.push(path.basename(current))
150
- current = parent
151
- }
152
- }
153
-
154
- function isNotFoundError(err: unknown): boolean {
155
- return err instanceof Error && 'code' in err && err.code === 'ENOENT'
139
+ return await realIntendedPath(absolutePath, realpath, {
140
+ recoverable: RECOVER_MISSING,
141
+ onExhausted: 'throw',
142
+ })
156
143
  }
@@ -1,6 +1,8 @@
1
1
  import { readFile, realpath } from 'node:fs/promises'
2
2
  import path from 'node:path'
3
3
 
4
+ import { RECOVER_MISSING, realIntendedPath } from '@/path-safety/real-intended-path'
5
+
4
6
  import type { GuardBlock } from '../policy'
5
7
 
6
8
  export const GUARD_SKILL_AUTHORING = 'skillAuthoring'
@@ -161,25 +163,11 @@ function isInside(parent: string, child: string): boolean {
161
163
  return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
162
164
  }
163
165
 
166
+ // RECOVER_MISSING only: this policy decides whether a write is ALLOWED, so an
167
+ // ancestor that cannot be resolved must never widen the permitted surface.
164
168
  async function resolveRealIntendedPath(absolutePath: string): Promise<string> {
165
- const pending: string[] = []
166
- let current = absolutePath
167
-
168
- while (true) {
169
- try {
170
- const realCurrent = await realpath(current)
171
- return path.join(realCurrent, ...pending.reverse())
172
- } catch (err) {
173
- if (!isNotFoundError(err)) throw err
174
- }
175
-
176
- const parent = path.dirname(current)
177
- if (parent === current) throw new Error(`could not resolve existing parent for ${absolutePath}`)
178
- pending.push(path.basename(current))
179
- current = parent
180
- }
181
- }
182
-
183
- function isNotFoundError(err: unknown): boolean {
184
- return err instanceof Error && 'code' in err && err.code === 'ENOENT'
169
+ return await realIntendedPath(absolutePath, realpath, {
170
+ recoverable: RECOVER_MISSING,
171
+ onExhausted: 'throw',
172
+ })
185
173
  }
@@ -111,6 +111,8 @@ The subagent uses these signals to:
111
111
 
112
112
  There is no `## Historical observations` bucket. Demoted topics live as their own shards; injection-time filtering (the index/direct split) handles the prompt-budget pressure.
113
113
 
114
+ **The agent's own response style never becomes a belief (rule 10).** Streams capture the agent's own turns, so fragments sometimes describe how it replied rather than what is true — how it apologized, how it took a correction, how terse its status updates were. Consolidating those teaches the next session to reproduce a shape instead of doing the work; a shard describing a convincing apology is the worst case, because it makes accountability a template the agent can perform without having verified anything. The user-side fact is kept ("the user wants status updates under 20 words"), the agent-side self-description dropped. Voice and register belong in `SOUL.md`, which the subagent never writes.
115
+
114
116
  ## Muscle memory (three forms)
115
117
 
116
118
  While reading streams, the dreaming subagent watches for **repeated multi-step procedures** the user has guided the main agent through, and codifies them. There are three forms, picked smallest-that-fits (top to bottom, stop at the first match):
@@ -997,6 +997,8 @@ references:
997
997
 
998
998
  The reference files under \`memory/references/\` are verbatim artifacts. You MUST NOT read, rewrite, or distill their content. You may only cite them by slug. On eviction (Phase 4), citations are pruned — but that is a separate pass, not your concern here.
999
999
 
1000
+ **10. Never turn the main agent's own response style into a belief.** Streams often contain fragments describing how the main agent phrased, structured, or paced its own reply — how it apologized, how it took a correction, how long its status updates ran. A durable fact about the USER is memory; a description of how the agent's own reply *sounded* is not. Consolidating one teaches the next session to reproduce a shape instead of doing the work, and a shard describing a convincing apology is the worst case: it turns accountability into a template the agent can perform without having verified anything, which is exactly the behavior that produces false "I fixed it" claims. Keep the user-side fact ("the user wants status updates under 20 words", "the user corrected the summary language to Korean") and drop the agent-side self-description ("the agent replied with an apology, a root cause, and a fix in under 70 words"). When a fragment carries both, keep only the user-side half. Voice and register live in \`SOUL.md\`, which the user owns and you never write.
1001
+
1000
1002
  # What a topic shard looks like
1001
1003
 
1002
1004
  \`\`\`
@@ -16,6 +16,7 @@ import path from 'node:path'
16
16
  import { fileURLToPath } from 'node:url'
17
17
 
18
18
  import { TOOLS_WITHOUT_LOCAL_FILE_OPERANDS } from '@/agent/tools-without-local-file-operands'
19
+ import { RECOVER_MISSING_OR_UNSEARCHABLE, realIntendedPathSync } from '@/path-safety/real-intended-path'
19
20
  import type { ToolFileOperands } from '@/plugin'
20
21
  import {
21
22
  CANONICAL_AGENT_SECRET_DIRS,
@@ -959,30 +960,16 @@ function hasSameFileIdentity(candidate: string, deniedFile: string): boolean {
959
960
  }
960
961
  }
961
962
 
962
- // Resolves symlinks on the longest existing prefix of an absolute path, then
963
- // re-appends the non-existent tail. A bare realpathSync throws on a path that
964
- // does not exist yet (a write target, or a read of a not-yet-created file), so
965
- // we walk up to the nearest existing ancestor, realpath THAT (collapsing any
966
- // symlinked component including a planted symlink), and rejoin the remainder.
967
- // This catches `public/leak/x` where `public/leak` is a symlink into a hidden
968
- // dir even though `public/leak/x` itself does not exist. Sync (realpathSync)
969
- // keeps the guard synchronous; the cost is one syscall per existing component,
970
- // negligible at the tool-call boundary. Sync mirror of resolveRealIntendedPath
971
- // in the guard plugin's non-workspace-write policy.
963
+ // Sync keeps the guard synchronous; the cost is one syscall per existing
964
+ // component, negligible at the tool-call boundary. EACCES is recoverable here
965
+ // (but NOT in the guard plugin's write policies): this is denylist matching, so
966
+ // a path under an unsearchable ancestor must still be matched rather than
967
+ // aborting the whole guard. See @/path-safety/real-intended-path.
972
968
  function realpathRealIntendedPath(absolutePath: string, realpath: (candidate: string) => string): string {
973
- const pending: string[] = []
974
- let current = absolutePath
975
- while (true) {
976
- try {
977
- return path.join(realpath(current), ...pending.reverse())
978
- } catch (err) {
979
- if (!isNotFoundError(err)) throw err
980
- }
981
- const parent = path.dirname(current)
982
- if (parent === current) return absolutePath
983
- pending.push(path.basename(current))
984
- current = parent
985
- }
969
+ return realIntendedPathSync(absolutePath, realpath, {
970
+ recoverable: RECOVER_MISSING_OR_UNSEARCHABLE,
971
+ onExhausted: 'return-input',
972
+ })
986
973
  }
987
974
 
988
975
  function isNotFoundError(err: unknown): boolean {