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.
@@ -0,0 +1,120 @@
1
+ import type { ModelOptionCost } from './models-dev'
2
+
3
+ const CATALOG_URL = 'https://apis.opengateway.ai/v1/models'
4
+ const PRICES_URL = 'https://opengateway.ai/api/model-prices'
5
+ const REQUEST_TIMEOUT_MS = 10_000
6
+ const PER_MILLION = 1_000_000
7
+
8
+ export type OpenGatewayModel = {
9
+ id: string
10
+ ownedBy: string
11
+ input: string[]
12
+ cost: ModelOptionCost | null
13
+ }
14
+
15
+ export type OpenGatewayCatalogResult = {
16
+ models: OpenGatewayModel[]
17
+ catalog: 'live' | 'unavailable'
18
+ prices: 'live' | 'unavailable'
19
+ warnings: string[]
20
+ }
21
+
22
+ type SourceResult<T> = { status: 'live'; value: T } | { status: 'unavailable'; warning: string }
23
+
24
+ export async function fetchOpenGatewayCatalog(
25
+ options: { fetchImpl?: typeof fetch; timeoutMs?: number } = {},
26
+ ): Promise<OpenGatewayCatalogResult> {
27
+ const fetchImpl = options.fetchImpl ?? fetch
28
+ const timeoutMs = options.timeoutMs ?? REQUEST_TIMEOUT_MS
29
+ const [catalogResult, pricesResult] = await Promise.all([
30
+ fetchCatalog(fetchImpl, timeoutMs),
31
+ fetchPrices(fetchImpl, timeoutMs),
32
+ ])
33
+ const warnings = [
34
+ ...(catalogResult.status === 'unavailable' ? [catalogResult.warning] : []),
35
+ ...(pricesResult.status === 'unavailable' ? [pricesResult.warning] : []),
36
+ ]
37
+ const prices = pricesResult.status === 'live' ? pricesResult.value : {}
38
+ const models =
39
+ catalogResult.status === 'live'
40
+ ? catalogResult.value.map((model) => ({ ...model, cost: costForModel(prices[model.id]) }))
41
+ : []
42
+
43
+ return {
44
+ models,
45
+ catalog: catalogResult.status,
46
+ prices: pricesResult.status,
47
+ warnings,
48
+ }
49
+ }
50
+
51
+ async function fetchCatalog(fetchImpl: typeof fetch, timeoutMs: number): Promise<SourceResult<OpenGatewayModel[]>> {
52
+ try {
53
+ const response = await fetchImpl(CATALOG_URL, { signal: AbortSignal.timeout(timeoutMs) })
54
+ if (!response.ok) return unavailable('catalog', `returned ${response.status}`)
55
+ const value: unknown = await response.json()
56
+ if (!isRecord(value) || !Array.isArray(value.data)) return unavailable('catalog', 'returned malformed JSON')
57
+ return { status: 'live', value: value.data.flatMap(parseCatalogModel) }
58
+ } catch (error) {
59
+ return unavailable('catalog', reasonFrom(error))
60
+ }
61
+ }
62
+
63
+ async function fetchPrices(fetchImpl: typeof fetch, timeoutMs: number): Promise<SourceResult<Record<string, unknown>>> {
64
+ try {
65
+ const response = await fetchImpl(PRICES_URL, { signal: AbortSignal.timeout(timeoutMs) })
66
+ if (!response.ok) return unavailable('prices', `returned ${response.status}`)
67
+ const value: unknown = await response.json()
68
+ if (!isRecord(value)) return unavailable('prices', 'returned malformed JSON')
69
+ return { status: 'live', value }
70
+ } catch (error) {
71
+ return unavailable('prices', reasonFrom(error))
72
+ }
73
+ }
74
+
75
+ function parseCatalogModel(value: unknown): OpenGatewayModel[] {
76
+ if (!isRecord(value)) return []
77
+ if (typeof value.id !== 'string' || value.id.length === 0) return []
78
+ if (typeof value.owned_by !== 'string' || value.owned_by.length === 0) return []
79
+ if (value.status !== 'active') return []
80
+ if (!isRecord(value.modalities) || !stringArray(value.modalities.output).includes('text')) return []
81
+ if (!stringArray(value.endpoints).includes('chat_completions')) return []
82
+ const input = stringArray(value.modalities.input).filter((modality) => modality === 'text' || modality === 'image')
83
+ return [{ id: value.id, ownedBy: value.owned_by, input, cost: null }]
84
+ }
85
+
86
+ function costForModel(value: unknown): ModelOptionCost | null {
87
+ if (!isRecord(value)) return null
88
+ const input = requiredRate(value.inputCostPerToken)
89
+ const output = requiredRate(value.outputCostPerToken)
90
+ const cacheRead = optionalRate(value.cacheReadInputTokenCost)
91
+ const cacheWrite = optionalRate(value.cacheCreationInputTokenCost)
92
+ if (input === null || output === null || cacheRead === null || cacheWrite === null) return null
93
+ return { input, output, cacheRead, cacheWrite }
94
+ }
95
+
96
+ function requiredRate(value: unknown): number | null {
97
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) return null
98
+ return Number((value * PER_MILLION).toPrecision(15))
99
+ }
100
+
101
+ function optionalRate(value: unknown): number | null {
102
+ if (value === null || value === undefined) return 0
103
+ return requiredRate(value)
104
+ }
105
+
106
+ function unavailable<T>(source: 'catalog' | 'prices', reason: string): SourceResult<T> {
107
+ return { status: 'unavailable', warning: `OpenGateway ${source} ${reason}` }
108
+ }
109
+
110
+ function reasonFrom(error: unknown): string {
111
+ return error instanceof Error ? error.message : String(error)
112
+ }
113
+
114
+ function isRecord(value: unknown): value is Record<string, unknown> {
115
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
116
+ }
117
+
118
+ function stringArray(value: unknown): string[] {
119
+ return Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : []
120
+ }
@@ -1,6 +1,14 @@
1
+ import {
2
+ AGENT_MESSENGER_CONFIG_RELATIVE_DIR,
3
+ LEGACY_AGENT_MESSENGER_CONFIG_RELATIVE_DIR,
4
+ } from '@/agent-messenger/config-dir'
5
+
1
6
  export const CANONICAL_AGENT_SECRET_DIRS = [
2
7
  'workspace/.config/gws',
3
- 'workspace/.agent-messenger',
8
+ AGENT_MESSENGER_CONFIG_RELATIVE_DIR,
9
+ // Retained permanently for interrupted migrations, operator backups under
10
+ // the old name, and older installs. This is not an active config location.
11
+ LEGACY_AGENT_MESSENGER_CONFIG_RELATIVE_DIR,
4
12
  '.typeclaw/home',
5
13
  '.typeclaw/logs',
6
14
  ] as const
