Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions packages/core/src/v1/config/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,21 @@ const KNOWN_KEYS = new Set([
"tools",
])

// altimate_change start — callers can name the top-level keys that `normalize` folds into `options`
// The fold is a published contract: `AgentConfig` allows additional properties, an agent's
// `audience` is read from `options`, and legacy markdown agents carry provider request options
// as top-level keys that `migrateAgent` moves into `request.body`. It stays; the loaders log
// the keys it folded so a typo (`budget` for `steps`) is no longer silent.
/** Top-level keys the agent schema interprets; every other top-level key is folded into `options`. */
export const knownKeys: readonly string[] = [...KNOWN_KEYS]

/** The top-level keys of a raw agent config that `normalize` folds into `options`. */
export function unknownKeys(agent: unknown): string[] {
if (typeof agent !== "object" || agent === null || Array.isArray(agent)) return []
return Object.keys(agent).filter((key) => !KNOWN_KEYS.has(key))
}
// altimate_change end

const normalize = (agent: Schema.Schema.Type<typeof AgentSchema>): Schema.Schema.Type<typeof AgentSchema> => {
const options: Record<string, unknown> = { ...agent.options }
for (const [key, value] of Object.entries(agent)) {
Expand Down
77 changes: 77 additions & 0 deletions packages/core/test/config/agent-v1-keys.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { describe, expect, test } from "bun:test"
import { Schema } from "effect"
import { ConfigAgentV1 } from "../../src/v1/config/agent"

const decode = Schema.decodeUnknownSync(ConfigAgentV1.Info)

describe("ConfigAgentV1 top-level keys", () => {
test("a known key is accepted as itself", () => {
const agent = decode({ model: "test/model", steps: 3, description: "Known keys only" })
expect(agent).toMatchObject({ model: "test/model", steps: 3, description: "Known keys only" })
expect(agent.options).toEqual({})
expect(ConfigAgentV1.unknownKeys({ model: "test/model", steps: 3 })).toEqual([])
})

test("an unknown top-level key is folded into options and can be named", () => {
const raw = { model: "test/model", budget: 5, audience: "executive" }
const agent = decode(raw)
expect(agent.options).toEqual({ budget: 5, audience: "executive" })
expect(agent).not.toHaveProperty("steps")
expect(ConfigAgentV1.unknownKeys(raw)).toEqual(["budget", "audience"])
})

test("keys nested under options keep working and are not reported", () => {
const raw = { model: "test/model", options: { audience: "executive", reasoningEffort: "high" } }
const agent = decode(raw)
expect(agent.options).toEqual({ audience: "executive", reasoningEffort: "high" })
expect(ConfigAgentV1.unknownKeys(raw)).toEqual([])
})

test("the known-key list is the schema's own", () => {
expect([...ConfigAgentV1.knownKeys].sort()).toEqual(
[
"name",
"model",
"variant",
"prompt",
"description",
"temperature",
"top_p",
"mode",
"hidden",
"color",
"steps",
"maxSteps",
"options",
"permission",
"disable",
"tools",
].sort(),
)
expect(ConfigAgentV1.unknownKeys(undefined)).toEqual([])
expect(ConfigAgentV1.unknownKeys(["budget"])).toEqual([])
})

test("every field the schema interprets is decoded as itself, not folded into options", () => {
const raw = {
name: "reviewer",
model: "test/model",
variant: "high",
prompt: "Review the change.",
description: "Reviews changes",
temperature: 0.2,
top_p: 0.9,
mode: "subagent",
hidden: true,
color: "#FF5733",
steps: 3,
maxSteps: 4,
options: { audience: "executive" },
permission: { edit: "deny" },
disable: false,
tools: { bash: false },
}
expect(ConfigAgentV1.unknownKeys(raw)).toEqual([])
expect(decode(raw).options).toEqual({ audience: "executive" })
})
})
82 changes: 61 additions & 21 deletions packages/opencode/bin/altimate-code
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,15 @@ function findAllNodeModules(startDir) {
return paths
}

function isExecutableFile(file) {
try {
fs.accessSync(file, fs.constants.X_OK)
return fs.statSync(file).isFile()
} catch {
return false
}
}

function run(target) {
// Resolve NODE_PATH so the compiled Bun binary can find external packages
// installed alongside the wrapper (e.g. @altimateai/altimate-core NAPI module).
Expand Down Expand Up @@ -54,37 +63,68 @@ function run(target) {
}
} catch {
// realpathSync failed (e.g. target doesn't exist) — continue without
// NODE_PATH; spawnSync will report the missing binary via result.error.
// NODE_PATH; spawn will report the missing binary via the "error" event.
}

// Become the binary where node can (POSIX, node >= 22.15 / 23.11): one
// process, so a signal sent to this pid or to its process group reaches the
// binary exactly once, as if it had been started directly, and the caller
// sees the binary's own exit status, a signal death included. A failed
// execve aborts node instead of throwing, so only an executable file is
// exec'd; anything else falls through to spawn, which reports it as before.
if (typeof process.execve === "function" && isExecutableFile(target)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Critical: on Windows with Node 22.15 or later the wrapper crashes before it reaches spawn. Node defines process.execve on every platform (lib/internal/bootstrap/node.js assigns it unconditionally) and throws ERR_FEATURE_UNAVAILABLE_ON_PLATFORM from inside it on win32. On Windows fs.accessSync(X_OK) behaves like F_OK, so the installed .exe passes isExecutableFile, and every altimate-code invocation (the TUI, run, serve, every subcommand) exits 1 with a stack trace. Repro on macOS with a preload that sets process.platform to win32: on Node 26.8.1 and 22.22.2, head prints TypeError [ERR_FEATURE_UNAVAILABLE_ON_PLATFORM]: The feature process.execve is unavailable on the current platform at altimate-code:76, while base runs the binary. No CI job runs this wrapper on Windows, and the test file skips win32. Fix: gate on process.platform !== "win32" as well (or wrap the call in try for the synchronous throw), and add a test that simulates win32 with a preload.

process.execve(target, [target, ...process.argv.slice(2)], env)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor (not blocking: a broken-install edge; a correct install never hits it). The X_OK and isFile check does not make execve safe. An executable file can still fail with ENOEXEC (a truncated or wrong-format binary), ENOENT (a missing ELF interpreter, e.g. a glibc build picked by the musl fallback list) or ETXTBSY. Node 22.x then aborts (exit 134, possibly a core dump) and Node 26 throws an uncaught stack trace. Base printed spawnSync … ENOENT / ENOEXEC and exited 1. Repro: an ALTIMATE_CODE_BIN_PATH pointing to a #!/nonexistent/interp script, or to 10 bytes of \x7fELF garbage. The comment says that "anything else falls through to spawn", but these do not. Consider a cheap header check (ELF/Mach-O magic or #!), or say in the comment that these failures are fatal.

}

const result = childProcess.spawnSync(target, process.argv.slice(2), {
// Otherwise spawn asynchronously and forward termination signals: with
// spawnSync a `kill <wrapper pid>` ended the wrapper alone and left the
// binary running as an orphan (observed: a run kept going past its budget).
// A signal sent to the process group then reaches the binary twice, directly
// and through the forward; `run` takes a repeat of the same signal within a
// second as the same delivery when this variable says it is forwarded.
env.ALTIMATE_WRAPPER_FORWARDS_SIGNALS = "1"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: On Windows this marker makes run swallow a genuine second Ctrl-C

ALTIMATE_WRAPPER_FORWARDS_SIGNALS=1 is set unconditionally on the spawn path, but the forward loop below only relays SIGINT off Windows (signal === "SIGTERM" || process.platform !== "win32"). Windows has no process.execve, so it always takes this path, and the console delivers one SIGINT per Ctrl-C press to both processes — no duplicate is ever forwarded. run's coalescer (run.ts:1647 via run-signal.ts:28-31) then drops the user's real second Ctrl-C within 1 s instead of taking exitAfterMirrors' if (signalled) return process.exit(code) fast path, so the forced exit waits out the 2 s drain, contradicting the intent stated at run.ts:1597-1600. The marker is also inherited by every descendant (tool shells re-export process.env; tool/bash.ts strips only HOST_MARKERS and the run-mode keys), so a nested run whose own wrapper exec'd enables coalescing with no forwarded copy to coalesce. Marking the signals actually forwarded (per signal, not one flag) closes both.

const child = childProcess.spawn(target, process.argv.slice(2), {
stdio: "inherit",
env,
})
if (result.error) {
console.error(result.error.message)
process.exit(1)
const forward = (signal) => {
try {
child.kill(signal)
} catch {
// The child already exited; its "exit" handler below decides the status.
}
}
// A child killed by a signal (e.g. the kernel OOM killer) has no exit status; report it the way
// a shell would (128 + signal number) instead of exiting 0 as if the run had succeeded.
if (result.signal) {
console.error(`altimate-code terminated by ${result.signal}`)
process.exit(128 + (os.constants.signals[result.signal] ?? 1))
// On Windows the console delivers Ctrl-C to every attached process and
// child.kill terminates outright, so only SIGTERM is forwarded there. Every
// signal keeps a listener so the wrapper waits for the child and exits with
// the child's status.
for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major: on the spawn path a group-directed SIGTERM now cuts serve and the MCP server short. Forwarding applies to every subcommand, but only run coalesces. serve.ts:116-117 and the MCP server (altimate/mcp-server/server.ts:207) use process.once, so the forwarded copy hits the default disposition and kills the process during, or even before, its shutdown. Repro with the spawn path forced (--require a file that deletes process.execve, as on Node 22.14 and older) and a fake binary with the same once + 1 s shutdown: after kill -TERM -<pgid>, head spawn logs only READY, then altimate-code terminated by SIGTERM with status 143. Head on the exec path and base both log SHUTDOWN-START SHUTDOWN-DONE. systemd's default KillMode=control-group sends SIGTERM to every process in the unit, so a serve unit on older node hits this on every stop. The PR description acknowledges it, but it is a regression against main on the path this PR changes. Fix: the same source-aware delivery as the coalescing comment, or do not forward when the child already got the signal from its group.

process.on(signal, () => {
if (signal === "SIGTERM" || process.platform !== "win32") forward(signal)
})
}
const code = typeof result.status === "number" ? result.status : 1
process.exit(code)
child.on("error", (error) => {
console.error(error.message)
process.exit(1)
})
child.on("exit", (status, signal) => {
// A child killed by a signal (e.g. the kernel OOM killer) has no exit status; report it the way
// a shell would (128 + signal number) instead of exiting 0 as if the run had succeeded.
if (signal) {
console.error(`altimate-code terminated by ${signal}`)
process.exit(128 + (os.constants.signals[signal] ?? 1))
}
const code = typeof status === "number" ? status : 1
process.exit(code)
})
}

// run() returns while the child is still running, so every branch below must
// be the only one taken: the first match wins, and the fallback search runs
// only when neither override is present.
const envPath = process.env.ALTIMATE_CODE_BIN_PATH
if (envPath) {
run(envPath)
}

//
const cached = path.join(scriptDir, ".altimate-code")
if (fs.existsSync(cached)) {
run(cached)
}
const override = envPath || (fs.existsSync(cached) ? cached : undefined)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: The AVX2/musl probe now runs on every launch even when the cached binary is found

names (line 197) calls supportsAvx2() and the Linux musl probe, forking sysctl on darwin x64, PowerShell on win32 x64 and ldd --version on Linux, and it is a module-level constant evaluated before override ?? findBinary(scriptDir) at line 260. Before this change the override and cached branches called run(), which ended synchronously in spawnSync + process.exit, so none of that ran. script/postinstall.mjs installs bin/.altimate-code on every non-Windows install, so the cached override is the normal production launch path and now pays this probe (roughly 10-30 ms on Linux/macOS; up to the 3 s PowerShell timeout on Windows) on every CLI start. Compute names only in the fallback branch, or memoize it.


const platformMap = {
darwin: "darwin",
Expand Down Expand Up @@ -222,7 +262,7 @@ function findBinary(startDir) {
}
}

const resolved = findBinary(scriptDir)
const resolved = override ?? findBinary(scriptDir)
if (!resolved) {
console.error(
"It seems that your package manager failed to install the right version of the altimate-code CLI for your platform. You can try manually installing " +
Expand Down
4 changes: 4 additions & 0 deletions packages/opencode/src/altimate/observability/tracing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,10 @@ export interface RunBudgetMetadata {
/** Unix milliseconds, matching generation and span timestamps. */
effort_downgraded_at?: number
generation_interrupted_at?: number
/** `--max-tokens` accounting; present only when a token budget is set. */
max_tokens?: number
tokens_used?: number
token_budget_exhausted?: boolean
}

interface TracePartIdentity {
Expand Down
39 changes: 39 additions & 0 deletions packages/opencode/src/cli/cmd/run-signal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// altimate_change start — fork-only: one delivery per signal when the npm wrapper forwards it
// Where node has no process.execve (Windows, older node), the npm wrapper spawns
// the binary and forwards termination signals to it. A signal sent to the
// process group (GNU `timeout`, `killpg`, tree-kill, a terminal's Ctrl-C) then
// reaches the binary twice: directly, and again through the forward. `run`
// reads a second signal as "exit now", so the pair would skip its shutdown
// flush. The wrapper says it forwards through ALTIMATE_WRAPPER_FORWARDS_SIGNALS;
// only then is one repeat of the same signal soon after a delivery dropped.

/** How soon after a delivery a repeat of the same signal is its forwarded copy. */
export const REPEAT_WINDOW_MS = 1_000

/** True when the npm wrapper forwards termination signals to this process. */
export function forwardedByWrapper(env: Record<string, string | undefined> = process.env): boolean {
return env.ALTIMATE_WRAPPER_FORWARDS_SIGNALS === "1"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This flag is inherited, not set by the wrapper for this process. The exec path copies process.env and keeps the inherited ALTIMATE_WRAPPER_FORWARDS_SIGNALS, so forwardedByWrapper() returns true where nothing forwards. Delete the variable from env in the exec path of bin/altimate-code before process.execve.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/opencode/src/cli/cmd/run-signal.ts, line 15:

<comment>This flag is inherited, not set by the wrapper for this process. The exec path copies `process.env` and keeps the inherited `ALTIMATE_WRAPPER_FORWARDS_SIGNALS`, so `forwardedByWrapper()` returns true where nothing forwards. Delete the variable from `env` in the exec path of `bin/altimate-code` before `process.execve`.</comment>

<file context>
@@ -0,0 +1,39 @@
+
+/** True when the npm wrapper forwards termination signals to this process. */
+export function forwardedByWrapper(env: Record<string, string | undefined> = process.env): boolean {
+  return env.ALTIMATE_WRAPPER_FORWARDS_SIGNALS === "1"
+}
+
</file context>

}

/**
* Wraps signal handlers so a forwarded copy of a signal is not a second
* delivery. Without forwarding every signal is delivered, as before.
*/
export function coalescer(forwarded: boolean, now: () => number = Date.now) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: Use a monotonic clock for signal coalescing. A backward wall-clock adjustment makes at - previous.at negative, causing a legitimate signal to be dropped as the wrapper’s forwarded copy.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/opencode/src/cli/cmd/run-signal.ts, line 22:

<comment>Use a monotonic clock for signal coalescing. A backward wall-clock adjustment makes `at - previous.at` negative, causing a legitimate signal to be dropped as the wrapper’s forwarded copy.</comment>

<file context>
@@ -0,0 +1,39 @@
+ * Wraps signal handlers so a forwarded copy of a signal is not a second
+ * delivery. Without forwarding every signal is delivered, as before.
+ */
+export function coalescer(forwarded: boolean, now: () => number = Date.now) {
+  const last = new Map<string, { at: number; repeated: boolean }>()
+  return (signal: string, handle: () => void) => () => {
</file context>

const last = new Map<string, { at: number; repeated: boolean }>()
return (signal: string, handle: () => void) => () => {
if (forwarded) {
const at = now()
const previous = last.get(signal)
if (previous && !previous.repeated && at - previous.at < REPEAT_WINDOW_MS) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major: the 1 s coalescing also swallows real second signals. The window cannot tell a forwarded copy from a second real signal. (1) On the spawn path, two pid-directed signals sent 300 ms apart (kill -INT <wrapper> twice, or a driver that escalates with a second TERM) give HANDLED once and then the 2 s flush. The "second signal exits at once" contract is lost (my run: spawn notty INT pid x2: RAW HANDLED RAW FLUSH-DONE; the exec path and base exit at once). (2) On Windows the wrapper never forwards SIGINT, yet it sets ALTIMATE_WRAPPER_FORWARDS_SIGNALS=1, so a real second Ctrl-C within 1 s is dropped. (3) The variable is never removed on the exec path (bin/altimate-code:85 sets it, and env copies process.env), so it leaks into tool subprocesses. A nested altimate-code run started from the bash tool then coalesces although no wrapper forwards anything. (4) A forwarded copy that arrives more than 1 s late is taken as a second signal. Suggested fix: mark the forwarded copy itself rather than guessing by time. For example, forward a distinct signal (such as SIGUSR2, with the original name in an env var or a pipe) that the binary maps back, so a real repeat is never mistaken for a copy. At least, set the variable only for the platforms and signals the wrapper actually forwards, and delete it before execve.

previous.repeated = true
return
}
last.set(signal, { at, repeated: false })
}
handle()
}
}

export * as RunSignal from "./run-signal"
// altimate_change end
Loading
Loading