typeclaw 0.48.0 → 0.48.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/agent/plugin-tools.ts +68 -9
- package/src/agent-messenger/config-dir.ts +131 -0
- package/src/agent-messenger/host-config-dir.ts +121 -0
- package/src/cli/channel.ts +15 -16
- package/src/cli/hostd.ts +8 -13
- package/src/cli/init.ts +21 -7
- package/src/cli/model.ts +6 -3
- package/src/cli/restart.ts +13 -15
- package/src/compose/restart.ts +14 -6
- package/src/config/providers.ts +14 -125
- package/src/container/agent-operation-lock.ts +85 -0
- package/src/container/controller.ts +6 -0
- package/src/container/index.ts +8 -0
- package/src/container/restart.ts +55 -0
- package/src/container/shared.ts +5 -0
- package/src/container/start.ts +70 -4
- package/src/container/stop.ts +17 -1
- package/src/hostd/daemon.ts +1 -1
- package/src/hostd/paths.ts +17 -0
- package/src/hostd/supervisor.ts +27 -10
- package/src/init/dockerfile.ts +6 -5
- package/src/init/env-file.ts +42 -18
- package/src/init/instagram-auth.ts +55 -31
- package/src/init/kakaotalk-auth.ts +1 -5
- package/src/init/line-auth.ts +45 -29
- package/src/init/models-dev.ts +114 -7
- package/src/init/opengateway-catalog.ts +120 -0
- package/src/sandbox/canonical-secrets.ts +10 -1
- package/src/sandbox/errors.ts +0 -32
- package/src/sandbox/privileged-runtime.ts +8 -94
- package/src/test-helpers/fake-agent-operation-lock.ts +66 -0
- package/typeclaw.schema.json +5 -30
package/package.json
CHANGED
|
@@ -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
|
-
? {
|
|
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
|
-
|
|
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')
|
|
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
|
-
|
|
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(
|
|
@@ -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
|
+
}
|
package/src/cli/channel.ts
CHANGED
|
@@ -654,16 +654,12 @@ async function maybePromptCredentialRefresh(
|
|
|
654
654
|
return
|
|
655
655
|
}
|
|
656
656
|
|
|
657
|
-
const
|
|
658
|
-
if (!
|
|
659
|
-
console.error(errorLine(
|
|
660
|
-
process.exit(1)
|
|
661
|
-
}
|
|
662
|
-
const started = await controller.start({ cwd, preferredHostPort: config.port, cliEntry: process.argv[1] })
|
|
663
|
-
if (!started.ok) {
|
|
664
|
-
console.error(errorLine(`Restart failed during start: ${started.reason}`))
|
|
657
|
+
const restarted = await controller.restart({ cwd, preferredHostPort: config.port, cliEntry: process.argv[1] })
|
|
658
|
+
if (!restarted.ok) {
|
|
659
|
+
console.error(errorLine(formatRestartFailure(restarted.reason)))
|
|
665
660
|
process.exit(1)
|
|
666
661
|
}
|
|
662
|
+
const started = restarted.start
|
|
667
663
|
done({
|
|
668
664
|
title: c.green(`${label} ${verbPast}. Restarted ${started.plan.containerName} on host port ${started.hostPort}.`),
|
|
669
665
|
hints: [
|
|
@@ -2002,16 +1998,12 @@ async function maybePromptRestart(
|
|
|
2002
1998
|
return
|
|
2003
1999
|
}
|
|
2004
2000
|
|
|
2005
|
-
const
|
|
2006
|
-
if (!
|
|
2007
|
-
console.error(errorLine(
|
|
2008
|
-
process.exit(1)
|
|
2009
|
-
}
|
|
2010
|
-
const started = await controller.start({ cwd, preferredHostPort: config.port, cliEntry: process.argv[1] })
|
|
2011
|
-
if (!started.ok) {
|
|
2012
|
-
console.error(errorLine(`Restart failed during start: ${started.reason}`))
|
|
2001
|
+
const restarted = await controller.restart({ cwd, preferredHostPort: config.port, cliEntry: process.argv[1] })
|
|
2002
|
+
if (!restarted.ok) {
|
|
2003
|
+
console.error(errorLine(formatRestartFailure(restarted.reason)))
|
|
2013
2004
|
process.exit(1)
|
|
2014
2005
|
}
|
|
2006
|
+
const started = restarted.start
|
|
2015
2007
|
done({
|
|
2016
2008
|
title: c.green(
|
|
2017
2009
|
`${label} channel ${verb}. Restarted ${started.plan.containerName} on host port ${started.hostPort}.`,
|
|
@@ -2022,3 +2014,10 @@ async function maybePromptRestart(
|
|
|
2022
2014
|
],
|
|
2023
2015
|
})
|
|
2024
2016
|
}
|
|
2017
|
+
|
|
2018
|
+
function formatRestartFailure(reason: string): string {
|
|
2019
|
+
if (reason.startsWith('stop failed: ')) return `Restart failed during stop: ${reason.slice('stop failed: '.length)}`
|
|
2020
|
+
if (reason.startsWith('start failed: '))
|
|
2021
|
+
return `Restart failed during start: ${reason.slice('start failed: '.length)}`
|
|
2022
|
+
return `Restart failed: ${reason}`
|
|
2023
|
+
}
|
package/src/cli/hostd.ts
CHANGED
|
@@ -5,9 +5,8 @@ import {
|
|
|
5
5
|
resolveController,
|
|
6
6
|
resolveHostPort,
|
|
7
7
|
resolveTuiToken,
|
|
8
|
-
type
|
|
9
|
-
type
|
|
10
|
-
type StopResult,
|
|
8
|
+
type RestartOptions,
|
|
9
|
+
type RestartResult,
|
|
11
10
|
} from '@/container'
|
|
12
11
|
import {
|
|
13
12
|
applyCredentialRotation,
|
|
@@ -116,17 +115,15 @@ export const hostdCommand = defineCommand({
|
|
|
116
115
|
|
|
117
116
|
export type HostdRestartDeps = {
|
|
118
117
|
validateConfig: (cwd: string) => ValidateConfigResult
|
|
119
|
-
stop: (opts: { cwd: string }) => Promise<StopResult>
|
|
120
118
|
loadConfigSync: (cwd: string) => Config
|
|
121
|
-
|
|
119
|
+
restart: (opts: RestartOptions) => Promise<RestartResult>
|
|
122
120
|
}
|
|
123
121
|
|
|
124
122
|
const controller = resolveController()
|
|
125
123
|
const defaultRestartDeps: HostdRestartDeps = {
|
|
126
124
|
validateConfig,
|
|
127
|
-
stop: (opts) => controller.stop(opts),
|
|
128
125
|
loadConfigSync,
|
|
129
|
-
|
|
126
|
+
restart: (opts) => controller.restart(opts),
|
|
130
127
|
}
|
|
131
128
|
|
|
132
129
|
export function buildHostdRestart(
|
|
@@ -134,7 +131,7 @@ export function buildHostdRestart(
|
|
|
134
131
|
deps: HostdRestartDeps = defaultRestartDeps,
|
|
135
132
|
daemonVersion?: string,
|
|
136
133
|
): SupervisorRestart {
|
|
137
|
-
return async ({ containerName, cwd, build = false, currentHostDaemon }) => {
|
|
134
|
+
return async ({ containerName, cwd, build = false, currentHostDaemon, operationLease }) => {
|
|
138
135
|
const drift = await detectSourceDrift(cliEntry, daemonVersion)
|
|
139
136
|
if (drift) return { ok: false, reason: drift }
|
|
140
137
|
|
|
@@ -142,19 +139,17 @@ export function buildHostdRestart(
|
|
|
142
139
|
if (!validated.ok) {
|
|
143
140
|
return { ok: false, reason: `invalid config for ${containerName}: ${validated.reason}` }
|
|
144
141
|
}
|
|
145
|
-
const stopResult = await deps.stop({ cwd })
|
|
146
|
-
if (!stopResult.ok) return { ok: false, reason: `stop failed: ${stopResult.reason}` }
|
|
147
|
-
|
|
148
142
|
const cfg = deps.loadConfigSync(cwd)
|
|
149
|
-
const
|
|
143
|
+
const restartResult = await deps.restart({
|
|
150
144
|
cwd,
|
|
151
145
|
preferredHostPort: cfg.port,
|
|
152
146
|
forceBuild: build,
|
|
153
147
|
cliEntry,
|
|
154
148
|
reuseCurrentHostDaemon: true,
|
|
149
|
+
operationLease,
|
|
155
150
|
...(currentHostDaemon ? { currentHostDaemon } : {}),
|
|
156
151
|
})
|
|
157
|
-
if (!
|
|
152
|
+
if (!restartResult.ok) return restartResult
|
|
158
153
|
return { ok: true }
|
|
159
154
|
}
|
|
160
155
|
}
|
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 {
|
|
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
|
|
1227
|
-
const
|
|
1228
|
-
|
|
1229
|
-
|
|
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
|
|
1237
|
+
s.stop('Loaded model catalogs.')
|
|
1232
1238
|
}
|
|
1233
|
-
return
|
|
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,
|
|
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 (
|
|
551
|
-
|
|
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
|
package/src/cli/restart.ts
CHANGED
|
@@ -74,28 +74,26 @@ export const restartCommand = defineCommand({
|
|
|
74
74
|
|
|
75
75
|
const stopSpin = spinner()
|
|
76
76
|
stopSpin.start('Stopping container...')
|
|
77
|
-
|
|
78
|
-
|
|
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 (!
|
|
93
|
-
startSpin.error(
|
|
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
|
|
94
|
+
startSpin?.stop('Started.')
|
|
97
95
|
|
|
98
|
-
reportConfigWarnings(
|
|
99
|
-
console.log(renderStartSuccess(
|
|
96
|
+
reportConfigWarnings(restarted.start.dockerfileWarnings)
|
|
97
|
+
console.log(renderStartSuccess(restarted.start))
|
|
100
98
|
},
|
|
101
99
|
})
|
package/src/compose/restart.ts
CHANGED
|
@@ -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
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
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
|
}
|