@@ -17,6 +25,7 @@ export const CANONICAL_HOME_SECRET_DIRS = [
17
25
  '.ssh',
18
26
  '.config/gh',
19
27
  '.config/gws',
28
+ '.config/agent-messenger',
20
29
  '.agent-messenger',
21
30
  '.codex',
22
31
  '.claude',
@@ -26,38 +26,6 @@ export class SandboxPolicyError extends Error {
26
26
  }
27
27
  }
28
28
 
29
- // Raised when model-driven bash invokes an agent-messenger CLI. TypeClaw never
30
- // brokers those reusable auth profiles (resolvePrivilegedSandboxRuntime) AND
31
- // masks the whole `workspace/.agent-messenger` directory, so the CLI can never
32
- // authenticate here — every platform resolves credentials from a
33
- // `<platform>-credentials.json` file, never from the environment.
34
- //
35
- // The refusal MUST announce itself. A silent one lets the uncredentialed CLI
36
- // print its own "No current workspace set. Run `auth extract` first.", which the
37
- // model reads as a fact about the WORLD — and it will then tell a human the
38
- // runtime has no workspace authentication, laundering a local policy decision
39
- // into a false claim about the upstream service. The CLI is honest about ITS
40
- // state; it has no way to know it was deliberately deprived.
41
- //
42
- // Hence the message states its own provenance: what was withheld, that the
43
- // decision is local, that retrying cannot help, and which mediated tool does
44
- // work. The last part is load-bearing — a dead end the model cannot route
45
- // around produces exactly the confabulation this class exists to prevent.
46
- export class SandboxCredentialWithheldError extends Error {
47
- override readonly name = 'SandboxCredentialWithheldError'
48
- constructor(executable: string) {
49
- super(
50
- `credential withheld by TypeClaw policy: \`${executable}\` cannot authenticate in model-driven bash. ` +
51
- 'TypeClaw never brokers an agent-messenger auth profile to a model-controlled child (the CLI can upload ' +
52
- 'arbitrary files, so a brokered credential would make it a confused deputy), and its credential directory ' +
53
- 'is masked. This is a LOCAL sandbox policy decision. It is NOT evidence that the workspace, account, or ' +
54
- 'upstream service lacks authentication — do not report it as such. Retrying, running `auth extract`, or ' +
55
- 'switching package runner will not change it. Use the mediated channel_* tools instead (channel_read, ' +
56
- 'channel_history, channel_send), which run inside TypeClaw with the configured channel credential.',
57
- )
58
- }
59
- }
60
-
61
29
  // Raised when the /proc strategy degraded to the empty `tmpfs` fallback AND the
