Skip to content

Commit 5d6cab9

Browse files
feat(workspace): honour a workspace pinned by the IDE extension (#1320)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
1 parent 8877e56 commit 5d6cab9

6 files changed

Lines changed: 885 additions & 2 deletions

File tree

‎packages/opencode/src/altimate/workspace/api-client.ts‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -162,10 +162,27 @@ async function req<T>(
162162
* exchanges and covers the request body too, so a call that uploads
163163
* megabytes (a skill bundle) needs its own. */
164164
timeoutMs?: number
165+
/** Act as THIS credential rather than resolving the ambient one.
166+
*
167+
* `creds()` reads the credentials afresh on every call, so a caller that
168+
* needs its request and its own bookkeeping to be about the same principal
169+
* cannot get that by reading them itself — the request would resolve them
170+
* again, and an account switch in between makes the two disagree. Comparing
171+
* before and after does not close it either: A→B→A passes the comparison
172+
* while the request was served as B. Passing the captured credential is the
173+
* only form that cannot drift.
174+
*
175+
* Callers that pass this have already read the credential, so the
176+
* `isConfigured()` gate inside `creds()` — a file-existence check on the
177+
* same file they just read — is skipped. The one behavioural difference:
178+
* deleting the credentials file mid-flight no longer aborts THIS request.
179+
* It still completes as the principal it captured, and the next call fails
180+
* at its own credential read. */
181+
actAs?: { url: string; instance: string; apiKey: string }
165182
} = {},
166183
): Promise<T> {
167184
const timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS
168-
const { url, instance, apiKey } = await creds()
185+
const { url, instance, apiKey } = opts.actAs ?? (await creds())
169186
const qs = opts.query ? "?" + new URLSearchParams(opts.query).toString() : ""
170187
const basePath = opts.base ?? "/datamate-project-bindings"
171188
const target = `${url}${basePath}${subpath}${qs}`
@@ -530,14 +547,21 @@ export namespace WorkspaceApi {
530547
* gets. (M5) Filters out non-integer / non-positive ids so a corrupt row
531548
* doesn't reach the picker as a "NaN" label that the caller then binds
532549
* against. */
533-
export async function listDatamates(): Promise<DatamateRef[]> {
550+
/** `actAs` pins the request to a specific credential — see `req`'s `actAs`. Omitted, this
551+
* resolves the ambient credential as every other call does. */
552+
export async function listDatamates(actAs?: {
553+
url: string
554+
instance: string
555+
apiKey: string
556+
}): Promise<DatamateRef[]> {
534557
// Accept THREE response envelopes — today's ``{datamates: [...]}``, a
535558
// bare ``[...]``, and a generic ``{data: [...]}`` — so a backend
536559
// contract change (or compat layer) doesn't silently empty the picker.
537560
// (cubic-dev-ai round 3.)
538561
type Row = { id: number | string; name: string; memory_enabled?: boolean; user_id?: number }
539562
const body = await req<Row[] | { datamates?: Row[]; data?: Row[] }>("GET", "/", {
540563
base: "/datamates",
564+
...(actAs ? { actAs } : {}),
541565
})
542566
let rows: Row[]
543567
if (Array.isArray(body)) {
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
// altimate_change - new file
2+
//
3+
// The IDE extension's workspace pin.
4+
//
5+
// `altimate-code serve` is launched by the VS Code / Cursor extension, which already knows which
6+
// datamate the user picked in its panel. That selection is what should govern the session's skills
7+
// and memory — not whatever binding this project happens to carry on the backend. The extension
8+
// hands it over in the child's environment and this module turns it back into a `CachedBinding`
9+
// for `state.ts`'s `resolveBindingOutcome` to return.
10+
//
11+
// Why the environment, and not a `serve` argument: `resolveBindingOutcome` is reached from
12+
// per-turn prompt assembly and from every memory write, neither of which has a path back to the
13+
// command's parsed `args`. `session-context.ts` and `serve.ts`'s `ALTIMATE_CODE_SERVE` both made
14+
// the same call, for the same reason — it has to be readable from every module realm. A `serve`
15+
// flag can still be added as sugar, so long as its handler writes these vars before anything else
16+
// runs.
17+
//
18+
// Why NOT the existing `ALTIMATE_RESOLVED_WORKSPACE_*` namespace, which looks like the obvious
19+
// home: `launch-resolve.ts` sets `ALTIMATE_RESOLVED_WORKSPACE_ID` **alone** for the TUI's
20+
// `--workspace <name>` flag — no name, no root. Reusing that namespace would make every such TUI
21+
// session look like a half-populated pin, and the fail-closed rule below would then break
22+
// `--workspace` outright. The two mechanisms are kept apart deliberately, and `readPin` additionally
23+
// stands down outside `serve`.
24+
import { realpathSync } from "node:fs"
25+
import path from "node:path"
26+
import { Filesystem } from "@/util/filesystem"
27+
import { Log } from "@/altimate/util/log"
28+
29+
const log = Log.create({ service: "workspace-pin" })
30+
31+
const ENV_ID = "ALTIMATE_PINNED_WORKSPACE_ID"
32+
const ENV_NAME = "ALTIMATE_PINNED_WORKSPACE_NAME"
33+
const ENV_ROOT = "ALTIMATE_PINNED_WORKSPACE_ROOT"
34+
35+
export interface ValidPin {
36+
kind: "valid"
37+
datamateId: number
38+
datamateName: string
39+
/** The directory `serve` was launched for. The pin applies to this tree and nothing else. */
40+
root: string
41+
}
42+
43+
/**
44+
* `absent` and `invalid` are deliberately NOT the same answer.
45+
*
46+
* Collapsing them — the shape `getResolvedWorkspaceId` uses, where anything unparseable returns
47+
* `null` — would make a malformed pin fall through to ordinary cache/server resolution, which can
48+
* legitimately return a DIFFERENT workspace. Silently doing work against a workspace the user did
49+
* not pick is the one outcome this feature must never produce, so a pin that is present but broken
50+
* fails closed instead.
51+
*/
52+
export type PinState = { kind: "absent" } | { kind: "invalid"; reason: string } | ValidPin
53+
54+
/**
55+
* Whether `directory` is the pinned root or lives underneath it.
56+
*
57+
* Delegates to `Filesystem.containsReal`, which resolves symlinks and — critically — walks up to
58+
* the nearest existing ancestor when the path itself does not exist yet, rejecting `..` segments
59+
* along the way. An earlier version here compared `realpathSync` output with a LEXICAL fallback
60+
* when resolution failed, which a not-yet-created path under a symlinked ancestor defeated:
61+
* `<root>/link/new`, with `link -> /outside`, resolved to nothing, fell back to the literal string,
62+
* and passed the prefix test. Since the directory arrives from the caller-supplied
63+
* `x-opencode-directory` header on an unsecured server, that was enough to attribute an outside
64+
* project's skills and memory to the pinned workspace.
65+
*/
66+
export function withinRoot(directory: string, root: string): boolean {
67+
return resolveWithinRoot(directory, root) !== null
68+
}
69+
70+
/**
71+
* `withinRoot`, but returning the CANONICAL directory it validated — or `null` when the directory
72+
* is not contained.
73+
*
74+
* Exists because containment is checked once, early, and the caller then does async work
75+
* (credentials, a network round trip) before it needs the directory again. Re-deriving it from the
76+
* caller-supplied string at that point re-opens the window: a symlink swapped in between would be
77+
* resolved the second time and not the first, so the path that was authorised and the path that is
78+
* used need not be the same one. Callers keep this value and use it instead of the raw argument.
79+
*
80+
* The canonical form is the one `resolveProjectIdentifier` would compute — `realpath` where it
81+
* resolves, the normalised absolute path otherwise, so a directory that does not exist yet (which
82+
* `containsReal` accepts, having walked to its nearest existing ancestor) still yields something
83+
* stable to carry forward.
84+
*/
85+
export function resolveWithinRoot(directory: string, root: string): string | null {
86+
if (!Filesystem.containsReal(root, directory)) return null
87+
try {
88+
return realpathSync(directory)
89+
} catch {
90+
return path.resolve(directory)
91+
}
92+
}
93+
94+
/**
95+
* Read the pin out of the environment.
96+
*
97+
* Returns `absent` outside `serve`: the pin is the extension's channel, and the TUI has its own
98+
* (`--workspace`, via `launch-resolve.ts`). Keeping them from ever being live in the same process
99+
* is cheaper than reasoning about what should win.
100+
*/
101+
export function readPin(env: NodeJS.ProcessEnv = process.env): PinState {
102+
if (env["ALTIMATE_CODE_SERVE"] !== "1") return { kind: "absent" }
103+
104+
const rawId = env[ENV_ID]
105+
const name = env[ENV_NAME]
106+
const root = env[ENV_ROOT]
107+
108+
// `absent` means the extension set NOTHING. Tested on key presence, not truthiness: three
109+
// present-but-empty variables are a broken pin, not the absence of one, and collapsing them into
110+
// `absent` let a malformed pin fall through to ordinary cache/server resolution — the exact
111+
// fall-open this function exists to prevent.
112+
if (rawId === undefined && name === undefined && root === undefined) {
113+
return { kind: "absent" }
114+
}
115+
116+
// Partial or empty is invalid, never "good enough". The extension sets all three or none;
117+
// anything else means something rewrote the environment and we no longer know what was intended.
118+
if (!rawId || !name || !root) {
119+
return { kind: "invalid", reason: "pin is partially set or empty" }
120+
}
121+
122+
const datamateId = Number(rawId)
123+
if (!Number.isSafeInteger(datamateId) || datamateId <= 0) {
124+
return { kind: "invalid", reason: `datamate id ${JSON.stringify(rawId)} is not a positive integer` }
125+
}
126+
if (!path.isAbsolute(root)) {
127+
return { kind: "invalid", reason: "pinned root is not an absolute path" }
128+
}
129+
130+
return { kind: "valid", datamateId, datamateName: name, root }
131+
}
132+
133+
/** `readPin`, with the refusal logged once at the point it is taken. */
134+
export function readPinLogged(env: NodeJS.ProcessEnv = process.env): PinState {
135+
const pin = readPin(env)
136+
if (pin.kind === "invalid") log.warn("ignoring workspace pin and failing closed", { reason: pin.reason })
137+
return pin
138+
}

0 commit comments

Comments
 (0)