typeclaw 0.46.0 → 0.46.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.
- package/README.md +1 -1
- package/package.json +2 -2
- package/src/agent/multimodal/looker.ts +11 -1
- package/src/agent/network/safe-http.ts +17 -8
- package/src/agent/plugin-tools.ts +1 -3
- package/src/agent/tool-file-safety.ts +414 -145
- package/src/agent/tools/webfetch/fetch.ts +22 -2
- package/src/agent/tools/webfetch/strategies/jq.ts +1 -2
- package/src/agent/tools/webfetch/strategies/readability.ts +39 -16
- package/src/agent/tools/webfetch/strategies/selector.ts +4 -2
- package/src/agent/tools/webfetch/strategies/snapshot.ts +3 -2
- package/src/agent/tools/webfetch/tool.ts +3 -3
- package/src/agent/tools-without-local-file-operands.ts +9 -6
- package/src/bundled-plugins/backup/README.md +23 -10
- package/src/bundled-plugins/backup/git-auth.ts +6 -4
- package/src/bundled-plugins/backup/index.ts +104 -47
- package/src/bundled-plugins/backup/runner.ts +102 -5
- package/src/bundled-plugins/github-cli-auth/git-askpass.ts +74 -26
- package/src/bundled-plugins/github-cli-auth/git-command.ts +224 -36
- package/src/bundled-plugins/github-cli-auth/graphql-auth-nudge.ts +9 -9
- package/src/bundled-plugins/github-cli-auth/index.ts +110 -31
- package/src/bundled-plugins/github-cli-auth/token-class.ts +4 -6
- package/src/bundled-plugins/memory/README.md +9 -0
- package/src/bundled-plugins/memory/vector/embed-threads.ts +36 -0
- package/src/bundled-plugins/memory/vector/embedder.ts +19 -1
- package/src/bundled-plugins/memory/vector/hybrid.ts +10 -2
- package/src/bundled-plugins/memory/vector/store.ts +21 -9
- package/src/bundled-plugins/researcher/write-report.ts +3 -3
- package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +8 -3
- package/src/bundled-plugins/security/policies/private-surface-read.ts +616 -50
- package/src/bundled-plugins/security/policies/ssrf.ts +119 -34
- package/src/channels/adapters/github/inbound.ts +11 -0
- package/src/channels/adapters/github/index.ts +48 -54
- package/src/channels/adapters/github/reconcile-cooldown-store.ts +178 -0
- package/src/channels/adapters/github/reconcile-open-prs.ts +31 -0
- package/src/channels/adapters/slack-bot-edit.ts +85 -20
- package/src/channels/adapters/slack-bot.ts +7 -2
- package/src/channels/adapters/slack-format.ts +245 -0
- package/src/channels/github-token-bridge.ts +2 -3
- package/src/cli/inspect.ts +16 -0
- package/src/container/docker-app.ts +42 -13
- package/src/container/shared.ts +19 -6
- package/src/container/start.ts +13 -0
- package/src/cron/bridge.ts +9 -2
- package/src/doctor/checks.ts +5 -2
- package/src/git/bound-gc-config.ts +82 -0
- package/src/hostd/spawn.ts +133 -47
- package/src/init/checkpoint.ts +4 -4
- package/src/init/dockerfile.ts +100 -88
- package/src/init/gitignore.ts +5 -6
- package/src/init/run-bun-install.ts +16 -2
- package/src/init/validate-api-key.ts +1 -0
- package/src/inspect/item-list.ts +12 -6
- package/src/inspect/replay.ts +21 -9
- package/src/inspect/session-list.ts +71 -33
- package/src/mcp/tools.ts +1 -0
- package/src/network/internal-destinations.ts +267 -0
- package/src/permissions/permissions.ts +93 -2
- package/src/plugin/types.ts +3 -2
- package/src/role-claim/code.ts +9 -5
- package/src/run/index.ts +45 -36
- package/src/sandbox/canonical-secrets.ts +6 -0
- package/src/sandbox/env-exposure.ts +18 -15
- package/src/sandbox/index.ts +1 -0
- package/src/sandbox/policy.ts +5 -3
- package/src/sandbox/privileged-runtime.ts +1 -0
- package/src/sandbox/symlinks.ts +1 -1
- package/src/secrets/export-claude-credentials-file.ts +13 -22
- package/src/secrets/export-codex-auth-file.ts +12 -28
- package/src/skills/typeclaw-config/SKILL.md +22 -6
- package/src/skills/typeclaw-permissions/SKILL.md +22 -9
- package/src/skills/typeclaw-plugins/SKILL.md +37 -0
- package/src/usage/scan.ts +11 -2
- package/typeclaw.schema.json +5 -0
- package/src/git/secret-history.ts +0 -371
package/src/container/start.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { tmpdir } from 'node:os'
|
|
|
5
5
|
import { isAbsolute, join, relative, resolve } from 'node:path'
|
|
6
6
|
|
|
7
7
|
import { expandMountPath, loadConfigSync, withDefaultPlugins, type Config, type PortForward } from '@/config'
|
|
8
|
+
import { applyBoundGcConfig } from '@/git/bound-gc-config'
|
|
8
9
|
import { commitGitignoreWithUntracks, untrackTrulyIgnoredFiles } from '@/git/reconcile-ignored'
|
|
9
10
|
import { commitSystemFile as commitSystemFileShared } from '@/git/system-commit'
|
|
10
11
|
import { send as sendToDaemon } from '@/hostd/client'
|
|
@@ -238,6 +239,15 @@ export async function start({
|
|
|
238
239
|
// that would surprise a user invoking `compose start` against a partially-up
|
|
239
240
|
// tree.
|
|
240
241
|
const state = await inspectContainer(exec, containerName)
|
|
242
|
+
|
|
243
|
+
// Bound gc/repack memory even when start() is an already-running no-op below:
|
|
244
|
+
// the running agent's backup keeps committing, so it must not keep using the
|
|
245
|
+
// unbounded Git defaults until a full stop/restart. This is a machine-local
|
|
246
|
+
// `git config` write (never committed, no template/side effect), so unlike the
|
|
247
|
+
// Dockerfile/.gitignore/package.json refreshes it is safe before the running
|
|
248
|
+
// return — no surprise for `compose start` against a partially-up tree.
|
|
249
|
+
await applyBoundGcConfig(cwd)
|
|
250
|
+
|
|
241
251
|
if (state.exists && state.running) {
|
|
242
252
|
return await reportAlreadyRunning(exec, cwd, containerName)
|
|
243
253
|
}
|
|
@@ -262,6 +272,9 @@ export async function start({
|
|
|
262
272
|
// refreshGitignore call below reads typeclaw.json and will incidentally
|
|
263
273
|
// trigger the migration commit if the file was legacy.
|
|
264
274
|
await refreshGitignore(cwd)
|
|
275
|
+
// Machine-local `git config` that bounds gc/repack memory on the agent repo.
|
|
276
|
+
// Runs alongside the other managed-file refreshes; not committed (local scope).
|
|
277
|
+
await applyBoundGcConfig(cwd)
|
|
265
278
|
const pkgRefresh = await refreshPackageJson(cwd)
|
|
266
279
|
const { untracked } = await untrackTrulyIgnoredFiles(cwd, (await loadTypeclawConfig(cwd)).git.ignore.append)
|
|
267
280
|
if (untracked.length > 0) {
|
package/src/cron/bridge.ts
CHANGED
|
@@ -5,6 +5,12 @@ export type CronListBridgeOptions = {
|
|
|
5
5
|
cwd: string
|
|
6
6
|
url?: string
|
|
7
7
|
timeoutMs?: number
|
|
8
|
+
// Budget for the WS handshake only. Defaults to timeoutMs so production
|
|
9
|
+
// behavior is unchanged. Split out so the reply-timeout path can be tested
|
|
10
|
+
// with a tight reply budget while giving the connect phase enough slack to
|
|
11
|
+
// survive CPU contention under parallel tests — a slow handshake must not
|
|
12
|
+
// masquerade as a reply timeout (or, worse, surface as `unreachable`).
|
|
13
|
+
connectTimeoutMs?: number
|
|
8
14
|
// Injected for tests so the in-container short-circuit can be exercised
|
|
9
15
|
// without polluting process.env. Production callers omit this and the
|
|
10
16
|
// bridge reads from process.env directly.
|
|
@@ -35,6 +41,7 @@ type DialResult = { kind: 'ok'; ws: WebSocket; timeoutMs: number } | { kind: 'un
|
|
|
35
41
|
|
|
36
42
|
async function dial(opts: CronListBridgeOptions): Promise<DialResult> {
|
|
37
43
|
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
44
|
+
const connectTimeoutMs = opts.connectTimeoutMs ?? timeoutMs
|
|
38
45
|
let url = opts.url
|
|
39
46
|
if (url === undefined) {
|
|
40
47
|
try {
|
|
@@ -74,8 +81,8 @@ async function dial(opts: CronListBridgeOptions): Promise<DialResult> {
|
|
|
74
81
|
try {
|
|
75
82
|
ws.close()
|
|
76
83
|
} catch {}
|
|
77
|
-
reject(new Error(`timed out connecting to ${displayUrl} after ${
|
|
78
|
-
},
|
|
84
|
+
reject(new Error(`timed out connecting to ${displayUrl} after ${connectTimeoutMs}ms`))
|
|
85
|
+
}, connectTimeoutMs)
|
|
79
86
|
ws.addEventListener('open', onOpen, { once: true })
|
|
80
87
|
ws.addEventListener('error', onError, { once: true })
|
|
81
88
|
ws.addEventListener('close', onClose, { once: true })
|
package/src/doctor/checks.ts
CHANGED
|
@@ -61,12 +61,15 @@ function dockerDaemon(exec: DockerExec): DoctorCheck {
|
|
|
61
61
|
if (result.ok) return { status: 'ok', message: 'docker info responded' }
|
|
62
62
|
return {
|
|
63
63
|
status: 'error',
|
|
64
|
-
message: result.reason === 'binary-missing' ? 'docker binary missing on $PATH' : 'docker daemon
|
|
64
|
+
message: result.reason === 'binary-missing' ? 'docker binary missing on $PATH' : 'docker daemon not reachable',
|
|
65
65
|
details: [result.detail],
|
|
66
66
|
fix:
|
|
67
67
|
result.reason === 'binary-missing'
|
|
68
68
|
? { description: 'Install Docker (Docker Desktop, OrbStack, or docker-ce).' }
|
|
69
|
-
: {
|
|
69
|
+
: {
|
|
70
|
+
description:
|
|
71
|
+
'Start the Docker runtime (Docker Desktop, OrbStack, or `systemctl start docker`). If it is already running, check `docker context ls`, `DOCKER_CONTEXT`, and `DOCKER_HOST`.',
|
|
72
|
+
},
|
|
70
73
|
}
|
|
71
74
|
},
|
|
72
75
|
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { hooklessGitArgs } from './hookless'
|
|
2
|
+
import { resolveAgentGit } from './resolve-agent-git'
|
|
3
|
+
|
|
4
|
+
// Machine-local `git config` written into the agent repo on every `typeclaw
|
|
5
|
+
// start` to bound git's gc/repack/pack-objects memory. Agents force-commit
|
|
6
|
+
// sessions/ + memory/, so packs grow to GB scale; on such a repo git's default
|
|
7
|
+
// auto-gc was measured at ~1.8GB RSS and OOM-killed the container. These keys cap
|
|
8
|
+
// the peak (git-config(1): peak ≈ pack.threads × pack.windowMemory + overhead).
|
|
9
|
+
// Do NOT "modernize" any back to a git default without re-checking the OOM:
|
|
10
|
+
// gc.auto/autoPackLimit=0 no surprise full repack from the backup's `git
|
|
11
|
+
// commit`; reclamation moves to the idle backup path
|
|
12
|
+
// (see bound-git-maintenance / Fix 2).
|
|
13
|
+
// pack.threads=1 default auto-detects to CPU count; windowMemory is
|
|
14
|
+
// PER THREAD, so N cores = N× the spike.
|
|
15
|
+
// pack.windowMemory=64m default is UNLIMITED — the primary per-thread bound.
|
|
16
|
+
// pack.deltaCacheSize=1 virtually disables the 256MB write-phase delta cache.
|
|
17
|
+
// core.bigFileThreshold=10m load-bearing for append-only JSONL: bigger objects
|
|
18
|
+
// store plain-deflated with NO delta attempt, keeping
|
|
19
|
+
// transcripts out of the memory-heavy delta pipeline.
|
|
20
|
+
// core.multiPackIndex=true required for Fix 2's `maintenance incremental-repack`.
|
|
21
|
+
export const BOUND_GC_CONFIG: ReadonlyArray<readonly [key: string, value: string]> = [
|
|
22
|
+
['gc.auto', '0'],
|
|
23
|
+
['gc.autoPackLimit', '0'],
|
|
24
|
+
['gc.bigPackThreshold', '100m'],
|
|
25
|
+
['pack.threads', '1'],
|
|
26
|
+
['pack.windowMemory', '64m'],
|
|
27
|
+
['pack.deltaCacheSize', '1'],
|
|
28
|
+
['pack.window', '5'],
|
|
29
|
+
['pack.depth', '10'],
|
|
30
|
+
['core.bigFileThreshold', '10m'],
|
|
31
|
+
['core.deltaBaseCacheLimit', '16m'],
|
|
32
|
+
['core.multiPackIndex', 'true'],
|
|
33
|
+
] as const
|
|
34
|
+
|
|
35
|
+
// Writes BOUND_GC_CONFIG into the agent repo's machine-local git config.
|
|
36
|
+
//
|
|
37
|
+
// Best-effort, exactly like untrackTrulyIgnoredFiles / commitSystemFile: no-ops
|
|
38
|
+
// when the folder is not a git repo or Bun is missing, and NEVER throws — start()
|
|
39
|
+
// hygiene must not block boot. These are `git config` (local scope) writes: they
|
|
40
|
+
// live in .git/config, are not tracked, not committed, and are idempotent —
|
|
41
|
+
// re-running just re-sets the same values.
|
|
42
|
+
//
|
|
43
|
+
// Returns the number of keys successfully written (0 when skipped) so callers /
|
|
44
|
+
// tests can assert the write happened without coupling to git internals.
|
|
45
|
+
export async function applyBoundGcConfig(cwd: string): Promise<{ applied: number }> {
|
|
46
|
+
const bun = getBun()
|
|
47
|
+
if (!bun) return { applied: 0 }
|
|
48
|
+
const repo = resolveAgentGit(cwd)
|
|
49
|
+
if (!repo) return { applied: 0 }
|
|
50
|
+
|
|
51
|
+
let applied = 0
|
|
52
|
+
for (const [key, value] of BOUND_GC_CONFIG) {
|
|
53
|
+
if (await setLocalConfig(bun, cwd, repo.gitArgs, key, value)) applied += 1
|
|
54
|
+
}
|
|
55
|
+
return { applied }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function setLocalConfig(
|
|
59
|
+
bun: BunLike,
|
|
60
|
+
cwd: string,
|
|
61
|
+
gitArgs: readonly string[],
|
|
62
|
+
key: string,
|
|
63
|
+
value: string,
|
|
64
|
+
): Promise<boolean> {
|
|
65
|
+
try {
|
|
66
|
+
const proc = bun.spawn({
|
|
67
|
+
cmd: ['git', ...hooklessGitArgs([...gitArgs, 'config', '--local', key, value])],
|
|
68
|
+
cwd,
|
|
69
|
+
stdout: 'pipe',
|
|
70
|
+
stderr: 'pipe',
|
|
71
|
+
})
|
|
72
|
+
return (await proc.exited) === 0
|
|
73
|
+
} catch {
|
|
74
|
+
return false
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
type BunLike = { spawn: typeof Bun.spawn }
|
|
79
|
+
|
|
80
|
+
function getBun(): BunLike | undefined {
|
|
81
|
+
return (globalThis as { Bun?: BunLike }).Bun
|
|
82
|
+
}
|
package/src/hostd/spawn.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { existsSync } from 'node:fs'
|
|
2
|
-
import { open, readFile, unlink, writeFile } from 'node:fs/promises'
|
|
2
|
+
import { lstat, open, readFile, unlink, writeFile } from 'node:fs/promises'
|
|
3
|
+
|
|
4
|
+
import lockfile from 'proper-lockfile'
|
|
3
5
|
|
|
4
6
|
import { isWindows } from '@/shared'
|
|
5
7
|
|
|
@@ -14,6 +16,9 @@ export type EnsureDaemonOptions = {
|
|
|
14
16
|
// Test seam: tests inject a deterministic version probe + respawn so the
|
|
15
17
|
// unit test can exercise the drift path without spawning a real daemon.
|
|
16
18
|
expectedVersion?: string
|
|
19
|
+
// Test seam: parks execution inside the spawn lock, just before spawning, so a
|
|
20
|
+
// test can prove a concurrent caller cannot enter the critical section.
|
|
21
|
+
onSpawnEnter?: () => Promise<void>
|
|
17
22
|
}
|
|
18
23
|
|
|
19
24
|
export type EnsureDaemonResult =
|
|
@@ -23,6 +28,18 @@ export type EnsureDaemonResult =
|
|
|
23
28
|
const DEFAULT_SPAWN_TIMEOUT_MS = 5_000
|
|
24
29
|
const SHUTDOWN_TIMEOUT_MS = 5_000
|
|
25
30
|
const POLL_INTERVAL_MS = 50
|
|
31
|
+
const EXIT_SETTLE_MS = 500
|
|
32
|
+
// proper-lockfile refreshes the held lock's mtime every `stale/2` ms, so a lock
|
|
33
|
+
// held across the full spawn (readiness poll + EXIT_SETTLE_MS grace) is never
|
|
34
|
+
// seen as stale by a contender — only a crashed holder, whose refresh timer
|
|
35
|
+
// died with it, is reclaimed. Mirrors the models/secrets locks' 30s ceiling.
|
|
36
|
+
const LOCK_STALE_MS = 30_000
|
|
37
|
+
const LOCK_RETRY_BACKOFF = {
|
|
38
|
+
factor: 1,
|
|
39
|
+
minTimeout: POLL_INTERVAL_MS,
|
|
40
|
+
maxTimeout: POLL_INTERVAL_MS,
|
|
41
|
+
randomize: false,
|
|
42
|
+
} as const
|
|
26
43
|
|
|
27
44
|
export async function ensureDaemon(opts: EnsureDaemonOptions): Promise<EnsureDaemonResult> {
|
|
28
45
|
if (await isDaemonReachable()) {
|
|
@@ -36,13 +53,13 @@ export async function ensureDaemon(opts: EnsureDaemonOptions): Promise<EnsureDae
|
|
|
36
53
|
return { ok: false, reason: 'daemon version drifted but shutdown request did not complete' }
|
|
37
54
|
}
|
|
38
55
|
await ensureDirs()
|
|
39
|
-
const respawn = await
|
|
56
|
+
const respawn = await spawnUnderLock(opts)
|
|
40
57
|
if (!respawn.ok) return respawn
|
|
41
58
|
return { ...respawn, respawned: true }
|
|
42
59
|
}
|
|
43
60
|
|
|
44
61
|
await ensureDirs()
|
|
45
|
-
const result = await
|
|
62
|
+
const result = await spawnUnderLock(opts)
|
|
46
63
|
if (!result.ok) return result
|
|
47
64
|
return { ...result, respawned: false }
|
|
48
65
|
}
|
|
@@ -90,19 +107,20 @@ async function requestShutdownAndWait(): Promise<boolean> {
|
|
|
90
107
|
|
|
91
108
|
type SpawnAttemptResult = { ok: true; pid: number; spawned: boolean; httpPort: number } | { ok: false; reason: string }
|
|
92
109
|
|
|
93
|
-
async function
|
|
94
|
-
const lock = await
|
|
95
|
-
if (lock.kind === '
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
if (
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
110
|
+
async function spawnUnderLock(opts: EnsureDaemonOptions): Promise<SpawnAttemptResult> {
|
|
111
|
+
const lock = await acquireSpawnLock(opts.spawnTimeoutMs ?? DEFAULT_SPAWN_TIMEOUT_MS)
|
|
112
|
+
if (lock.kind === 'contended') {
|
|
113
|
+
// Another caller holds the spawn lock. If a daemon came up meanwhile, reuse
|
|
114
|
+
// it; otherwise that caller is still mid-spawn, so back off without racing a
|
|
115
|
+
// second spawn. proper-lockfile reclaims a crashed holder's lock on its own
|
|
116
|
+
// (its mtime refresh timer dies with the process), so there's no lock to
|
|
117
|
+
// clear here — the ownership-unsafe manual clear is gone.
|
|
118
|
+
if (await isDaemonReachable()) {
|
|
119
|
+
const httpPort = await readHttpPort()
|
|
120
|
+
if (httpPort === null) return { ok: false, reason: 'daemon did not report an HTTP control port' }
|
|
121
|
+
return { ok: true, pid: await readPidQuiet(), spawned: false, httpPort }
|
|
122
|
+
}
|
|
123
|
+
return { ok: false, reason: 'another daemon spawn is in progress' }
|
|
106
124
|
}
|
|
107
125
|
|
|
108
126
|
try {
|
|
@@ -121,9 +139,10 @@ async function ensureDaemonWithRetry(opts: EnsureDaemonOptions, retriesLeft: num
|
|
|
121
139
|
if (ready === null) return { ok: false, reason: 'daemon spawned but did not become reachable yet' }
|
|
122
140
|
return { ok: true, pid: existingPid, spawned: false, httpPort: ready }
|
|
123
141
|
}
|
|
142
|
+
await opts.onSpawnEnter?.()
|
|
124
143
|
return await spawnDaemonDetached(opts)
|
|
125
144
|
} finally {
|
|
126
|
-
await
|
|
145
|
+
await lock.release()
|
|
127
146
|
}
|
|
128
147
|
}
|
|
129
148
|
|
|
@@ -196,10 +215,18 @@ async function spawnDaemonDetached(opts: EnsureDaemonOptions): Promise<SpawnAtte
|
|
|
196
215
|
// Timed out waiting for readiness. A still-running child is "slow-booting",
|
|
197
216
|
// not "wedged" — killing it would throw away a daemon that's about to come up
|
|
198
217
|
// and force every caller into a respawn loop. Only reap a child that already
|
|
199
|
-
// EXITED
|
|
200
|
-
//
|
|
201
|
-
//
|
|
202
|
-
//
|
|
218
|
+
// EXITED: that's a genuine failure with a dangling pidfile to clean. A
|
|
219
|
+
// live-but-not-ready child is left running so the caller can re-probe it (see
|
|
220
|
+
// registerWithDaemon's retry) — the next ensureDaemon() fast-paths through
|
|
221
|
+
// isDaemonReachable() once its socket binds.
|
|
222
|
+
//
|
|
223
|
+
// `proc.exitCode` is a non-blocking snapshot, so a child that fails fast (e.g.
|
|
224
|
+
// a bad CLI entry) can still read as `null` here if the readiness deadline
|
|
225
|
+
// lands in the narrow window between the process exiting and Bun reaping it.
|
|
226
|
+
// Give it a bounded grace to settle by racing `proc.exited`; this makes the
|
|
227
|
+
// exited-vs-slow-booting classification deterministic instead of dependent on
|
|
228
|
+
// scheduler timing, without ever killing a still-live child.
|
|
229
|
+
if (proc.exitCode === null) await settleExit(proc, EXIT_SETTLE_MS)
|
|
203
230
|
if (proc.exitCode !== null) {
|
|
204
231
|
try {
|
|
205
232
|
const raw = await readFile(pidfilePath(), 'utf8').catch(() => '')
|
|
@@ -210,40 +237,99 @@ async function spawnDaemonDetached(opts: EnsureDaemonOptions): Promise<SpawnAtte
|
|
|
210
237
|
return { ok: false, reason: 'daemon spawned but did not become reachable yet' }
|
|
211
238
|
}
|
|
212
239
|
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
240
|
+
async function settleExit(proc: ReturnType<typeof Bun.spawn>, graceMs: number): Promise<void> {
|
|
241
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
242
|
+
const grace = new Promise<void>((resolve) => {
|
|
243
|
+
timer = setTimeout(resolve, graceMs)
|
|
244
|
+
})
|
|
245
|
+
try {
|
|
246
|
+
await Promise.race([proc.exited.then(() => undefined), grace])
|
|
247
|
+
} finally {
|
|
248
|
+
if (timer) clearTimeout(timer)
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
type LockResult = { kind: 'acquired'; release: () => Promise<void> } | { kind: 'contended' }
|
|
219
253
|
|
|
220
|
-
async function
|
|
254
|
+
async function acquireSpawnLock(timeoutMs: number): Promise<LockResult> {
|
|
221
255
|
const path = lockfilePath()
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
256
|
+
await clearLegacyFileLock(path)
|
|
257
|
+
const retries = Math.max(1, Math.ceil(timeoutMs / POLL_INTERVAL_MS))
|
|
258
|
+
try {
|
|
259
|
+
const release = await lockfile.lock(path, {
|
|
260
|
+
lockfilePath: path,
|
|
261
|
+
realpath: false,
|
|
262
|
+
stale: LOCK_STALE_MS,
|
|
263
|
+
retries: { ...LOCK_RETRY_BACKOFF, retries },
|
|
264
|
+
})
|
|
265
|
+
return { kind: 'acquired', release: () => release().catch(() => {}) }
|
|
266
|
+
} catch (error) {
|
|
267
|
+
if (errorCode(error) === 'ELOCKED') return { kind: 'contended' }
|
|
268
|
+
throw error
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// The pre-proper-lockfile daemon left the lock as a regular FILE at this path.
|
|
273
|
+
// proper-lockfile locks by creating a DIRECTORY there, so a stale legacy file
|
|
274
|
+
// makes mkdir fail EEXIST (reported as ELOCKED) while its own reclaim rmdir
|
|
275
|
+
// fails ENOTDIR — wedging startup forever after an upgrade. Clear an abandoned
|
|
276
|
+
// legacy file, but never a live one: a co-existing old-binary caller mid-spawn
|
|
277
|
+
// may hold it before its daemon is reachable. The recorded pid is only a hint
|
|
278
|
+
// (pids get recycled), so it's trusted only while the file is fresh; an aged
|
|
279
|
+
// file is reclaimed regardless. Directories (a live proper-lockfile lock) and
|
|
280
|
+
// symlinks are left untouched.
|
|
281
|
+
async function clearLegacyFileLock(path: string): Promise<void> {
|
|
282
|
+
let observed: Awaited<ReturnType<typeof lstat>>
|
|
283
|
+
try {
|
|
284
|
+
observed = await lstat(path)
|
|
285
|
+
} catch (error) {
|
|
286
|
+
if (errorCode(error) === 'ENOENT') return
|
|
287
|
+
throw error
|
|
288
|
+
}
|
|
289
|
+
if (!observed.isFile()) return
|
|
290
|
+
|
|
291
|
+
let raw: string
|
|
292
|
+
try {
|
|
293
|
+
raw = await readFile(path, 'utf8')
|
|
294
|
+
} catch (error) {
|
|
295
|
+
const code = errorCode(error)
|
|
296
|
+
if (code === 'ENOENT' || code === 'EISDIR') return
|
|
297
|
+
throw error
|
|
233
298
|
}
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
299
|
+
|
|
300
|
+
const pid = Number.parseInt(raw.trim(), 10)
|
|
301
|
+
const hasValidPid = Number.isSafeInteger(pid) && pid > 0
|
|
302
|
+
const isFresh = Date.now() - observed.mtimeMs < LOCK_STALE_MS
|
|
303
|
+
// A bare pid is only trustworthy briefly: pid reuse would otherwise let an
|
|
304
|
+
// abandoned legacy file (whose recorded pid the OS reassigned to an unrelated
|
|
305
|
+
// process) look "held" forever. So preserve only a FRESH file that is either
|
|
306
|
+
// held by a live pid or still within the grace for a not-yet-written pid; once
|
|
307
|
+
// the file ages past LOCK_STALE_MS, reclaim it regardless of pid liveness.
|
|
308
|
+
if (isFresh && (!hasValidPid || processExists(pid))) return
|
|
309
|
+
|
|
237
310
|
try {
|
|
311
|
+
const current = await lstat(path)
|
|
312
|
+
if (!current.isFile() || current.dev !== observed.dev || current.ino !== observed.ino) return
|
|
238
313
|
await unlink(path)
|
|
239
|
-
} catch {
|
|
240
|
-
|
|
314
|
+
} catch (error) {
|
|
315
|
+
const code = errorCode(error)
|
|
316
|
+
if (code === 'ENOENT' || code === 'EISDIR' || code === 'EPERM') return
|
|
317
|
+
throw error
|
|
318
|
+
}
|
|
241
319
|
}
|
|
242
320
|
|
|
243
|
-
|
|
321
|
+
function processExists(pid: number): boolean {
|
|
244
322
|
try {
|
|
245
|
-
|
|
246
|
-
|
|
323
|
+
process.kill(pid, 0)
|
|
324
|
+
return true
|
|
325
|
+
} catch (error) {
|
|
326
|
+
// EPERM means the process exists but we may not signal it — still alive.
|
|
327
|
+
return errorCode(error) !== 'ESRCH'
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function errorCode(error: unknown): string | undefined {
|
|
332
|
+
return typeof error === 'object' && error !== null ? (error as { code?: string }).code : undefined
|
|
247
333
|
}
|
|
248
334
|
|
|
249
335
|
async function readPidQuiet(): Promise<number> {
|
package/src/init/checkpoint.ts
CHANGED
|
@@ -13,10 +13,10 @@ import {
|
|
|
13
13
|
|
|
14
14
|
// In-folder scratch for an in-progress `typeclaw init`, co-located with the
|
|
15
15
|
// agent it describes. Lives under the agent's `.typeclaw/` (the same gitignored
|
|
16
|
-
// local-scratch dir
|
|
17
|
-
// the half-init folder is deleted, survives a folder
|
|
18
|
-
// inspectable right next to the thing being resumed.
|
|
19
|
-
// `TRULY_IGNORED_PATTERNS`; never committed.
|
|
16
|
+
// local-scratch dir that may contain orphaned legacy runtime-HOME credentials),
|
|
17
|
+
// so it self-cleans when the half-init folder is deleted, survives a folder
|
|
18
|
+
// rename mid-init, and is inspectable right next to the thing being resumed.
|
|
19
|
+
// Gitignored via `TRULY_IGNORED_PATTERNS`; never committed.
|
|
20
20
|
export const INIT_CHECKPOINT_PATH = join('.typeclaw', 'init-progress.json')
|
|
21
21
|
|
|
22
22
|
export const WIZARD_CHECKPOINT_VERSION = 1
|