62
30
  // command needs a real /proc (bunx / bun run that reads the
63
31
  // kernel-backed /proc/self/{fd,maps}). Without this pre-check Bun aborts deep in
@@ -2,7 +2,7 @@ import { chmod, lstat, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises
2
2
  import { homedir, tmpdir } from 'node:os'
3
3
  import path from 'node:path'
4
4
 
5
- import { SandboxCredentialWithheldError, SandboxPolicyError } from './errors'
5
+ import { SandboxPolicyError } from './errors'
6
6
  import type { SandboxMount } from './policy'
7
7
 
8
8
  const SAFE_GIT_SUBCOMMANDS = new Set([
@@ -30,49 +30,6 @@ const SAFE_GIT_SUBCOMMANDS = new Set([
30
30
 
31
31
  const SHELL_ACTIVE = new Set(['|', ';', '&', '\n', '\r', '(', ')', '{', '}', '<', '>', '`', '$', '\\'])
32
32
 
33
- // The exact bins agent-messenger installs, kept in lockstep with the installed
34
- // manifest by a test. Reserving the whole `agent-*` namespace instead would
35
- // over-claim AND under-claim: an unrelated user-installed `agent-lint` would be
36
- // refused with a false agent-messenger credential claim — the very class of
37
- // false statement this refusal exists to prevent — while `amsg`, a real
38
- // agent-messenger bin, carries no `agent-` prefix and would slip through.
39
- export const AGENT_MESSENGER_BINS: ReadonlySet<string> = new Set([
40
- 'agent-channeltalk',
41
- 'agent-channeltalkbot',
42
- 'agent-discord',
43
- 'agent-discordbot',
44
- 'agent-imessage',
45
- 'agent-instagram',
46
- 'agent-kakaotalk',
47
- 'agent-line',
48
- 'agent-messenger',
49
- 'agent-slack',
50
- 'agent-slackbot',
51
- 'agent-teams',
52
- 'agent-telegram',
53
- 'agent-telegrambot',
54
- 'agent-webex',
55
- 'agent-webexbot',
56
- 'agent-wechatbot',
57
- 'agent-whatsapp',
58
- 'agent-whatsappbot',
59
- 'amsg',
60
- ])
61
-
62
- // Ephemeral runners that execute a package bin named by their first operand.
63
- // `bunx` is the bare-binary alias for `bun x` (see sandbox/package-install.ts);
64
- // npx/pnpx are the non-bun spellings the bun-hygiene guard still permits.
65
- const PACKAGE_RUNNERS = new Set(['bunx', 'npx', 'pnpx'])
66
- const BUN_RUNNER_SUBCOMMANDS = new Set(['x', 'run'])
67
-
68
- // Splits at the shell operators that begin a NEW simple command, mirroring
69
- // `commandNeedsRealProc`. Deliberately coarse: it over-splits inside quotes and
70
- // `$()`, but this feeds a DENY-ONLY decision, so a spurious extra segment can
71
- // only make the refusal MORE likely — it can never grant a credential.
72
- const SHELL_COMMAND_SEPARATOR = /(?:&&|\|\||[;|&\n()<>])+/
73
-
74
- const ENV_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/
75
-
76
33
  export type PrivilegedSandboxRuntime = {
77
34
  env: Record<string, string>
78
35
  mounts: SandboxMount[]
@@ -89,7 +46,6 @@ export async function resolvePrivilegedSandboxRuntime(options: {
89
46
  env?: NodeJS.ProcessEnv
90
47
  homeDir?: string
91
48
  }): Promise<PrivilegedSandboxRuntime> {
92
- rejectAgentMessengerCommand(options.command)
93
49
  const runtime = emptyRuntime()
94
50
  // TYPECLAW_GIT_TOKEN is set only after the auth analyzer accepts a Git command.
95
51
  // Trust that decision rather than reparsing its command with a less capable
@@ -106,26 +62,13 @@ export async function resolvePrivilegedSandboxRuntime(options: {
106
62
  const executable = unwrapBunx(parsed)
107
63
  if (executable === null) return runtime
108
64
 
109
- // Re-checked here as well as in the deny-only scan: this path resolves quoted
110
- // and `bunx`-wrapped executables the coarse segment split cannot.
111
- if (AGENT_MESSENGER_BINS.has(path.basename(executable.executable))) {
112
- throw new SandboxCredentialWithheldError(path.basename(executable.executable))
113
- }
114
-
115
- // These CLIs can print or upload arbitrary files. Supplying their reusable
116
- // auth profile to a model-controlled child would therefore make the CLI a
117
- // confused deputy even when the outer shell is syntactically standalone.
118
- //
119
- // They stay executable-but-uncredentialed rather than refused outright: an
120
- // operator CAN authenticate them from `.env`, which model bash does inherit,
121
- // so refusing would break working setups. The agent-messenger family cannot —
122
- // every platform reads a `<platform>-credentials.json` file under the
123
- // unconditionally masked `workspace/.agent-messenger` — so it is a guaranteed
124
- // dead end and is refused loudly above instead of failing misleadingly.
125
- if (executable.executable === 'gws' || executable.executable === 'codex' || executable.executable === 'claude') {
126
- return runtime
127
- }
128
-
65
+ // Credentials are default-deny: only an explicit broker below grants a
66
+ // profile, and `git` is the only broker. Do not add executable-name checks
67
+ // here. The confused-deputy argument belongs to the default, not to a list of
68
+ // names — it holds for every model-controlled child that can print or upload
69
+ // files, including ones not yet written. A name list is also where beliefs
70
+ // about a tool's credential layout accumulate; one such belief was wrong and
71
+ // refused a working CLI family outright. See this file's history.
129
72
  if (executable.executable === 'git') {
130
73
  runtime.env.GIT_CONFIG_GLOBAL = '/dev/null'
131
74
  runtime.env.GIT_CONFIG_NOSYSTEM = '1'
@@ -148,35 +91,6 @@ function containsGitInvocation(command: string): boolean {
148
91
  return /(^|[;&|]\s*)git(?:\s|$)/.test(command.trim())
149
92
  }
150
93
 
151
- function rejectAgentMessengerCommand(command: string): void {
152
- for (const segment of command.split(SHELL_COMMAND_SEPARATOR)) {
153
- const bin = agentMessengerBinIn(segment)
154
- if (bin !== undefined) throw new SandboxCredentialWithheldError(bin)
155
- }
156
- }
157
-
158
- function agentMessengerBinIn(segment: string): string | undefined {
159
- const words = segment
160
- .trim()
161
- .split(/\s+/)
162
- .map((word) => word.replaceAll(/^["']|["']$/g, ''))
163
- .filter((word) => word !== '' && !ENV_ASSIGNMENT.test(word))
164
- const operand = unwrapPackageRunner(words).find((word) => !word.startsWith('-'))
165
- if (operand === undefined) return undefined
166
- const bin = path.basename(operand)
167
- return AGENT_MESSENGER_BINS.has(bin) ? bin : undefined
168
- }
169
-
170
- function unwrapPackageRunner(words: readonly string[]): readonly string[] {
171
- const head = words[0]
172
- if (head === undefined) return words
173
- const runner = path.basename(head)
174
- if (PACKAGE_RUNNERS.has(runner)) return words.slice(1)
175
- const subcommand = words[1]
176
- if (runner === 'bun' && subcommand !== undefined && BUN_RUNNER_SUBCOMMANDS.has(subcommand)) return words.slice(2)
177
- return words
178
- }
179
-
180
94
  export async function verifyPrivilegedSandboxRuntime(runtime: PrivilegedSandboxRuntime): Promise<void> {
181
95
  const identities = mountedIdentities.get(runtime) ?? new Map()
182
96
  for (const mount of runtime.mounts) {
@@ -0,0 +1,66 @@
1
+ import { resolve } from 'node:path'
2
+
3
+ import type {
4
+ AgentOperation,
5
+ AgentOperationLease,
6
+ AgentOperationLockResult,
7
+ WithAgentOperationLock,
8
+ } from '@/container/agent-operation-lock'
9
+ import { containerNameFromCwd } from '@/container/shared'
10
+
11
+ export class FakeAgentOperationCoordinator {
12
+ readonly events: string[] = []
13
+ readonly operationLock: WithAgentOperationLock
14
+
15
+ private readonly active = new Set<string>()
16
+
17
+ constructor(private readonly contentionReason = 'contended') {
18
+ this.operationLock = async <T>(
19
+ input: { agentDir: string; operation: AgentOperation; lease?: AgentOperationLease },
20
+ run: (lease: AgentOperationLease) => Promise<T>,
21
+ ): Promise<AgentOperationLockResult<T>> => {
22
+ const agentDir = resolve(input.agentDir)
23
+ const containerName = containerNameFromCwd(agentDir)
24
+ const lease = { containerName, agentDir }
25
+ if (input.lease !== undefined) {
26
+ if (input.lease.containerName !== containerName || resolve(input.lease.agentDir) !== agentDir) {
27
+ return { ok: false, reason: 'mismatched lease' }
28
+ }
29
+ return { ok: true, value: await run(input.lease) }
30
+ }
31
+ if (this.active.has(containerName)) {
32
+ this.events.push(`lock-contention:${input.operation}`)
33
+ return { ok: false, reason: this.contentionReason }
34
+ }
35
+ this.active.add(containerName)
36
+ this.events.push(`lock-enter:${input.operation}`)
37
+ try {
38
+ return { ok: true, value: await run(lease) }
39
+ } finally {
40
+ this.events.push(`lock-exit:${input.operation}`)
41
+ this.active.delete(containerName)
42
+ }
43
+ }
44
+ }
45
+
46
+ park(): { entered: Promise<void>; wait: () => Promise<void>; release: () => void } {
47
+ const entered = deferred()
48
+ const released = deferred()
49
+ return {
50
+ entered: entered.promise,
51
+ wait: async () => {
52
+ entered.resolve()
53
+ await released.promise
54
+ },
55
+ release: () => released.resolve(),
56
+ }
57
+ }
58
+ }
59
+
60
+ function deferred(): { promise: Promise<void>; resolve: () => void } {
61
+ let resolvePromise: () => void = () => {}
62
+ const promise = new Promise<void>((resolve) => {
63
+ resolvePromise = resolve
64
+ })
65
+ return { promise, resolve: resolvePromise }
66
+ }
@@ -65,12 +65,7 @@
65
65
  "moonshot/kimi-k2.6",
66
66
  "moonshot/kimi-k2.5",
67
67
  "moonshot-coding/kimi-for-coding",
68
- "opengateway/openai/gpt-5.4-nano",
69
- "opengateway/openai/gpt-5.5",
70
- "opengateway/anthropic/claude-sonnet-5",
71
- "opengateway/anthropic/claude-opus-4-8",
72
- "opengateway/moonshotai/kimi-k2.6",
73
- "opengateway/minimax/MiniMax-M3"
68
+ "opengateway/openai/gpt-5.4-nano"
74
69
  ]
75
70
  },
76
71
  {
@@ -127,12 +122,7 @@
127
122
  "moonshot/kimi-k2.6",
128
123
  "moonshot/kimi-k2.5",
129
124
  "moonshot-coding/kimi-for-coding",
130
- "opengateway/openai/gpt-5.4-nano",
131
- "opengateway/openai/gpt-5.5",
132
- "opengateway/anthropic/claude-sonnet-5",
133
- "opengateway/anthropic/claude-opus-4-8",
134
- "opengateway/moonshotai/kimi-k2.6",
135
- "opengateway/minimax/MiniMax-M3"
125
+ "opengateway/openai/gpt-5.4-nano"
136
126
  ]
137
127
  },
138
128
  {
@@ -190,12 +180,7 @@
190
180
  "moonshot/kimi-k2.6",
191
181
  "moonshot/kimi-k2.5",
192
182
  "moonshot-coding/kimi-for-coding",
193
- "opengateway/openai/gpt-5.4-nano",
194
- "opengateway/openai/gpt-5.5",
195
- "opengateway/anthropic/claude-sonnet-5",
196
- "opengateway/anthropic/claude-opus-4-8",
197
- "opengateway/moonshotai/kimi-k2.6",
198
- "opengateway/minimax/MiniMax-M3"
183
+ "opengateway/openai/gpt-5.4-nano"
199
184
  ]
200
185
  },
201
186
  {
@@ -251,12 +236,7 @@
251
236
  "moonshot/kimi-k2.6",
252
237
  "moonshot/kimi-k2.5",
253
238
  "moonshot-coding/kimi-for-coding",
254
- "opengateway/openai/gpt-5.4-nano",
255
- "opengateway/openai/gpt-5.5",
256
- "opengateway/anthropic/claude-sonnet-5",
257
- "opengateway/anthropic/claude-opus-4-8",
258
- "opengateway/moonshotai/kimi-k2.6",
259
- "opengateway/minimax/MiniMax-M3"
239
+ "opengateway/openai/gpt-5.4-nano"
260
240
  ]
261
241
  },
262
242
  {
@@ -313,12 +293,7 @@
313
293
  "moonshot/kimi-k2.6",
314
294
  "moonshot/kimi-k2.5",
315
295
  "moonshot-coding/kimi-for-coding",
316
- "opengateway/openai/gpt-5.4-nano",
317
- "opengateway/openai/gpt-5.5",
318
- "opengateway/anthropic/claude-sonnet-5",
319
- "opengateway/anthropic/claude-opus-4-8",
320
- "opengateway/moonshotai/kimi-k2.6",
321
- "opengateway/minimax/MiniMax-M3"
296
+ "opengateway/openai/gpt-5.4-nano"
322
297
  ]
323
298
  },
324
299
  {