mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 02:47:34 +00:00
Merge remote-tracking branch 'private/cloud/integration' into cloud/ra11-running-strip
This commit is contained in:
@@ -0,0 +1,377 @@
|
||||
// Live proof on a real dev VM (no model spend): per-turn code checkpoints in an Orca Cloud workspace.
|
||||
// A real Claude Code chat runs in orcad on the VM, with its model pointed at a stand-in on the VM
|
||||
// (standin-anthropic.py), and the desktop's own E2EE request connection and client capabilities.
|
||||
// 1. Each message that opens a turn writes one refs/orca/checkpoints/<chat>/turn/* ref; the user's
|
||||
// HEAD, staged files and stash list never change.
|
||||
// 2. Sleep (suspend) and wake (resume): the refs and files are unchanged. A fresh connection, as a
|
||||
// restarted desktop has, rewinds the chat to turn B and restores its files; Undo brings them back.
|
||||
// 3. Rollover (host replaced): the refs are still there, a new turn gets its own ref, and the agent's
|
||||
// context holds only the turns left after the rewind.
|
||||
// 4. Restart (orcad restarted): rewind to turn A restores the files from before the first turn.
|
||||
// Dev backends only. The VM is always deleted at the end unless --keep is given.
|
||||
// Run from the repo root after `pnpm install` there and in cloud/:
|
||||
// node_modules/.bin/tsx cloud/apps/acceptance/live/checkpoints-vm.ts [--keep]
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { control, vercel } from '../src/clients'
|
||||
import { RemoteRuntimeRequestConnection } from '../../../../src/shared/remote-runtime/requests/remote-runtime-request-connection'
|
||||
import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../../src/shared/electron-remote-runtime-client-capabilities'
|
||||
import { pairedRuntimeConnectionFromOffer } from '../../../../src/shared/remote-runtime/pairing/paired-runtime-connection'
|
||||
import { parsePairingCode } from '../../../../src/shared/remote-runtime/pairing/pairing'
|
||||
import {
|
||||
createStructuredAgentSessionId,
|
||||
structuredAgentSessionCreateParams
|
||||
} from '../../../../src/shared/agent-session/structured-agent-session-create'
|
||||
import {
|
||||
createStructuredAgentSessionOperationId,
|
||||
structuredAgentSessionPayloadFingerprint
|
||||
} from '../../../../src/shared/agent-session/lifecycle/structured-agent-session-mutation'
|
||||
import { structuredAgentSessionMessageSendMutation } from '../../../../src/shared/agent-session/requests/structured-agent-session-send-mutation'
|
||||
import { agentJournalSubmissionKey } from '../../../../src/shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import type { AgentSessionHistoryResult } from '../../../../src/shared/agent-session/agent-session-wire'
|
||||
import type {
|
||||
AgentSessionCheckpointPreview,
|
||||
AgentSessionCheckpointRestoreResult
|
||||
} from '../../../../src/shared/agent-session/lifecycle/agent-session-checkpoint'
|
||||
|
||||
const REPO = '/vercel/sandbox/ckvm-repo'
|
||||
const STANDIN = path.join(path.dirname(fileURLToPath(import.meta.url)), 'standin-anthropic.py')
|
||||
const MODEL = 'claude-sonnet-4-5-20250929'
|
||||
const who = { sub: `ckvm-${Date.now().toString(36)}` }
|
||||
const keep = process.argv.includes('--keep')
|
||||
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
|
||||
const since = (t0: number) => Math.round(performance.now() - t0)
|
||||
type Files = Record<string, string>
|
||||
type Vm = { id: string; vsession: string; pairingCode: string }
|
||||
|
||||
const timings: Record<string, number> = {}
|
||||
const failures: string[] = []
|
||||
function log(line: string): void {
|
||||
console.log(`${new Date().toISOString()} ${line}`)
|
||||
}
|
||||
function check(ok: boolean, what: string): void {
|
||||
log(`${ok ? 'PASS' : 'FAIL'} ${what}`)
|
||||
if (!ok) {
|
||||
failures.push(what)
|
||||
}
|
||||
}
|
||||
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
|
||||
|
||||
async function exec(vm: Vm, script: string, timeoutMs = 120_000): Promise<string> {
|
||||
const r = await vercel().runCommand(vm.vsession, { command: 'bash', args: ['-lc', script], timeoutMs })
|
||||
if (r.exitCode !== 0) {
|
||||
throw new Error(`VM command exited ${r.exitCode}: ${r.stderr.slice(-1500)}`)
|
||||
}
|
||||
return r.stdout
|
||||
}
|
||||
|
||||
/** Every file in the repo except .git and .claude, with its content, as the user sees it. */
|
||||
async function files(vm: Vm): Promise<Files> {
|
||||
const out = await exec(
|
||||
vm,
|
||||
`cd ${REPO} && find . \\( -name .git -o -name .claude \\) -prune -o -type f -print | sort | while read -r f; do printf '%s\\t%s\\n' "\${f#./}" "$(base64 -w0 < "$f")"; done`
|
||||
)
|
||||
const result: Files = {}
|
||||
for (const line of out.split('\n').filter(Boolean)) {
|
||||
const [name, b64] = line.split('\t')
|
||||
result[name!] = Buffer.from(b64 ?? '', 'base64').toString('utf8')
|
||||
}
|
||||
return result
|
||||
}
|
||||
const refs = async (vm: Vm) =>
|
||||
(await exec(vm, `cd ${REPO} && git for-each-ref --format='%(refname) %(objectname)' refs/orca/`)).trim().split('\n').filter(Boolean)
|
||||
const turnRefs = async (vm: Vm) => (await refs(vm)).filter((ref) => ref.includes('/turn/'))
|
||||
/** HEAD, staged paths, stash count: what checkpoints must never touch. */
|
||||
const userGit = (vm: Vm) =>
|
||||
exec(vm, `cd ${REPO} && git rev-parse HEAD && git diff --cached --name-only && git stash list | wc -l`).then((s) => s.trim())
|
||||
|
||||
/** The desktop's own paired request connection and client capabilities (E2EE WebSocket to orcad). */
|
||||
function connect(vm: Vm) {
|
||||
const offer = parsePairingCode(vm.pairingCode)
|
||||
if (!offer) {
|
||||
throw new Error('the control plane returned an unreadable pairing code')
|
||||
}
|
||||
const connection = new RemoteRuntimeRequestConnection(
|
||||
pairedRuntimeConnectionFromOffer(offer),
|
||||
ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES
|
||||
)
|
||||
const raw = async <T>(method: string, params: unknown, timeoutMs = 60_000) => {
|
||||
const response = await connection.request<T>(method, params, timeoutMs)
|
||||
if (response.ok === false) {
|
||||
throw new Error(`${method}: ${response.error.message} ${JSON.stringify(response.error.data ?? null)}`)
|
||||
}
|
||||
return response
|
||||
}
|
||||
const call = async <T>(method: string, params: unknown, timeoutMs?: number) => (await raw<T>(method, params, timeoutMs)).result
|
||||
return { raw, call, close: () => connection.close() }
|
||||
}
|
||||
type Client = ReturnType<typeof connect>
|
||||
|
||||
const tail = (client: Client, sessionId: string) =>
|
||||
client.call<AgentSessionHistoryResult>('agentSession.history', { sessionId, direction: 'tail', limit: 200 })
|
||||
|
||||
async function startStandin(vm: Vm): Promise<void> {
|
||||
const source = readFileSync(STANDIN).toString('base64')
|
||||
await exec(vm, `echo ${source} | base64 -d > /tmp/standin.py; pkill -f '^python3 /tmp/standin[.]py' || true`)
|
||||
// Detached: a runCommand's process tree ends with the call.
|
||||
await vercel().startCommand(vm.vsession, { command: 'python3', args: ['/tmp/standin.py'], timeoutMs: 30 * 60_000 })
|
||||
const code = await exec(
|
||||
vm,
|
||||
`for i in $(seq 1 20); do c=$(curl -s --noproxy '*' -o /dev/null -w '%{http_code}' http://127.0.0.1:8998/v1/models); [ "$c" = 200 ] && break; sleep 0.5; done; echo $c`
|
||||
)
|
||||
if (code.trim() !== '200') {
|
||||
throw new Error(`stand-in model server did not start (${code.trim()})`)
|
||||
}
|
||||
}
|
||||
|
||||
async function lifecycle(vm: Vm, action: 'resume' | 'rollover' | 'restart'): Promise<void> {
|
||||
const t0 = performance.now()
|
||||
const r = await control.as(who, 'POST', `/v1/sandboxes/${vm.id}/${action}`)
|
||||
if (r.status !== 200) {
|
||||
throw new Error(`${action} -> ${r.status} ${JSON.stringify(r.body).slice(0, 400)}`)
|
||||
}
|
||||
timings[action] = since(t0)
|
||||
vm.vsession = r.body.sandbox.session.id
|
||||
vm.pairingCode = r.body.connection.pairingCode
|
||||
log(`${action}: 200 in ${timings[action]} ms`)
|
||||
await startStandin(vm)
|
||||
}
|
||||
|
||||
const TURNS: Record<string, string> = {
|
||||
A: "printf 'one\\n' > feature.txt",
|
||||
B: "printf 'v2\\n' > app.txt && rm feature.txt && mkdir -p notes && printf 'later\\n' > notes/todo.txt",
|
||||
C: "printf 'three\\n' > three.txt && printf 'v3\\n' > app.txt",
|
||||
D: "printf 'after-rewind\\n' > d.txt",
|
||||
E: "printf 'e\\n' > e.txt"
|
||||
}
|
||||
type Turn = { itemId: string; before: Files; after: Files }
|
||||
|
||||
/** Sends one message and waits until the agent replied and the chat has gone quiet. */
|
||||
async function turn(vm: Vm, client: Client, sessionId: string, name: string): Promise<Turn> {
|
||||
const before = await files(vm)
|
||||
const refsBefore = (await turnRefs(vm)).length
|
||||
const clientOperationId = createStructuredAgentSessionOperationId(randomUUID)
|
||||
const page = (await tail(client, sessionId)).page
|
||||
await client.call(
|
||||
'agentSession.send',
|
||||
structuredAgentSessionMessageSendMutation({
|
||||
sessionId,
|
||||
clientOperationId,
|
||||
expectedRuntimeFence: page.fence ?? 0,
|
||||
body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: `Turn ${name}. RUN: ${TURNS[name]}` }] },
|
||||
delivery: 'queue-if-active'
|
||||
}),
|
||||
120_000
|
||||
)
|
||||
const itemId = agentJournalSubmissionKey(clientOperationId)
|
||||
let last = -1
|
||||
let quiet = 0
|
||||
for (let i = 0; i < 150; i++) {
|
||||
await sleep(2000)
|
||||
const items = (await tail(client, sessionId)).page.items
|
||||
const index = items.findIndex((item) => item.itemId === itemId)
|
||||
const replied =
|
||||
index !== -1 && items.slice(index + 1).some((item) => item.body.kind === 'message' && item.body.role === 'assistant')
|
||||
const newest = items.at(-1)?.sequence ?? -1
|
||||
quiet = newest === last ? quiet + 1 : 0
|
||||
last = newest
|
||||
if (replied && quiet >= 3) {
|
||||
break
|
||||
}
|
||||
}
|
||||
const after = await files(vm)
|
||||
check((await turnRefs(vm)).length === refsBefore + 1, `turn ${name} wrote one checkpoint ref (${refsBefore} -> ${refsBefore + 1})`)
|
||||
check(!same(before, after), `turn ${name}: the agent changed files`)
|
||||
return { itemId, before, after }
|
||||
}
|
||||
|
||||
/** The "Turn X." markers in the context of the model request that ran this turn's command. */
|
||||
async function modelContext(vm: Vm, name: string): Promise<string> {
|
||||
const lines = (await exec(vm, 'cat /tmp/standin.log')).split('\n')
|
||||
const line = lines.reverse().find((l) => l.includes(`-> tool ${TURNS[name]!.slice(0, 40)}`))
|
||||
return /context=(\[[^\]]*\])/.exec(line ?? '')?.[1] ?? 'none'
|
||||
}
|
||||
|
||||
async function rewindAndRestore(vm: Vm, client: Client, sessionId: string, name: string, t: Turn, undo: boolean) {
|
||||
const items = (await tail(client, sessionId)).page.items
|
||||
check(items.some((item) => item.itemId === t.itemId), `fresh connection: turn ${name}'s message is in the chat (${items.length} items)`)
|
||||
let t0 = performance.now()
|
||||
const preview = await client.call<AgentSessionCheckpointPreview>('agentSession.checkpointPreview', { sessionId, itemId: t.itemId })
|
||||
timings[`preview${name}`] = since(t0)
|
||||
log(`preview ${name}: ${JSON.stringify(preview)}`)
|
||||
check(preview.available && !preview.busy && !preview.headMoved, `turn ${name} has a restorable checkpoint`)
|
||||
const filesBefore = await files(vm)
|
||||
// As the UI does: rewind the chat first, then restore the files.
|
||||
let rewound = ''
|
||||
for (let i = 0; i < 40 && !rewound.includes('"ok":true'); i++) {
|
||||
const page = (await tail(client, sessionId)).page
|
||||
const fields = { itemId: t.itemId, expectedEpoch: page.epoch }
|
||||
const response = await client.raw('agentSession.rewind', {
|
||||
...fields,
|
||||
envelope: {
|
||||
sessionId,
|
||||
clientOperationId: createStructuredAgentSessionOperationId(randomUUID),
|
||||
expectedRuntimeFence: page.fence,
|
||||
payloadFingerprint: structuredAgentSessionPayloadFingerprint({ method: 'agentSession.rewind', sessionId, fields })
|
||||
}
|
||||
}, 200_000)
|
||||
rewound = JSON.stringify(response.result)
|
||||
if (!rewound.includes('"ok":true')) {
|
||||
await sleep(5000)
|
||||
}
|
||||
}
|
||||
const after = (await tail(client, sessionId)).page.items
|
||||
check(
|
||||
rewound.includes('"ok":true') && !after.some((item) => item.itemId === t.itemId),
|
||||
`rewind ${name}: the chat drops the message and everything after it (${items.length} -> ${after.length} items)`
|
||||
)
|
||||
let restored: AgentSessionCheckpointRestoreResult | undefined
|
||||
t0 = performance.now()
|
||||
for (let i = 0; i < 30 && !restored; i++) {
|
||||
try {
|
||||
restored = await client.call<AgentSessionCheckpointRestoreResult>('agentSession.checkpointRestore', { sessionId, itemId: t.itemId }, 120_000)
|
||||
} catch (error) {
|
||||
if (!String(error).includes('busy')) {
|
||||
throw error
|
||||
}
|
||||
await sleep(2000)
|
||||
}
|
||||
}
|
||||
timings[`restore${name}`] = since(t0)
|
||||
const now = await files(vm)
|
||||
check(same(now, t.before), `restore ${name}: files are exactly as when turn ${name} was sent (${restored?.changedFiles} changed)`)
|
||||
if (undo && restored) {
|
||||
t0 = performance.now()
|
||||
await client.call('agentSession.checkpointUndo', { sessionId, undoId: restored.undoId }, 120_000)
|
||||
timings[`undo${name}`] = since(t0)
|
||||
check(same(await files(vm), filesBefore), `undo ${name}: the agent's later edits are back`)
|
||||
}
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
let t0 = performance.now()
|
||||
const created = await control.as(who, 'POST', '/v1/sandboxes', { machineSize: 'standard', workspaceId: 'ckvm' })
|
||||
if (created.status !== 200) {
|
||||
throw new Error(`create -> ${created.status} ${JSON.stringify(created.body)}`)
|
||||
}
|
||||
timings.create = since(t0)
|
||||
const vm: Vm = {
|
||||
id: created.body.sandbox.id,
|
||||
vsession: created.body.sandbox.session.id,
|
||||
pairingCode: created.body.connection.pairingCode
|
||||
}
|
||||
log(`create: ${vm.id} (${who.sub}) in ${timings.create} ms, region ${created.body.sandbox.region}`)
|
||||
try {
|
||||
await startStandin(vm)
|
||||
const settingsEnv = Buffer.from(JSON.stringify({
|
||||
ANTHROPIC_BASE_URL: 'http://127.0.0.1:8998',
|
||||
ANTHROPIC_AUTH_TOKEN: 'standin-no-cost',
|
||||
ANTHROPIC_API_KEY: '',
|
||||
ANTHROPIC_MODEL: MODEL,
|
||||
ANTHROPIC_SMALL_FAST_MODEL: MODEL,
|
||||
ANTHROPIC_DEFAULT_HAIKU_MODEL: MODEL,
|
||||
NO_PROXY: '127.0.0.1,localhost',
|
||||
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1'
|
||||
})).toString('base64')
|
||||
// Claude Code applies settings.json env over its inherited env: its model is the stand-in.
|
||||
const setup = await exec(vm, `set -e
|
||||
f="$HOME/.claude/settings.json"; mkdir -p "$(dirname "$f")"; [ -f "$f" ] || echo '{}' > "$f"
|
||||
python3 -c 'import json,sys,base64; f=sys.argv[1]; d=json.load(open(f)); d.setdefault("env",{}).update(json.loads(base64.b64decode(sys.argv[2]))); json.dump(d,open(f,"w"))' "$f" ${settingsEnv}
|
||||
claude --version; cat /opt/orca/runtime/orcad/SOURCE_COMMIT
|
||||
rm -rf ${REPO}; mkdir -p ${REPO}; cd ${REPO}; git init -q; git config user.name E2E; git config user.email e2e@example.test
|
||||
printf 'build/\\n' > .gitignore; printf 'v0\\n' > app.txt; git add .; git -c commit.gpgsign=false commit -qm base
|
||||
printf 'staged by the user\\n' > staged.txt; git add staged.txt`)
|
||||
log(`VM: ${setup.trim().replace(/\n/g, ', ')}`)
|
||||
const gitAtStart = await userGit(vm)
|
||||
|
||||
let client = connect(vm)
|
||||
const added = await client.call<{ repo: { id: string } }>('repo.add', { path: REPO })
|
||||
let worktreeId = ''
|
||||
for (let i = 0; i < 30 && !worktreeId; i++) {
|
||||
worktreeId = (await client.call<{ worktrees: { id: string }[] }>('worktree.list', { repo: `id:${added.repo.id}` })).worktrees[0]?.id ?? ''
|
||||
if (!worktreeId) {
|
||||
await sleep(1000)
|
||||
}
|
||||
}
|
||||
const sessionId = createStructuredAgentSessionId('claude', randomUUID)
|
||||
await client.call('agentSession.create', structuredAgentSessionCreateParams({
|
||||
sessionId,
|
||||
worktree: `id:${worktreeId}`,
|
||||
agent: 'claude',
|
||||
options: { permissionMode: 'full-access' },
|
||||
randomUuid: randomUUID
|
||||
}))
|
||||
for (let i = 0; i < 60 && !(await tail(client, sessionId)).page.fence; i++) {
|
||||
await sleep(2000)
|
||||
}
|
||||
const runtimeAtStart = (await client.raw('agentSession.history', { sessionId, direction: 'tail', limit: 1 }))._meta.runtimeId
|
||||
|
||||
// 1. One checkpoint per turn; the user's git state untouched.
|
||||
const turns: Record<string, Turn> = {}
|
||||
for (const name of ['A', 'B', 'C']) {
|
||||
turns[name] = await turn(vm, client, sessionId, name)
|
||||
}
|
||||
check((await userGit(vm)) === gitAtStart, 'HEAD, staged files and stash list unchanged by snapshots')
|
||||
client.close()
|
||||
|
||||
// 2. Sleep and wake, then a fresh connection (a restarted desktop) rewinds to B and restores.
|
||||
const refsBeforeSleep = await refs(vm)
|
||||
const filesBeforeSleep = await files(vm)
|
||||
t0 = performance.now()
|
||||
const suspended = await control.as(who, 'POST', `/v1/sandboxes/${vm.id}/suspend`)
|
||||
timings.suspend = since(t0)
|
||||
check(suspended.status === 200 && suspended.body.sandbox.status === 'suspended', `suspend -> ${suspended.body?.sandbox?.status} in ${timings.suspend} ms`)
|
||||
await lifecycle(vm, 'resume')
|
||||
check(same(await refs(vm), refsBeforeSleep), `after sleep and wake: all ${refsBeforeSleep.length} checkpoint refs are unchanged`)
|
||||
check(same(await files(vm), filesBeforeSleep), 'after sleep and wake: files unchanged')
|
||||
client = connect(vm)
|
||||
await rewindAndRestore(vm, client, sessionId, 'B', turns.B!, true)
|
||||
check((await userGit(vm)) === gitAtStart, 'after restore and undo: HEAD, staged files and stash list unchanged')
|
||||
client.close()
|
||||
|
||||
// 3. Rollover: refs survive a new host; a new turn checkpoints; the agent only sees A and D.
|
||||
const refsBeforeRollover = await refs(vm)
|
||||
await lifecycle(vm, 'rollover')
|
||||
check(same(await refs(vm), refsBeforeRollover), `after rollover: all ${refsBeforeRollover.length} refs (turn and undo) are unchanged`)
|
||||
client = connect(vm)
|
||||
turns.D = await turn(vm, client, sessionId, 'D')
|
||||
const contextD = await modelContext(vm, 'D')
|
||||
check(contextD === "['A', 'D']", `after rewind to B, the agent's context holds only A and D (${contextD})`)
|
||||
client.close()
|
||||
|
||||
// 4. Restart orcad, then a fresh connection rewinds to the first turn.
|
||||
await lifecycle(vm, 'restart')
|
||||
client = connect(vm)
|
||||
const runtimeNow = (await client.raw('agentSession.history', { sessionId, direction: 'tail', limit: 1 }))._meta.runtimeId
|
||||
check(runtimeNow !== runtimeAtStart, `orcad is a new process (runtime ${runtimeAtStart.slice(0, 8)} -> ${runtimeNow.slice(0, 8)})`)
|
||||
await rewindAndRestore(vm, client, sessionId, 'A', turns.A!, false)
|
||||
turns.E = await turn(vm, client, sessionId, 'E')
|
||||
const contextE = await modelContext(vm, 'E')
|
||||
check(contextE === "['E']", `after rewind to A, the agent's context holds only E (${contextE})`)
|
||||
check((await userGit(vm)) === gitAtStart, 'end: HEAD, staged files and stash list unchanged')
|
||||
client.close()
|
||||
log(`refs at the end:\n${(await refs(vm)).join('\n')}`)
|
||||
} finally {
|
||||
if (keep) {
|
||||
log(`--keep: ${vm.id} left running for ${who.sub}`)
|
||||
} else {
|
||||
const deleted = await control.as(who, 'DELETE', `/v1/sandboxes/${vm.id}`)
|
||||
const listed = await control.as(who, 'GET', '/v1/sandboxes')
|
||||
log(`delete ${vm.id}: ${deleted.status} ${deleted.body?.sandbox?.status}; sandboxes left: ${JSON.stringify(listed.body?.sandboxes?.map((s: { id: string; status: string }) => [s.id, s.status]) ?? [])}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main().then(
|
||||
() => {
|
||||
log(`timings (ms): ${JSON.stringify(timings)}`)
|
||||
log(failures.length ? `FAILED ${failures.length}: ${failures.join('; ')}` : 'checkpoints-vm OK')
|
||||
process.exit(failures.length ? 1 : 0)
|
||||
},
|
||||
(error: unknown) => {
|
||||
console.error(error)
|
||||
process.exit(1)
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,96 @@
|
||||
# No-cost stand-in for the Anthropic Messages API (checkpoints-vm.ts uploads it to the VM and runs it
|
||||
# at 127.0.0.1:8998). Claude Code uses it as its model, so a chat turn is real Claude Code with real
|
||||
# tools and no model spend:
|
||||
# - a user message containing "RUN: <bash>" gets one Bash tool_use running that command;
|
||||
# - a tool_result gets the text "DONE";
|
||||
# - anything else (titles, side calls) gets a short text.
|
||||
# Each request is logged to /tmp/standin.log with the "Turn X." markers in the model's context, which
|
||||
# shows whether a rewind also rewound what the agent sees.
|
||||
import http.server, json, re, time, uuid
|
||||
|
||||
LOG = '/tmp/standin.log'
|
||||
|
||||
|
||||
def log(line):
|
||||
with open(LOG, 'a') as f:
|
||||
f.write(time.strftime('%H:%M:%S ') + line + '\n')
|
||||
|
||||
|
||||
def texts(content):
|
||||
if isinstance(content, str):
|
||||
return [content]
|
||||
return [b.get('text', '') for b in (content or []) if isinstance(b, dict) and b.get('type') == 'text']
|
||||
|
||||
|
||||
def decide(body):
|
||||
messages = body.get('messages') or []
|
||||
if not body.get('tools') or not messages:
|
||||
return ('text', 'ok')
|
||||
content = messages[-1].get('content')
|
||||
if isinstance(content, list) and any(isinstance(b, dict) and b.get('type') == 'tool_result' for b in content):
|
||||
return ('text', 'DONE')
|
||||
for text in reversed(texts(content)):
|
||||
if 'RUN:' in text:
|
||||
return ('tool', text.split('RUN:', 1)[1].split('\n', 1)[0].strip())
|
||||
return ('text', 'DONE')
|
||||
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
protocol_version = 'HTTP/1.1'
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def reply(self, obj, content_type='application/json'):
|
||||
data = obj if isinstance(obj, bytes) else json.dumps(obj).encode()
|
||||
self.send_response(200)
|
||||
self.send_header('content-type', content_type)
|
||||
self.send_header('content-length', str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def do_GET(self):
|
||||
self.reply({'data': [], 'has_more': False})
|
||||
|
||||
def do_POST(self):
|
||||
size = int(self.headers.get('content-length') or 0)
|
||||
try:
|
||||
body = json.loads(self.rfile.read(size) or b'{}')
|
||||
except ValueError:
|
||||
body = {}
|
||||
if 'count_tokens' in self.path:
|
||||
return self.reply({'input_tokens': 10})
|
||||
kind, value = decide(body)
|
||||
model = body.get('model', 'claude-standin')
|
||||
messages = body.get('messages') or []
|
||||
context = [t for m in messages for text in texts(m.get('content')) for t in re.findall(r'Turn ([A-Z])[.]', text)]
|
||||
log(f'POST {self.path} tools={len(body.get("tools") or [])} msgs={len(messages)} context={context} -> {kind} {value[:160]}')
|
||||
usage = {'input_tokens': 10, 'output_tokens': 5, 'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0}
|
||||
if kind == 'tool':
|
||||
block = {'type': 'tool_use', 'id': 'toolu_' + uuid.uuid4().hex[:20], 'name': 'Bash',
|
||||
'input': {'command': value, 'description': 'Scripted edit'}}
|
||||
stop = 'tool_use'
|
||||
else:
|
||||
block = {'type': 'text', 'text': value}
|
||||
stop = 'end_turn'
|
||||
message_id = 'msg_' + uuid.uuid4().hex[:20]
|
||||
if not body.get('stream'):
|
||||
return self.reply({'id': message_id, 'type': 'message', 'role': 'assistant', 'model': model, 'content': [block],
|
||||
'stop_reason': stop, 'stop_sequence': None, 'usage': usage})
|
||||
events = [('message_start', {'type': 'message_start', 'message': {
|
||||
'id': message_id, 'type': 'message', 'role': 'assistant', 'model': model, 'content': [],
|
||||
'stop_reason': None, 'stop_sequence': None, 'usage': usage}})]
|
||||
if kind == 'tool':
|
||||
events.append(('content_block_start', {'type': 'content_block_start', 'index': 0, 'content_block': {**block, 'input': {}}}))
|
||||
events.append(('content_block_delta', {'type': 'content_block_delta', 'index': 0,
|
||||
'delta': {'type': 'input_json_delta', 'partial_json': json.dumps(block['input'])}}))
|
||||
else:
|
||||
events.append(('content_block_start', {'type': 'content_block_start', 'index': 0, 'content_block': {'type': 'text', 'text': ''}}))
|
||||
events.append(('content_block_delta', {'type': 'content_block_delta', 'index': 0, 'delta': {'type': 'text_delta', 'text': value}}))
|
||||
events.append(('content_block_stop', {'type': 'content_block_stop', 'index': 0}))
|
||||
events.append(('message_delta', {'type': 'message_delta', 'delta': {'stop_reason': stop, 'stop_sequence': None}, 'usage': {'output_tokens': 5}}))
|
||||
events.append(('message_stop', {'type': 'message_stop'}))
|
||||
self.reply(b''.join(f'event: {name}\ndata: {json.dumps(data)}\n\n'.encode() for name, data in events), 'text/event-stream')
|
||||
|
||||
|
||||
http.server.ThreadingHTTPServer(('127.0.0.1', 8998), Handler).serve_forever()
|
||||
@@ -49,6 +49,7 @@ export const CATALOG: Feature[] = [
|
||||
{ id: 'life.read-asleep-access', section: S.life, feature: 'Read-while-asleep access control: removed member loses access at once (keys deleted), private workspace is owner-only', conductor: 'Org access to server-held chats', owner: 'gap-read-asleep', priority: 'P0', better: 'End-to-end encrypted; server holds only ciphertext' },
|
||||
{ id: 'life.read-asleep-phone', section: S.life, feature: 'Phone shows "Latest from this workspace" for a sleeping workspace without waking it', conductor: 'iOS app reads server-held chats', owner: 'gap-read-asleep', priority: 'P1' },
|
||||
{ id: 'local.checkpoints', section: S.acct, feature: 'Per-turn code checkpoints: revert restores files and chat together', conductor: '0.19 (Claude), 0.44 (Codex) checkpoints', owner: 'gap-checkpoints', priority: 'P0' },
|
||||
{ id: 'cloud.checkpoints', section: S.life, feature: 'Per-turn checkpoints in a cloud workspace: Rewind restores files and chat on a real VM, after sleep/wake, rollover and an orcad restart (live/checkpoints-vm.ts, no model spend)', conductor: '0.19 (Claude), 0.44 (Codex) checkpoints in cloud', owner: 'checkpoints-vm', priority: 'P0' },
|
||||
// 1. Substrate
|
||||
{ id: 'sub.create', section: S.sub, feature: 'Hosted microVM per workspace, one call / one click', conductor: '0.78 GA', owner: 'core', priority: 'P0' },
|
||||
{ id: 'sub.size', section: S.sub, feature: 'Machine size: Standard 8 vCPU / 16 GB (Conductor parity)', conductor: 'Fixed 8 vCPU / 16 GB', owner: 'core', priority: 'P0' },
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
// POST /v1/billing/portal -> { url } Stripe Customer Portal
|
||||
// POST /v1/billing/team-plans {orgIds} other teams' plan state ("Switch to <team>"), read-only
|
||||
// POST /v1/billing/trial claim the team's one-time trial -> entitlement (trial.ts)
|
||||
// GET /v1/billing/usage?utcOffset= 30 days of sandbox hours; top members/sandboxes for admins
|
||||
// Stripe:
|
||||
// POST /v1/stripe/webhook signed events
|
||||
// Sandbox control plane (CONTROL_PLANE_TOKEN):
|
||||
@@ -50,6 +51,7 @@ import { OverageRequestSchema, updateOverage } from './overage'
|
||||
import { LiveModeRefusedError, StripeError, createStripeClient, type StripeClient } from './stripe'
|
||||
import { UsageReportSchema, flushMeterReports, recordUsage, validateSegment } from './usage'
|
||||
import { handleStripeWebhook } from './webhook'
|
||||
import { UsageHistoryQuerySchema, usageHistory } from './usage-history'
|
||||
import { renderReturnPage, returnOutcome } from './return-page'
|
||||
import {
|
||||
BindTeamSchema,
|
||||
@@ -316,6 +318,19 @@ export async function handleRequest(request: Request, env: Env, ctx: ExecutionCo
|
||||
return json(await desktopEntitlement(env, caller, request, now))
|
||||
}
|
||||
|
||||
case 'GET /v1/billing/usage': {
|
||||
// Any member reads the team's daily hours and their own; the breakdown is owners/admins only.
|
||||
const caller = await authenticateDesktop(env, request)
|
||||
if (!caller) {
|
||||
return json({ error: 'unauthorized' }, 401)
|
||||
}
|
||||
const query = UsageHistoryQuerySchema.safeParse(Object.fromEntries(url.searchParams))
|
||||
if (!query.success) {
|
||||
return json({ error: 'invalid_request' }, 400)
|
||||
}
|
||||
return json(await usageHistory(env.BILLING_DB, caller, now, query.data.utcOffset))
|
||||
}
|
||||
|
||||
case 'POST /v1/billing/trial': {
|
||||
// Any member may start the team's trial the first time they pick Orca Cloud (spec B1).
|
||||
const caller = await authenticateDesktop(env, request)
|
||||
|
||||
@@ -2,14 +2,23 @@
|
||||
// Opting in puts exactly one metered overage item, at STRIPE_PRICE_OVERAGE, on the Stripe
|
||||
// subscription: an item still on an older overage price is moved to the current one rather than a
|
||||
// second added (two items on the same meter would bill the same seconds twice). Opting out stops
|
||||
// metering immediately but leaves the item, so usage already reported is still invoiced.
|
||||
// metering immediately. The item is removed once it has nothing left to invoice (no meter report
|
||||
// this Stripe period): at once if none was sent, otherwise at a sync after the period rolls over,
|
||||
// so usage already reported is still invoiced and no $0 overage line is left on later invoices.
|
||||
import { z } from 'zod'
|
||||
import type { BillingCaller } from './auth'
|
||||
import { OPEN_STATUSES } from './checkout'
|
||||
import type { Env } from './env'
|
||||
import { planCatalog, planForPrice } from './plans'
|
||||
import type { StripeClient, StripeSubscription } from './stripe'
|
||||
import { accountSettings, currentSubscription, setOverageSettings, upsertSubscription, type SubscriptionRow } from './store'
|
||||
import {
|
||||
accountSettings,
|
||||
currentSubscription,
|
||||
meterReportsSince,
|
||||
setOverageSettings,
|
||||
upsertSubscription,
|
||||
type SubscriptionRow
|
||||
} from './store'
|
||||
|
||||
export const OverageRequestSchema = z
|
||||
.object({
|
||||
@@ -51,9 +60,35 @@ export async function updateOverage(
|
||||
? (await accountSettings(env.BILLING_DB, caller.accountId)).spend_cap_cents
|
||||
: request.spendCapCents
|
||||
await setOverageSettings(env.BILLING_DB, caller.accountId, { optIn: request.enabled, spendCapCents }, now)
|
||||
if (!request.enabled) {
|
||||
// Best effort: the opt-out already stops metering; a failed removal is retried by the next sync.
|
||||
await retireOverageItem(env, stripe, subscription, now).catch((error: unknown) => {
|
||||
console.error(JSON.stringify({ error: 'retire_overage_item', message: error instanceof Error ? error.message.slice(0, 200) : '' }))
|
||||
})
|
||||
}
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes an opted-out account's overage item once nothing on it is left to invoice: no meter
|
||||
* report (sent or pending) since the Stripe period began. Returns whether it removed one.
|
||||
*/
|
||||
export async function retireOverageItem(env: Env, stripe: StripeClient, subscription: SubscriptionRow, now: number): Promise<boolean> {
|
||||
if (!subscription.overage_item_id) {
|
||||
return false
|
||||
}
|
||||
const settings = await accountSettings(env.BILLING_DB, subscription.account_id)
|
||||
if (settings.overage_opt_in === 1) {
|
||||
return false
|
||||
}
|
||||
if ((await meterReportsSince(env.BILLING_DB, subscription.account_id, subscription.current_period_start)) > 0) {
|
||||
return false
|
||||
}
|
||||
await stripe.deleteSubscriptionItem(subscription.overage_item_id)
|
||||
await upsertSubscription(env.BILLING_DB, { ...subscription, overage_enabled: 0, overage_item_id: null, updated_at: now })
|
||||
return true
|
||||
}
|
||||
|
||||
/** A metered item that is not a seat price and not the current overage price: an older overage price. */
|
||||
function isStaleOverageItem(env: Env, item: StripeSubscription['items']['data'][number]): boolean {
|
||||
return (
|
||||
@@ -84,6 +119,17 @@ async function ensureOverageItem(env: Env, stripe: StripeClient, subscription: S
|
||||
}
|
||||
return replace.id
|
||||
}
|
||||
// Idempotent per subscription+price, so a retried opt-in cannot add a second item.
|
||||
return (await stripe.addSubscriptionItem({ subscription: subscription.stripe_subscription_id, price: env.STRIPE_PRICE_OVERAGE })).id
|
||||
// Idempotent per subscription+price, so a retried opt-in cannot add a second item. Opting out
|
||||
// can remove the item, so a later opt-in may get the removed item's id replayed (Stripe keeps
|
||||
// idempotent answers for 24 hours): then add again under a key that names the removed item.
|
||||
let after: string | undefined
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
const added = await stripe.addSubscriptionItem({ subscription: subscription.stripe_subscription_id, price: env.STRIPE_PRICE_OVERAGE, after })
|
||||
const fresh = await stripe.retrieveSubscription(subscription.stripe_subscription_id)
|
||||
if (fresh.items.data.some((item) => item.id === added.id)) {
|
||||
return added.id
|
||||
}
|
||||
after = added.id
|
||||
}
|
||||
throw new Error('overage_item_replayed')
|
||||
}
|
||||
|
||||
@@ -220,6 +220,18 @@ export async function insertUsage(db: D1Database, usage: UsageInsert): Promise<b
|
||||
return (result?.meta.changes ?? 0) > 0
|
||||
}
|
||||
|
||||
/** Meter reports (any status) for usage that ended since `since`, plus any still pending. */
|
||||
export async function meterReportsSince(db: D1Database, accountId: string, since: number): Promise<number> {
|
||||
const row = await db
|
||||
.prepare(
|
||||
`SELECT COUNT(*) AS n FROM meter_reports m JOIN usage_events p ON p.usage_id = m.usage_id
|
||||
WHERE p.account_id = ?1 AND (m.event_timestamp >= ?2 OR m.status = 'pending')`
|
||||
)
|
||||
.bind(accountId, since)
|
||||
.first<{ n: number }>()
|
||||
return row?.n ?? 0
|
||||
}
|
||||
|
||||
/** Overage seconds already metered (billed) in an allowance window. */
|
||||
export async function meteredSeconds(db: D1Database, accountId: string, windowStart: number): Promise<number> {
|
||||
const row = await db
|
||||
|
||||
@@ -143,13 +143,14 @@ export function createStripeClient(env: Env, fetchImpl: typeof fetch = fetch) {
|
||||
idempotencyKey
|
||||
)
|
||||
},
|
||||
addSubscriptionItem(args: { subscription: string; price: string }) {
|
||||
/** `after`: the id a replayed add returned for an item since removed, so this add is a new one. */
|
||||
addSubscriptionItem(args: { subscription: string; price: string; after?: string }) {
|
||||
return request<{ id: string }>(
|
||||
'POST',
|
||||
'/v1/subscription_items',
|
||||
// Metered: nothing to prorate; usage is billed in arrears.
|
||||
{ subscription: args.subscription, price: args.price, proration_behavior: 'none' },
|
||||
`overage-item:${args.subscription}:${args.price}`
|
||||
`overage-item:${args.subscription}:${args.price}${args.after ? `:after:${args.after}` : ''}`
|
||||
)
|
||||
},
|
||||
/** Moves an item to another price in place (an older overage price to the current one). */
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
// Usage history for Plan & billing: sandbox hours per day for the last 30 days, the caller's own
|
||||
// share, and (for owners and admins only) the top members and sandboxes. Read-only over
|
||||
// usage_events; hours are the same weighted seconds the included-hours meter counts. A segment
|
||||
// counts on the day it ended, as it counts in the allowance window it ended in.
|
||||
import { z } from 'zod'
|
||||
import type { BillingCaller } from './auth'
|
||||
|
||||
export const USAGE_HISTORY_DAYS = 30
|
||||
export const USAGE_HISTORY_TOP = 5
|
||||
const DAY_MS = 24 * 3600 * 1000
|
||||
|
||||
/** `utcOffset`: the viewer's minutes east of UTC, so days start at their local midnight. */
|
||||
export const UsageHistoryQuerySchema = z.object({
|
||||
utcOffset: z.coerce.number().int().min(-840).max(840).default(0)
|
||||
})
|
||||
|
||||
export type UsageHistoryTop<K extends string> = {
|
||||
top: Array<{ [key in K]: string } & { seconds: number }>
|
||||
/** Everyone (or everything) past the top entries, plus segments with no member recorded. */
|
||||
otherCount: number
|
||||
otherSeconds: number
|
||||
}
|
||||
|
||||
export type UsageHistory = {
|
||||
/** Oldest first, exactly USAGE_HISTORY_DAYS entries; `start` is the local midnight in epoch ms. */
|
||||
days: Array<{ start: number; seconds: number }>
|
||||
totalSeconds: number
|
||||
/** The caller's own sandbox hours in the same days. */
|
||||
yourSeconds: number
|
||||
/** Owners and admins only; null for members. */
|
||||
members: UsageHistoryTop<'userId'> | null
|
||||
sandboxes: UsageHistoryTop<'sandboxId'> | null
|
||||
}
|
||||
|
||||
/** Epoch ms of the local midnight that starts the oldest day shown. */
|
||||
export function usageHistoryStart(now: number, utcOffsetMinutes: number): number {
|
||||
const offset = utcOffsetMinutes * 60_000
|
||||
const today = Math.floor((now + offset) / DAY_MS) * DAY_MS - offset
|
||||
return today - (USAGE_HISTORY_DAYS - 1) * DAY_MS
|
||||
}
|
||||
|
||||
function topOf<K extends string>(
|
||||
key: K,
|
||||
rows: Array<{ id: string | null; seconds: number }>
|
||||
): UsageHistoryTop<K> {
|
||||
const named = rows.filter((row) => row.id !== null).sort((a, b) => b.seconds - a.seconds)
|
||||
const top = named.slice(0, USAGE_HISTORY_TOP)
|
||||
const rest = [...named.slice(USAGE_HISTORY_TOP), ...rows.filter((row) => row.id === null)]
|
||||
return {
|
||||
top: top.map((row) => ({ [key]: row.id, seconds: row.seconds }) as { [k in K]: string } & { seconds: number }),
|
||||
otherCount: rest.filter((row) => row.id !== null).length,
|
||||
otherSeconds: rest.reduce((sum, row) => sum + row.seconds, 0)
|
||||
}
|
||||
}
|
||||
|
||||
export async function usageHistory(
|
||||
db: D1Database,
|
||||
caller: BillingCaller,
|
||||
now: number,
|
||||
utcOffsetMinutes: number
|
||||
): Promise<UsageHistory> {
|
||||
const start = usageHistoryStart(now, utcOffsetMinutes)
|
||||
const range = 'account_id = ?1 AND ended_at >= ?2 AND ended_at <= ?3'
|
||||
const [byDay, mine, byMember, bySandbox] = await Promise.all([
|
||||
db
|
||||
.prepare(
|
||||
`SELECT CAST((ended_at - ?2) / ${DAY_MS} AS INTEGER) AS day, SUM(weighted_seconds) AS seconds
|
||||
FROM usage_events WHERE ${range} GROUP BY day`
|
||||
)
|
||||
.bind(caller.accountId, start, now)
|
||||
.all<{ day: number; seconds: number }>(),
|
||||
db
|
||||
.prepare(`SELECT COALESCE(SUM(weighted_seconds), 0) AS seconds FROM usage_events WHERE ${range} AND user_id = ?4`)
|
||||
.bind(caller.accountId, start, now, caller.userId)
|
||||
.first<{ seconds: number }>(),
|
||||
caller.canManage
|
||||
? db
|
||||
.prepare(`SELECT user_id AS id, SUM(weighted_seconds) AS seconds FROM usage_events WHERE ${range} GROUP BY user_id`)
|
||||
.bind(caller.accountId, start, now)
|
||||
.all<{ id: string | null; seconds: number }>()
|
||||
: null,
|
||||
caller.canManage
|
||||
? db
|
||||
.prepare(`SELECT sandbox_id AS id, SUM(weighted_seconds) AS seconds FROM usage_events WHERE ${range} GROUP BY sandbox_id`)
|
||||
.bind(caller.accountId, start, now)
|
||||
.all<{ id: string; seconds: number }>()
|
||||
: null
|
||||
])
|
||||
const days = Array.from({ length: USAGE_HISTORY_DAYS }, (_, index) => ({ start: start + index * DAY_MS, seconds: 0 }))
|
||||
for (const row of byDay.results) {
|
||||
const day = days[row.day]
|
||||
if (day) {
|
||||
day.seconds += row.seconds
|
||||
}
|
||||
}
|
||||
return {
|
||||
days,
|
||||
totalSeconds: days.reduce((sum, day) => sum + day.seconds, 0),
|
||||
yourSeconds: mine?.seconds ?? 0,
|
||||
members: byMember ? topOf('userId', byMember.results) : null,
|
||||
sandboxes: bySandbox ? topOf('sandboxId', bySandbox.results) : null
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,8 @@
|
||||
import type { Env } from './env'
|
||||
import { planForPrice } from './plans'
|
||||
import { allowsLiveMode, type StripeClient, type StripeSubscription } from './stripe'
|
||||
import { accountForCustomer, claimEvent, customerFor, finishEvent, upsertSubscription } from './store'
|
||||
import { accountForCustomer, claimEvent, currentSubscription, customerFor, finishEvent, upsertSubscription } from './store'
|
||||
import { retireOverageItem } from './overage'
|
||||
import { splitSecrets, verifyStripeSignature } from './webhook-signature'
|
||||
|
||||
const MAX_BODY_BYTES = 512 * 1024
|
||||
@@ -112,6 +113,15 @@ export async function syncSubscription(env: Env, stripe: StripeClient, subscript
|
||||
// Membership comes from auth, not Stripe: keep the stored count.
|
||||
member_count: null
|
||||
})
|
||||
if (overageItemId) {
|
||||
// An opted-out account's overage item goes once the period it was used in has been invoiced.
|
||||
const stored = await currentSubscription(db, accountId)
|
||||
if (stored?.stripe_subscription_id === subscription.id) {
|
||||
await retireOverageItem(env, stripe, stored, now).catch((error: unknown) => {
|
||||
console.error(JSON.stringify({ error: 'retire_overage_item', message: error instanceof Error ? error.message.slice(0, 200) : '' }))
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function handleStripeWebhook(env: Env, stripe: StripeClient, request: Request, now: number): Promise<Response> {
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
// Opting out of overage: nothing more is metered or billed, and the metered item comes off the
|
||||
// subscription once nothing on it is left to invoice (no $0 overage line on later invoices).
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { checkoutCompleted, stripeEvent } from './stripe-fake'
|
||||
import { createHarness } from './harness'
|
||||
|
||||
const HOUR = 3600
|
||||
const PERIOD_START = Math.floor(Date.now() / 1000) - 5 * 24 * HOUR
|
||||
const PERIOD_END = PERIOD_START + 30 * 24 * HOUR
|
||||
|
||||
async function optedInTeam() {
|
||||
const h = await createHarness()
|
||||
const token = await h.desktopToken({ sub: 'u1', org: 'o1', orgRole: 'owner', email: 'a@example.com' })
|
||||
const auth = { authorization: `Bearer ${token}` }
|
||||
await h.call('POST', '/v1/billing/checkout', { body: { plan: 'team', seats: 2 }, headers: auth })
|
||||
const customer = [...h.stripe.customers.keys()][0]!
|
||||
const subscription = h.stripe.putSubscription({
|
||||
customer,
|
||||
accountId: 'org:o1',
|
||||
basePrice: 'price_team_month',
|
||||
quantity: 2,
|
||||
periodStart: PERIOD_START,
|
||||
periodEnd: PERIOD_END
|
||||
})
|
||||
await h.webhook(checkoutCompleted({ customer, subscription: subscription.id, accountId: 'org:o1' }))
|
||||
const overage = (body: unknown) => h.call('POST', '/v1/billing/overage', { body, headers: auth })
|
||||
expect((await overage({ enabled: true })).status).toBe(200)
|
||||
const prices = () => subscription.items.data.map((item) => item.price.id)
|
||||
expect(prices()).toEqual(['price_team_month', 'price_overage'])
|
||||
let n = 0
|
||||
const use = (hours: number) => {
|
||||
const endedAt = Date.now() - 60_000
|
||||
return h.controlPlane('/v1/internal/usage', {
|
||||
usageId: `u-${n++}`,
|
||||
accountId: 'org:o1',
|
||||
sandboxId: 'sbx_1',
|
||||
machineSize: 'standard',
|
||||
startedAt: endedAt - hours * HOUR * 1000,
|
||||
endedAt
|
||||
})
|
||||
}
|
||||
const stored = () =>
|
||||
h.raw.prepare('SELECT overage_enabled, overage_item_id IS NOT NULL AS has_item FROM subscriptions').get()
|
||||
return { h, auth, subscription, overage, prices, use, stored }
|
||||
}
|
||||
|
||||
describe('overage opt-out', () => {
|
||||
it('removes the unused metered item at once, and opting back in adds it again', async () => {
|
||||
const { h, overage, prices, use, stored } = await optedInTeam()
|
||||
expect((await overage({ enabled: false })).status).toBe(200)
|
||||
expect(prices()).toEqual(['price_team_month'])
|
||||
expect(stored()).toEqual({ overage_enabled: 0, has_item: 0 })
|
||||
// Past the included hours with overage off: nothing is metered.
|
||||
for (let i = 0; i < 6; i++) {
|
||||
await use(24)
|
||||
}
|
||||
expect(h.stripe.meterEvents).toHaveLength(0)
|
||||
expect(h.raw.prepare('SELECT COUNT(*) AS n FROM meter_reports').get()).toEqual({ n: 0 })
|
||||
expect((await overage({ enabled: true })).status).toBe(200)
|
||||
expect(prices()).toEqual(['price_team_month', 'price_overage'])
|
||||
})
|
||||
|
||||
it('a $0 cap never meters, even with overage on', async () => {
|
||||
const { h, overage, use } = await optedInTeam()
|
||||
expect((await overage({ enabled: true, spendCapCents: 0 })).status).toBe(200)
|
||||
for (let i = 0; i < 6; i++) {
|
||||
await use(24)
|
||||
}
|
||||
expect(h.stripe.meterEvents).toHaveLength(0)
|
||||
expect(h.raw.prepare('SELECT COUNT(*) AS n FROM meter_reports').get()).toEqual({ n: 0 })
|
||||
})
|
||||
|
||||
it('keeps an item with usage to invoice until the period rolls over, then removes it', async () => {
|
||||
const { h, overage, prices, use, stored, subscription } = await optedInTeam()
|
||||
for (let i = 0; i < 5; i++) {
|
||||
await use(24)
|
||||
}
|
||||
await use(2)
|
||||
expect(h.stripe.meterEvents).toHaveLength(1)
|
||||
expect((await overage({ enabled: false })).status).toBe(200)
|
||||
// The 2 overage hours still have to be invoiced on this item.
|
||||
expect(prices()).toEqual(['price_team_month', 'price_overage'])
|
||||
await use(3)
|
||||
expect(h.stripe.meterEvents).toHaveLength(1)
|
||||
// A sync inside the same period keeps it.
|
||||
await h.webhook(stripeEvent('customer.subscription.updated', subscription))
|
||||
expect(prices()).toEqual(['price_team_month', 'price_overage'])
|
||||
// Renewal: the next period has nothing metered, so the sync takes the item off.
|
||||
for (const item of subscription.items.data) {
|
||||
item.current_period_start = PERIOD_END
|
||||
item.current_period_end = PERIOD_END + 30 * 24 * HOUR
|
||||
}
|
||||
await h.webhook(stripeEvent('customer.subscription.updated', subscription))
|
||||
expect(prices()).toEqual(['price_team_month'])
|
||||
expect(stored()).toEqual({ overage_enabled: 0, has_item: 0 })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,98 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { createHarness } from './harness'
|
||||
import { USAGE_HISTORY_DAYS, usageHistoryStart } from '../src/usage-history'
|
||||
|
||||
const HOUR = 3600
|
||||
const DAY_MS = 24 * 3600 * 1000
|
||||
// Tokens are checked against the real clock, so the fixture's "now" is real too.
|
||||
const NOW = Date.now()
|
||||
const utcMidnight = Math.floor(NOW / DAY_MS) * DAY_MS
|
||||
// Today's segment, kept inside today even just after midnight.
|
||||
const END = Math.max(utcMidnight, NOW - 60_000)
|
||||
|
||||
async function seeded() {
|
||||
const h = await createHarness()
|
||||
h.setNow(NOW)
|
||||
const insert = h.raw.prepare(
|
||||
`INSERT INTO usage_events (usage_id, account_id, sandbox_id, machine_size, started_at, ended_at, weighted_seconds,
|
||||
period_start, overage_seconds, created_at, user_id) VALUES (?, ?, ?, 'standard', ?, ?, ?, NULL, 0, ?, ?)`
|
||||
)
|
||||
let n = 0
|
||||
const add = (endedAt: number, hours: number, sandboxId: string, userId: string | null, account = 'org:o1') => {
|
||||
insert.run(`u${n++}`, account, sandboxId, endedAt - 60_000, endedAt, hours * HOUR, endedAt, userId)
|
||||
}
|
||||
add(END, 2, 'sbx_a', 'alice')
|
||||
add(END - DAY_MS, 1, 'sbx_b', 'bob')
|
||||
add(END - 3 * DAY_MS, 3, 'sbx_a', 'alice')
|
||||
// Six more members, half an hour each: three make the top five, three don't.
|
||||
for (const user of ['c', 'd', 'e', 'f', 'g', 'h']) {
|
||||
add(END - 5 * DAY_MS, 0.5, `sbx_${user}`, user)
|
||||
}
|
||||
// A segment from before members were recorded.
|
||||
add(END - 6 * DAY_MS, 0.25, 'sbx_old', null)
|
||||
// Outside the 30 days, and another team's: never counted.
|
||||
add(NOW - 31 * DAY_MS, 9, 'sbx_a', 'alice')
|
||||
add(NOW - DAY_MS, 9, 'sbx_z', 'zed', 'org:o2')
|
||||
return h
|
||||
}
|
||||
|
||||
async function read(h: Awaited<ReturnType<typeof seeded>>, role: string, sub = 'alice', query = '') {
|
||||
const token = await h.desktopToken({ sub, org: 'o1', orgRole: role })
|
||||
return h.call('GET', `/v1/billing/usage${query}`, { headers: { authorization: `Bearer ${token}` } })
|
||||
}
|
||||
|
||||
describe('GET /v1/billing/usage', () => {
|
||||
it('returns 30 local days of team hours and the owner/admin breakdown', async () => {
|
||||
const h = await seeded()
|
||||
const { status, body } = await read(h, 'owner')
|
||||
expect(status).toBe(200)
|
||||
expect(body.days).toHaveLength(USAGE_HISTORY_DAYS)
|
||||
expect(body.days.at(-1)).toEqual({ start: utcMidnight, seconds: 2 * HOUR })
|
||||
expect(body.days.at(-2).seconds).toBe(1 * HOUR)
|
||||
expect(body.days.at(-4).seconds).toBe(3 * HOUR)
|
||||
expect(body.totalSeconds).toBe(9.25 * HOUR)
|
||||
expect(body.yourSeconds).toBe(5 * HOUR)
|
||||
expect(body.members.top.map((m: { userId: string }) => m.userId).slice(0, 2)).toEqual(['alice', 'bob'])
|
||||
expect(body.members.top).toHaveLength(5)
|
||||
expect(body.members.otherCount).toBe(3)
|
||||
// Three members past the top five (1.5 hours) plus the unattributed quarter hour.
|
||||
expect(body.members.otherSeconds).toBe(1.75 * HOUR)
|
||||
expect(body.sandboxes.top[0]).toEqual({ sandboxId: 'sbx_a', seconds: 5 * HOUR })
|
||||
})
|
||||
|
||||
it('gives members the team chart and their own hours, never the breakdown', async () => {
|
||||
const h = await seeded()
|
||||
const { body } = await read(h, 'member', 'bob')
|
||||
expect(body.totalSeconds).toBe(9.25 * HOUR)
|
||||
expect(body.yourSeconds).toBe(1 * HOUR)
|
||||
expect(body.members).toBeNull()
|
||||
expect(body.sandboxes).toBeNull()
|
||||
})
|
||||
|
||||
it('starts days at the viewer’s local midnight', async () => {
|
||||
const h = await seeded()
|
||||
const { body } = await read(h, 'admin', 'alice', '?utcOffset=-480')
|
||||
// In UTC-8 a day starts at 08:00 UTC.
|
||||
const today = body.days.at(-1).start
|
||||
expect(new Date(today).getUTCHours()).toBe(8)
|
||||
expect(today).toBeLessThanOrEqual(NOW)
|
||||
expect(NOW - today).toBeLessThan(DAY_MS)
|
||||
expect(body.days[0].start).toBe(usageHistoryStart(NOW, -480))
|
||||
})
|
||||
|
||||
it('rejects a bad offset and an unsigned caller', async () => {
|
||||
const h = await seeded()
|
||||
expect((await read(h, 'owner', 'alice', '?utcOffset=9999')).status).toBe(400)
|
||||
expect((await h.call('GET', '/v1/billing/usage')).status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns zeroed days for a team with no usage', async () => {
|
||||
const h = await createHarness()
|
||||
h.setNow(NOW)
|
||||
const token = await h.desktopToken({ sub: 'u1', org: 'o9', orgRole: 'owner' })
|
||||
const { body } = await h.call('GET', '/v1/billing/usage', { headers: { authorization: `Bearer ${token}` } })
|
||||
expect(body.totalSeconds).toBe(0)
|
||||
expect(body.days.every((day: { seconds: number }) => day.seconds === 0)).toBe(true)
|
||||
expect(body.members).toEqual({ top: [], otherCount: 0, otherSeconds: 0 })
|
||||
})
|
||||
})
|
||||
@@ -5,7 +5,7 @@
|
||||
# Everything printed here streams live to the desktop build log.
|
||||
#
|
||||
# Env from the control plane (validated there): ORCA_BUILD_REPOS (`<url>|<branch or empty>|<dir>|
|
||||
# <git auth header or empty>` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER, plus
|
||||
# <git auth header or empty>` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER and ORCA_CLONE_FILTER, plus
|
||||
# the org secrets the environment names. `::orca-step:: <name>` lines mark progress.
|
||||
# Exit codes: 10 clone, 20 install script, 30 recording the result.
|
||||
set -uo pipefail
|
||||
@@ -39,7 +39,8 @@ while IFS='|' read -r url branch dir header; do
|
||||
echo "Cloning $url${branch:+ ($branch)}"
|
||||
rm -rf -- "$dest"
|
||||
# The clone's own error shows only when it really failed (an empty repo is recovered below).
|
||||
if ! git "${git_auth[@]}" clone --quiet ${branch:+--branch "$branch"} -- "$url" "$dest" 2>"$OUT/clone.err"; then
|
||||
# ORCA_CLONE_FILTER (automatic environments: blob:none) keeps history and trees, not every old blob.
|
||||
if ! git "${git_auth[@]}" clone --quiet ${ORCA_CLONE_FILTER:+--filter="$ORCA_CLONE_FILTER"} ${branch:+--branch "$branch"} -- "$url" "$dest" 2>"$OUT/clone.err"; then
|
||||
refs=0
|
||||
git "${git_auth[@]}" ls-remote --exit-code -- "$url" >/dev/null 2>&1 || refs=$?
|
||||
if [ -n "$branch" ] && [ "$refs" -eq 2 ]; then
|
||||
|
||||
+55
-20
@@ -68,9 +68,62 @@ clone_failure_reason() {
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
# Brings a prebuilt checkout (environment build) up to date: fetches only what changed on the target
|
||||
# branch (ORCA_REPO_REF, else the build's branch) and checks it out. A branch the remote doesn't have
|
||||
# yet (a new workspace branch) starts from the build's branch, freshly fetched. Progress goes to stderr.
|
||||
update_repo() {
|
||||
local base target status
|
||||
base="$(git -C "$P" symbolic-ref --quiet --short HEAD 2>/dev/null || true)"
|
||||
target="${ref:-$base}"
|
||||
[ -n "$target" ] || return 0
|
||||
timeout "$CLONE_TIMEOUT_S" git ${auth[@]+"${auth[@]}"} -C "$P" fetch --progress origin "+refs/heads/$target:refs/remotes/origin/$target"
|
||||
status=$?
|
||||
if [ "$status" -eq 0 ]; then
|
||||
# -f: the install may have rewritten tracked files (a lockfile); the branch's version wins.
|
||||
git -C "$P" checkout --quiet -f -B "$target" "origin/$target" --
|
||||
return $?
|
||||
fi
|
||||
[ "$status" -eq 124 ] && return 124
|
||||
{ [ -n "$base" ] && [ "$base" != "$target" ]; } || return "$status"
|
||||
timeout "$CLONE_TIMEOUT_S" git ${auth[@]+"${auth[@]}"} -C "$P" fetch --progress origin "+refs/heads/$base:refs/remotes/origin/$base" || return $?
|
||||
git -C "$P" checkout --quiet -f -B "$target" "origin/$base" --
|
||||
}
|
||||
|
||||
# Runs clone_repo or update_repo detached (own session, no inherited stdio), so the start command
|
||||
# returns while it runs; $CLONE_DIR/state reads running, then done or "failed <reason>".
|
||||
run_detached() {
|
||||
echo running >"$CLONE_DIR/state"
|
||||
: >"$CLONE_DIR/progress.log"
|
||||
export -f clone_repo update_repo first_commit clone_failure_reason
|
||||
export P CLONE_DIR CLONE_TIMEOUT_S ORCA_REPO_URL ref
|
||||
export ORCA_PRELUDE_AUTH="${ORCA_GIT_EXTRAHEADER:-}" ORCA_PRELUDE_STEP="$1"
|
||||
setsid bash -c '
|
||||
auth=()
|
||||
[ -n "$ORCA_PRELUDE_AUTH" ] && auth=(-c "http.https://github.com/.extraheader=$ORCA_PRELUDE_AUTH")
|
||||
unset ORCA_PRELUDE_AUTH
|
||||
"$ORCA_PRELUDE_STEP" >>"$CLONE_DIR/progress.log" 2>&1
|
||||
status=$?
|
||||
if [ "$status" -eq 0 ]; then
|
||||
echo done >"$CLONE_DIR/state.next"
|
||||
elif [ "$ORCA_PRELUDE_STEP" = update_repo ]; then
|
||||
# Not fatal: the build'"'"'s checkout is there, just older. The status says so; the create goes on.
|
||||
echo "done stale" >"$CLONE_DIR/state.next"
|
||||
else
|
||||
echo "failed $(clone_failure_reason "$status" "$CLONE_DIR/progress.log")" >"$CLONE_DIR/state.next"
|
||||
fi
|
||||
mv -f "$CLONE_DIR/state.next" "$CLONE_DIR/state"
|
||||
' </dev/null >/dev/null 2>&1 &
|
||||
}
|
||||
|
||||
if [ ! -e "$P" ] && [ -n "${ORCA_ENV_REPO_DIR:-}" ] && [ -d "$ROOT/$ORCA_ENV_REPO_DIR/.git" ]; then
|
||||
ln -s "$ROOT/$ORCA_ENV_REPO_DIR" "$P"
|
||||
if [ -n "$ref" ] && [ "$(git -C "$P" symbolic-ref --quiet --short HEAD 2>/dev/null)" != "$ref" ]; then
|
||||
if [ "${ORCA_CLONE_BACKGROUND:-}" = 1 ]; then
|
||||
# The desktop shows this as "Update repository" (GET /v1/sandboxes/:id/clone): fetch what changed
|
||||
# since the build, in the background. A failure leaves the build's commit, which still opens.
|
||||
mkdir -p "$CLONE_DIR"
|
||||
run_detached update_repo
|
||||
elif [ -n "$ref" ] && [ "$(git -C "$P" symbolic-ref --quiet --short HEAD 2>/dev/null)" != "$ref" ]; then
|
||||
if timeout 60 git "${auth[@]}" -C "$P" fetch --quiet origin "+refs/heads/$ref:refs/remotes/origin/$ref"; then
|
||||
# -f: the install may have rewritten tracked files (a lockfile); the branch's version wins.
|
||||
git -C "$P" checkout --quiet -f -B "$ref" "origin/$ref" -- ||
|
||||
@@ -83,25 +136,7 @@ if [ ! -e "$P" ] && [ -n "${ORCA_ENV_REPO_DIR:-}" ] && [ -d "$ROOT/$ORCA_ENV_REP
|
||||
elif [ ! -e "$P" ] && [ -n "${ORCA_REPO_URL:-}" ]; then
|
||||
mkdir -p "$P" "$CLONE_DIR"
|
||||
if [ "${ORCA_CLONE_BACKGROUND:-}" = 1 ]; then
|
||||
echo running >"$CLONE_DIR/state"
|
||||
: >"$CLONE_DIR/progress.log"
|
||||
# Detached (own session, no inherited stdio): the start command returns while this runs.
|
||||
export -f clone_repo first_commit clone_failure_reason
|
||||
export P CLONE_DIR CLONE_TIMEOUT_S ORCA_REPO_URL ref
|
||||
export ORCA_PRELUDE_AUTH="${ORCA_GIT_EXTRAHEADER:-}"
|
||||
setsid bash -c '
|
||||
auth=()
|
||||
[ -n "$ORCA_PRELUDE_AUTH" ] && auth=(-c "http.https://github.com/.extraheader=$ORCA_PRELUDE_AUTH")
|
||||
unset ORCA_PRELUDE_AUTH
|
||||
clone_repo >>"$CLONE_DIR/progress.log" 2>&1
|
||||
status=$?
|
||||
if [ "$status" -eq 0 ]; then
|
||||
echo done >"$CLONE_DIR/state.next"
|
||||
else
|
||||
echo "failed $(clone_failure_reason "$status" "$CLONE_DIR/progress.log")" >"$CLONE_DIR/state.next"
|
||||
fi
|
||||
mv -f "$CLONE_DIR/state.next" "$CLONE_DIR/state"
|
||||
' </dev/null >/dev/null 2>&1 &
|
||||
run_detached clone_repo
|
||||
else
|
||||
clone_repo 2>"$CLONE_DIR/progress.log" || exit 1
|
||||
fi
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -178,9 +178,12 @@ ca_env=(NODE_USE_SYSTEM_CA="${NODE_USE_SYSTEM_CA:-1}")
|
||||
for name in NODE_EXTRA_CA_CERTS SSL_CERT_FILE; do
|
||||
if [ -n "${!name:-}" ]; then ca_env+=("$name=${!name}"); fi
|
||||
done
|
||||
# Ports panel: programs under $ORCA_HOME are the image's own services, and 23456 is Vercel's
|
||||
# sandbox-init (root, pid invisible to this user); neither is listed as the user's port.
|
||||
env -i HOME="$HOME" USER="$(id -un)" LANG=C.UTF-8 TERM=xterm-256color "${ca_env[@]}" \
|
||||
PATH="$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname "$system_node"):/usr/local/bin:/usr/bin:/bin" \
|
||||
ORCA_USER_DATA="$HOME/.orcad-data" ORCA_SANDBOX_ID="$ORCA_SANDBOX_ID" "${managed_env[@]}" \
|
||||
ORCA_HOST_MANAGED_LISTENER_PATHS="$ORCA_HOME" ORCA_HOST_MANAGED_UNOWNED_PORTS=23456 \
|
||||
NODE_COMPILE_CACHE="$ORCA_HOME/compile-cache" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR="$ORCA_HOME/startup-qualification" \
|
||||
ORCA_SESSION_ENV_NAMES="${secret_names[*]}" "${agent_env[@]}" \
|
||||
setsid nohup "$node" "$ORCA_HOME/bin/orcad-boot" --code-cache "$ORCA_HOME/compile-cache/orcad-server.v8" \
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Last time the control plane's own auth check passed for this credential (POST
|
||||
-- /v1/agent-credentials/claude/verify, or the check behind a provider 401). Recent passes answer verify
|
||||
-- without calling the provider again.
|
||||
ALTER TABLE agent_credentials ADD COLUMN verified_at INTEGER;
|
||||
@@ -0,0 +1,8 @@
|
||||
-- Automatic environments (src/auto-environments.ts): the first create of a repo that no environment
|
||||
-- lists makes a default environment for it (just the repo) and builds it in the background, so later
|
||||
-- creates boot with the repo already checked out. 'org' rows are made or edited by an admin; 'auto' rows
|
||||
-- were made by the system and are deleted after 14 days without a create (an admin's edit makes them 'org').
|
||||
ALTER TABLE environments ADD COLUMN kind TEXT NOT NULL DEFAULT 'org';
|
||||
-- Last create that booted from this environment (or asked for one for its repo).
|
||||
ALTER TABLE environments ADD COLUMN last_used_at INTEGER;
|
||||
CREATE INDEX environments_kind ON environments (kind, deleted_at);
|
||||
@@ -0,0 +1,35 @@
|
||||
-- Teammate profiles and Pokes (team-presence). Additive; older Workers ignore all of it.
|
||||
--
|
||||
-- member_usage_hours: model spend each member's own client reported, by UTC hour. Filled from the
|
||||
-- deltas of the cumulative sandboxes.token_usd_micros a client PATCHes, so it accrues from the
|
||||
-- deploy onward. Compute time comes from usage_outbox and is not copied here.
|
||||
CREATE TABLE IF NOT EXISTS member_usage_hours (
|
||||
account_id TEXT NOT NULL,
|
||||
user_id TEXT NOT NULL,
|
||||
hour INTEGER NOT NULL, -- floor(ms / 3_600_000)
|
||||
token_usd_micros INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (account_id, user_id, hour)
|
||||
);
|
||||
|
||||
-- Heatmap reads compute segments per account and time window.
|
||||
CREATE INDEX IF NOT EXISTS usage_outbox_account_started ON usage_outbox (account_id, started_at);
|
||||
|
||||
-- Pokes are opt-in (Settings → Experimental): a poke goes through only when both people have it on.
|
||||
CREATE TABLE IF NOT EXISTS member_poke_prefs (
|
||||
account_id TEXT NOT NULL,
|
||||
user_id TEXT NOT NULL,
|
||||
enabled INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (account_id, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS member_pokes (
|
||||
id TEXT PRIMARY KEY, -- pok_<24 hex>
|
||||
account_id TEXT NOT NULL,
|
||||
from_user_id TEXT NOT NULL,
|
||||
to_user_id TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
seen_at INTEGER
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS member_pokes_inbox ON member_pokes (account_id, to_user_id, created_at);
|
||||
CREATE INDEX IF NOT EXISTS member_pokes_sender ON member_pokes (account_id, from_user_id, created_at);
|
||||
@@ -0,0 +1,40 @@
|
||||
-- G14: every cloud workspace gets a short number in its account (W-123), allocated from a per-account
|
||||
-- counter so a number is never reused, even after the row is destroyed. Orgs get a URL slug for links
|
||||
-- (orca://cloud/<slug>/W-123). G13: each member's sidebar prefs for cloud workspaces (pins, their
|
||||
-- order, and the order of sections) live on the account so every device shows the same sidebar.
|
||||
ALTER TABLE sandboxes ADD COLUMN number INTEGER;
|
||||
|
||||
-- Backfill: existing rows numbered by creation order within their account.
|
||||
UPDATE sandboxes SET number = (
|
||||
SELECT COUNT(*) FROM sandboxes AS earlier
|
||||
WHERE earlier.account_id = sandboxes.account_id
|
||||
AND (earlier.created_at < sandboxes.created_at OR (earlier.created_at = sandboxes.created_at AND earlier.id <= sandboxes.id))
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX sandboxes_account_number ON sandboxes (account_id, number) WHERE number IS NOT NULL;
|
||||
|
||||
CREATE TABLE org_workspace_counters (
|
||||
account_id TEXT PRIMARY KEY,
|
||||
last_number INTEGER NOT NULL
|
||||
);
|
||||
|
||||
INSERT INTO org_workspace_counters (account_id, last_number)
|
||||
SELECT account_id, MAX(number) FROM sandboxes GROUP BY account_id;
|
||||
|
||||
CREATE TABLE org_slugs (
|
||||
account_id TEXT PRIMARY KEY,
|
||||
slug TEXT NOT NULL UNIQUE,
|
||||
created_at INTEGER NOT NULL,
|
||||
created_by TEXT NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE workspace_prefs (
|
||||
account_id TEXT NOT NULL,
|
||||
user_id TEXT NOT NULL,
|
||||
document TEXT NOT NULL,
|
||||
revision INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
updated_by_device TEXT,
|
||||
PRIMARY KEY (account_id, user_id)
|
||||
);
|
||||
@@ -0,0 +1,15 @@
|
||||
-- Files uploaded through the public API / MCP for an agent to read (G10 attachments). The bytes live
|
||||
-- on the workspace's own disk (/vercel/sandbox/attachments/<id>/<filename>, outside the repo); this
|
||||
-- row lets a message reference the file by id. Additive only.
|
||||
CREATE TABLE IF NOT EXISTS workspace_attachments (
|
||||
id TEXT PRIMARY KEY,
|
||||
sandbox_id TEXT NOT NULL,
|
||||
account_id TEXT NOT NULL,
|
||||
uploaded_by TEXT NOT NULL,
|
||||
filename TEXT NOT NULL,
|
||||
content_type TEXT NOT NULL,
|
||||
byte_size INTEGER NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS workspace_attachments_sandbox ON workspace_attachments (sandbox_id, created_at);
|
||||
@@ -1,46 +1,56 @@
|
||||
// A provider 401 on an Orca-account request (the proxy swapped the real credential in) is a signal, not a
|
||||
// verdict: one transient auth error must not sign a person out of every workspace. Before revoking, the
|
||||
// control plane makes one cheap server-side auth check with the real credential (no tokens spent) and
|
||||
// revokes only when that also says the credential is dead. Checks are rate-limited per person and agent
|
||||
// (agent_credentials.checked_at), and every decision is audited (agent_credential_audit).
|
||||
// revokes only when that also says the credential is dead. The desktop can ask for the same check before a
|
||||
// launch (POST /v1/agent-credentials/claude/verify). Checks are rate-limited per person and agent
|
||||
// (agent_credentials.checked_at), passes are remembered (verified_at), and every keep or revoke is audited
|
||||
// (agent_credential_audit).
|
||||
import type { AccountProvider } from './account-providers'
|
||||
import { markAgentCredentialRevoked, readUsableAgentCredential } from './agent-credentials'
|
||||
import type { Keyring } from './secrets-crypto'
|
||||
|
||||
/** At most one auth check (and so one revoke) per person and agent per minute. */
|
||||
export const CREDENTIAL_CHECK_INTERVAL_MS = 60_000
|
||||
/** A pass this recent answers verify without calling the provider. */
|
||||
export const CREDENTIAL_VERIFIED_FRESH_MS = 10 * 60_000
|
||||
|
||||
export type CredentialVerdict = 'valid' | 'invalid' | 'unknown'
|
||||
export type UnauthorizedOutcome = 'revoked' | 'kept' | 'skipped'
|
||||
export type CheckOutcome = 'revoked' | 'kept' | 'skipped'
|
||||
|
||||
type CheckContext = {
|
||||
db: D1Database
|
||||
keyring: Keyring
|
||||
provider: Pick<AccountProvider, 'agent' | 'verify'>
|
||||
userId: string
|
||||
now: number
|
||||
fetch: typeof fetch
|
||||
}
|
||||
|
||||
async function audit(
|
||||
db: D1Database,
|
||||
entry: { userId: string; agent: string; action: 'revoked' | 'kept'; reason: string; sandboxId: string; path: string; now: number }
|
||||
entry: { userId: string; agent: string; action: 'revoked' | 'kept'; reason: string; sandboxId: string | null; path: string | null; now: number }
|
||||
): Promise<void> {
|
||||
await db
|
||||
.prepare(
|
||||
`INSERT INTO agent_credential_audit (user_id, agent, action, reason, sandbox_id, upstream_path, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`
|
||||
)
|
||||
.bind(entry.userId, entry.agent, entry.action, entry.reason, entry.sandboxId, entry.path.split('?')[0]!.slice(0, 200), entry.now)
|
||||
.bind(entry.userId, entry.agent, entry.action, entry.reason, entry.sandboxId, entry.path ? entry.path.split('?')[0]!.slice(0, 200) : null, entry.now)
|
||||
.run()
|
||||
console.log(JSON.stringify({ event: `agent_credential_${entry.action}`, agent: entry.agent, by: 'egress_401', reason: entry.reason, sandboxId: entry.sandboxId }))
|
||||
console.log(JSON.stringify({ event: `agent_credential_${entry.action}`, agent: entry.agent, reason: entry.reason, sandboxId: entry.sandboxId }))
|
||||
}
|
||||
|
||||
export async function handleAccountUnauthorized(ctx: {
|
||||
db: D1Database
|
||||
keyring: Keyring
|
||||
provider: Pick<AccountProvider, 'agent' | 'verify'>
|
||||
userId: string
|
||||
sandboxId: string
|
||||
/** The upstream path that answered 401 (audit only; no query string). */
|
||||
path: string
|
||||
now: number
|
||||
fetch: typeof fetch
|
||||
}): Promise<UnauthorizedOutcome> {
|
||||
/**
|
||||
* One rate-limited auth check. Revokes only on a definite auth failure; a pass is remembered. 'skipped'
|
||||
* when another check ran within the minute or the credential isn't usable.
|
||||
*/
|
||||
async function checkCredential(
|
||||
ctx: CheckContext,
|
||||
trigger: { kind: 'egress_401'; sandboxId: string; path: string } | { kind: 'verify' }
|
||||
): Promise<CheckOutcome> {
|
||||
const { db, provider, userId, now } = ctx
|
||||
const agent = provider.agent
|
||||
// Claim the check slot: a burst of parallel 401s, or a flapping provider, makes one check a minute.
|
||||
// Claim the check slot: a burst of parallel 401s or verify calls makes one check a minute.
|
||||
const claimed = await db
|
||||
.prepare(
|
||||
`UPDATE agent_credentials SET checked_at = ?
|
||||
@@ -49,7 +59,7 @@ export async function handleAccountUnauthorized(ctx: {
|
||||
.bind(now, userId, agent, now - CREDENTIAL_CHECK_INTERVAL_MS)
|
||||
.run()
|
||||
if (!claimed.meta.changes) {
|
||||
console.log(JSON.stringify({ event: 'agent_credential_401_skipped', agent, sandboxId: ctx.sandboxId }))
|
||||
console.log(JSON.stringify({ event: 'agent_credential_check_skipped', agent, trigger: trigger.kind }))
|
||||
return 'skipped'
|
||||
}
|
||||
const real = await readUsableAgentCredential(db, ctx.keyring, userId, agent, now)
|
||||
@@ -57,12 +67,56 @@ export async function handleAccountUnauthorized(ctx: {
|
||||
return 'skipped'
|
||||
}
|
||||
const verdict: CredentialVerdict = provider.verify ? await provider.verify(real, ctx.fetch) : 'unknown'
|
||||
const base = { userId, agent, sandboxId: ctx.sandboxId, path: ctx.path, now }
|
||||
const where =
|
||||
trigger.kind === 'egress_401'
|
||||
? { sandboxId: trigger.sandboxId, path: trigger.path }
|
||||
: { sandboxId: null, path: null }
|
||||
const base = { userId, agent, now, ...where }
|
||||
if (verdict === 'valid') {
|
||||
await db.prepare(`UPDATE agent_credentials SET verified_at = ? WHERE user_id = ? AND agent = ?`).bind(now, userId, agent).run()
|
||||
}
|
||||
if (verdict !== 'invalid') {
|
||||
await audit(db, { ...base, action: 'kept', reason: verdict === 'valid' ? 'check_passed' : 'check_inconclusive' })
|
||||
// A pass on a pre-launch verify is routine; a 401 that didn't hold up, or any inconclusive check, is audited.
|
||||
if (trigger.kind === 'egress_401' || verdict === 'unknown') {
|
||||
const reason = verdict === 'valid' ? 'check_passed' : 'check_inconclusive'
|
||||
await audit(db, { ...base, action: 'kept', reason: trigger.kind === 'verify' ? `verify_${reason}` : reason })
|
||||
}
|
||||
return 'kept'
|
||||
}
|
||||
await markAgentCredentialRevoked(db, userId, agent, now)
|
||||
await audit(db, { ...base, action: 'revoked', reason: 'provider_401_confirmed_by_check' })
|
||||
await audit(db, {
|
||||
...base,
|
||||
action: 'revoked',
|
||||
reason: trigger.kind === 'verify' ? 'verify_confirmed_auth_failure' : 'provider_401_confirmed_by_check'
|
||||
})
|
||||
return 'revoked'
|
||||
}
|
||||
|
||||
export function handleAccountUnauthorized(
|
||||
ctx: CheckContext & { sandboxId: string; path: string }
|
||||
): Promise<CheckOutcome> {
|
||||
return checkCredential(ctx, { kind: 'egress_401', sandboxId: ctx.sandboxId, path: ctx.path })
|
||||
}
|
||||
|
||||
/**
|
||||
* Pre-launch verify: a pass within CREDENTIAL_VERIFIED_FRESH_MS answers at once; otherwise one check (rate
|
||||
* limited). Returns what happened; the caller re-reads the state.
|
||||
*/
|
||||
export async function verifyAccountCredential(
|
||||
ctx: CheckContext
|
||||
): Promise<{ outcome: CheckOutcome | 'fresh'; verifiedAt: number | null }> {
|
||||
const row = await ctx.db
|
||||
.prepare(`SELECT verified_at FROM agent_credentials WHERE user_id = ? AND agent = ?`)
|
||||
.bind(ctx.userId, ctx.provider.agent)
|
||||
.first<{ verified_at: number | null }>()
|
||||
const last = row?.verified_at ?? null
|
||||
if (last !== null && ctx.now - last < CREDENTIAL_VERIFIED_FRESH_MS) {
|
||||
return { outcome: 'fresh', verifiedAt: last }
|
||||
}
|
||||
const outcome = await checkCredential(ctx, { kind: 'verify' })
|
||||
const after = await ctx.db
|
||||
.prepare(`SELECT verified_at FROM agent_credentials WHERE user_id = ? AND agent = ?`)
|
||||
.bind(ctx.userId, ctx.provider.agent)
|
||||
.first<{ verified_at: number | null }>()
|
||||
return { outcome, verifiedAt: after?.verified_at ?? null }
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Account credentials for agents (agent-sources contract D11): one per person per agent, Personal only.
|
||||
// GET /v1/agent-credentials -> {claude, codex: {state, label?, expiresAt?}, providerEnabled, providerState}
|
||||
// PUT /v1/agent-credentials/claude {token, label?, expiresAt?} (flag S1; desktop main runs `claude setup-token`)
|
||||
// POST /v1/agent-credentials/claude/verify -> {claude, verifiedAt, checked} (pre-launch check, agent-credential-checks.ts)
|
||||
// DELETE /v1/agent-credentials/:agent
|
||||
// Values are never returned or logged. They leave the Worker only when the egress proxy swaps them into a
|
||||
// request from the person's own, unshared workspace (D10, D13). The Codex broker (flag S2) stores its tokens
|
||||
@@ -104,7 +105,8 @@ export async function putAgentCredential(
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?)
|
||||
ON CONFLICT (user_id, agent) DO UPDATE SET account_id = excluded.account_id, kek_id = excluded.kek_id,
|
||||
wrapped_dek = excluded.wrapped_dek, ciphertext = excluded.ciphertext, label = excluded.label,
|
||||
expires_at = excluded.expires_at, state = 'active', updated_at = excluded.updated_at`
|
||||
expires_at = excluded.expires_at, state = 'active', updated_at = excluded.updated_at,
|
||||
checked_at = NULL, verified_at = NULL`
|
||||
)
|
||||
.bind(input.userId, input.accountId, input.agent, sealed.kekId, sealed.wrappedDek, sealed.ciphertext, input.label ?? null, input.expiresAt ?? null, now, now)
|
||||
.run()
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
// Files for an agent to read (POST /v1/workspaces/:id/attachments, MCP upload_attachment). The
|
||||
// bytes go straight onto the workspace's own disk through the provider's files API, outside the
|
||||
// repo so they never show up in git status; D1 keeps only the metadata a message references.
|
||||
import { z } from 'zod'
|
||||
import { ApiError } from './caller'
|
||||
import { randomId } from './keys'
|
||||
|
||||
export const ATTACHMENTS_ROOT = '/vercel/sandbox/attachments'
|
||||
/** Raw uploads (curl --data-binary). Workers buffer the body, so this stays well under memory. */
|
||||
export const MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024
|
||||
/** JSON uploads carry base64 (MCP tool calls): the MCP request cap bounds them. */
|
||||
export const MAX_JSON_ATTACHMENT_BYTES = 5 * 1024 * 1024
|
||||
export const MAX_ATTACHMENTS_PER_MESSAGE = 10
|
||||
|
||||
export type AttachmentRow = {
|
||||
id: string
|
||||
sandbox_id: string
|
||||
account_id: string
|
||||
uploaded_by: string
|
||||
filename: string
|
||||
content_type: string
|
||||
byte_size: number
|
||||
path: string
|
||||
created_at: number
|
||||
}
|
||||
|
||||
export function attachmentView(row: AttachmentRow) {
|
||||
return {
|
||||
id: row.id,
|
||||
workspaceId: row.sandbox_id,
|
||||
filename: row.filename,
|
||||
contentType: row.content_type,
|
||||
byteSize: row.byte_size,
|
||||
path: row.path,
|
||||
createdAt: row.created_at
|
||||
}
|
||||
}
|
||||
|
||||
/** A name safe for one path segment: ASCII letters, digits, `._-` and spaces; never hidden, never empty. */
|
||||
export function safeFilename(raw: string): string {
|
||||
const base = raw.split(/[\\/]/).at(-1) ?? ''
|
||||
const cleaned = base
|
||||
.normalize('NFKD')
|
||||
.replace(/[\u0300-\u036f]/g, '')
|
||||
.replace(/[^A-Za-z0-9._ -]/g, '_')
|
||||
.replace(/^[.\s]+/, '')
|
||||
.trim()
|
||||
const capped = cleaned.length > 100 ? `${cleaned.slice(0, 80)}${cleaned.slice(cleaned.lastIndexOf('.')).slice(0, 20)}` : cleaned
|
||||
return capped || 'file'
|
||||
}
|
||||
|
||||
const ContentType = z.string().trim().min(3).max(127).regex(/^[\w.+-]+\/[\w.+-]+$/)
|
||||
|
||||
const JsonUpload = z
|
||||
.object({
|
||||
filename: z.string().min(1).max(255),
|
||||
contentType: ContentType.optional(),
|
||||
/** Base64 (standard or url-safe) file bytes. */
|
||||
data: z.string().min(1).max(Math.ceil((MAX_JSON_ATTACHMENT_BYTES * 4) / 3) + 4)
|
||||
})
|
||||
.strict()
|
||||
|
||||
function decodeBase64(data: string): Uint8Array {
|
||||
const normal = data.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '')
|
||||
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(normal)) {
|
||||
throw new ApiError(400, 'invalid_request', 'data: not base64')
|
||||
}
|
||||
const binary = atob(normal)
|
||||
const bytes = new Uint8Array(binary.length)
|
||||
for (let i = 0; i < binary.length; i++) {
|
||||
bytes[i] = binary.charCodeAt(i)
|
||||
}
|
||||
return bytes
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads an upload: JSON `{filename, contentType?, data}` (base64), or the raw bytes with
|
||||
* `?filename=` and the file's own Content-Type.
|
||||
*/
|
||||
export async function readUpload(request: Request, url: URL): Promise<{ filename: string; contentType: string; bytes: Uint8Array }> {
|
||||
const declared = (request.headers.get('content-type') ?? '').split(';')[0]!.trim().toLowerCase()
|
||||
const length = Number(request.headers.get('content-length') ?? NaN)
|
||||
if (declared === 'application/json') {
|
||||
if (length > MAX_JSON_ATTACHMENT_BYTES * 1.4) {
|
||||
throw new ApiError(413, 'too_large', `max ${MAX_JSON_ATTACHMENT_BYTES} bytes as JSON; upload larger files raw`)
|
||||
}
|
||||
const parsed = JsonUpload.safeParse(JSON.parse(await request.text()))
|
||||
if (!parsed.success) {
|
||||
const issue = parsed.error.issues[0]
|
||||
throw new ApiError(400, 'invalid_request', issue ? `${issue.path.join('.') || 'body'}: ${issue.message}` : undefined)
|
||||
}
|
||||
const bytes = decodeBase64(parsed.data.data)
|
||||
if (bytes.length > MAX_JSON_ATTACHMENT_BYTES) {
|
||||
throw new ApiError(413, 'too_large', `max ${MAX_JSON_ATTACHMENT_BYTES} bytes as JSON; upload larger files raw`)
|
||||
}
|
||||
return { filename: parsed.data.filename, contentType: parsed.data.contentType ?? 'application/octet-stream', bytes }
|
||||
}
|
||||
const filename = url.searchParams.get('filename')
|
||||
if (!filename || filename.length > 255) {
|
||||
throw new ApiError(400, 'invalid_request', 'filename: required query parameter for raw uploads')
|
||||
}
|
||||
if (length > MAX_ATTACHMENT_BYTES) {
|
||||
throw new ApiError(413, 'too_large', `max ${MAX_ATTACHMENT_BYTES} bytes`)
|
||||
}
|
||||
const bytes = new Uint8Array(await request.arrayBuffer())
|
||||
if (bytes.length > MAX_ATTACHMENT_BYTES) {
|
||||
throw new ApiError(413, 'too_large', `max ${MAX_ATTACHMENT_BYTES} bytes`)
|
||||
}
|
||||
const contentType = ContentType.safeParse(declared)
|
||||
return { filename, contentType: contentType.success ? contentType.data : 'application/octet-stream', bytes }
|
||||
}
|
||||
|
||||
export function newAttachment(input: { sandboxId: string; accountId: string; uploadedBy: string; filename: string; contentType: string; byteSize: number }, now: number): AttachmentRow {
|
||||
const id = randomId('att')
|
||||
const filename = safeFilename(input.filename)
|
||||
return {
|
||||
id,
|
||||
sandbox_id: input.sandboxId,
|
||||
account_id: input.accountId,
|
||||
uploaded_by: input.uploadedBy,
|
||||
filename,
|
||||
content_type: input.contentType,
|
||||
byte_size: input.byteSize,
|
||||
path: `${ATTACHMENTS_ROOT}/${id}/${filename}`,
|
||||
created_at: now
|
||||
}
|
||||
}
|
||||
|
||||
export async function insertAttachment(db: D1Database, row: AttachmentRow): Promise<void> {
|
||||
await db
|
||||
.prepare(
|
||||
`INSERT INTO workspace_attachments (id, sandbox_id, account_id, uploaded_by, filename, content_type, byte_size, path, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
)
|
||||
.bind(row.id, row.sandbox_id, row.account_id, row.uploaded_by, row.filename, row.content_type, row.byte_size, row.path, row.created_at)
|
||||
.run()
|
||||
}
|
||||
|
||||
/** The named attachments of this workspace, in the order given; 400 if any is unknown or elsewhere. */
|
||||
export async function resolveAttachments(db: D1Database, sandboxId: string, ids: readonly string[]): Promise<AttachmentRow[]> {
|
||||
if (ids.length === 0) {
|
||||
return []
|
||||
}
|
||||
const unique = [...new Set(ids)]
|
||||
const { results } = await db
|
||||
.prepare(`SELECT * FROM workspace_attachments WHERE sandbox_id = ? AND id IN (${unique.map(() => '?').join(', ')})`)
|
||||
.bind(sandboxId, ...unique)
|
||||
.all<AttachmentRow>()
|
||||
const byId = new Map(results.map((row) => [row.id, row]))
|
||||
const missing = unique.filter((id) => !byId.has(id))
|
||||
if (missing.length > 0) {
|
||||
throw new ApiError(400, 'invalid_request', `attachments: unknown in this workspace: ${missing.join(',').slice(0, 200)}`)
|
||||
}
|
||||
return unique.map((id) => byId.get(id)!)
|
||||
}
|
||||
|
||||
/** The message text an agent gets: the user's words, then where each attached file is on disk. */
|
||||
export function withAttachmentPaths(text: string, attachments: readonly AttachmentRow[]): string {
|
||||
if (attachments.length === 0) {
|
||||
return text
|
||||
}
|
||||
const lines = attachments.map((row) => `- ${row.path} (${row.content_type}, ${row.byte_size} bytes)`)
|
||||
return `${text}\n\nAttached files (read them from disk):\n${lines.join('\n')}`
|
||||
}
|
||||
@@ -109,6 +109,18 @@ async function settle(
|
||||
.run()
|
||||
}
|
||||
|
||||
/**
|
||||
* What the agent is typed: a teammate's message names its sender (W4: agents address them and
|
||||
* commit as them via `orca-git-as`); nobody can type a leading envelope to impersonate someone else.
|
||||
*/
|
||||
export async function agentText(db: D1Database, workspace: { user_id: string; account_id: string }, sentBy: string, body: string): Promise<string> {
|
||||
if (sentBy === workspace.user_id) {
|
||||
return parseSenderEnvelope(body).body
|
||||
}
|
||||
const name = (await memberNamesFor(db, workspace.account_id, [sentBy])).get(sentBy) ?? sentBy
|
||||
return withSenderEnvelope(body, { userId: sentBy, name })
|
||||
}
|
||||
|
||||
/**
|
||||
* Delivers one queued message: wakes the workspace if needed, then continues the named session or
|
||||
* starts a new agent session with the text as its first prompt.
|
||||
@@ -127,15 +139,7 @@ export async function deliverMessage(life: LifecycleDeps, message: MessageRow):
|
||||
row = (await resumeSandbox(life, row)).row
|
||||
}
|
||||
const sessionId = row.session_id!
|
||||
// A teammate's message names its sender (W4: agents address them and commit as them via
|
||||
// `orca-git-as`); nobody can type a leading envelope to impersonate someone else.
|
||||
const text =
|
||||
message.sent_by === row.user_id
|
||||
? parseSenderEnvelope(message.body).body
|
||||
: withSenderEnvelope(message.body, {
|
||||
userId: message.sent_by,
|
||||
name: (await memberNamesFor(life.db, message.account_id, [message.sent_by])).get(message.sent_by) ?? message.sent_by
|
||||
})
|
||||
const text = await agentText(life.db, row, message.sent_by, message.body)
|
||||
let handle: string
|
||||
if (message.session_handle) {
|
||||
await sendToSession(life.provider, sessionId, message.session_handle, text)
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
// GET /v1/models (MCP list_models): the agents a cloud workspace runs and the models/efforts each
|
||||
// accepts. Built from the same seed catalogs the desktop's model picker uses, so the two never
|
||||
// disagree; the VM's own CLI may know newer models, which session create also accepts.
|
||||
import {
|
||||
CLAUDE_SESSION_OPTION_CATALOG,
|
||||
CODEX_SESSION_OPTION_CATALOG
|
||||
} from '../../../../../src/shared/agent-session/options/agent-session-option-catalog-claude-codex'
|
||||
import {
|
||||
CURSOR_SESSION_OPTION_CATALOG,
|
||||
GEMINI_SESSION_OPTION_CATALOG
|
||||
} from '../../../../../src/shared/agent-session/options/agent-session-option-catalog-gemini-cursor'
|
||||
import { OPENCODE_LAUNCH_OPTION_CATALOG } from '../../../../../src/shared/agent-session/options/agent-session-option-catalog-opencode'
|
||||
import type { AgentSessionOptionCatalog, CatalogModel } from '../../../../../src/shared/agent-session/options/agent-session-option-catalog-types'
|
||||
import { AGENTS, type AgentId } from './vm-agent'
|
||||
|
||||
const LABELS: Record<AgentId, string> = {
|
||||
claude: 'Claude Code',
|
||||
codex: 'Codex',
|
||||
opencode: 'OpenCode',
|
||||
gemini: 'Gemini CLI',
|
||||
cursor: 'Cursor',
|
||||
copilot: 'GitHub Copilot'
|
||||
}
|
||||
|
||||
const CATALOGS: Partial<Record<AgentId, AgentSessionOptionCatalog>> = {
|
||||
claude: CLAUDE_SESSION_OPTION_CATALOG,
|
||||
codex: CODEX_SESSION_OPTION_CATALOG,
|
||||
gemini: GEMINI_SESSION_OPTION_CATALOG,
|
||||
cursor: CURSOR_SESSION_OPTION_CATALOG,
|
||||
opencode: OPENCODE_LAUNCH_OPTION_CATALOG
|
||||
}
|
||||
|
||||
/** Model ids travel as one argv entry (`--model=<id>`); this keeps them to what agent CLIs use. */
|
||||
export const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:/@[\]-]{0,127}$/
|
||||
export const EFFORT_ID = /^[a-z]{2,16}$/
|
||||
|
||||
function modelView(model: CatalogModel) {
|
||||
const effort = model.options.find((option) => option.id === 'effort')
|
||||
const efforts = effort?.kind.type === 'select' ? effort.kind.choices.map((choice) => String(choice.value)) : []
|
||||
return {
|
||||
id: model.id,
|
||||
label: model.label,
|
||||
description: model.description ?? null,
|
||||
default: model.isDefault === true,
|
||||
efforts,
|
||||
defaultEffort: effort?.kind.type === 'select' ? effort.kind.defaultValue : null,
|
||||
fastMode: model.options.some((option) => option.id === 'fastMode' || option.id === 'serviceTier')
|
||||
}
|
||||
}
|
||||
|
||||
export type ModelsView = ReturnType<typeof modelsView>
|
||||
|
||||
export function modelsView() {
|
||||
return {
|
||||
agents: AGENTS.map((agent) => {
|
||||
const models = (CATALOGS[agent]?.models ?? []).map(modelView)
|
||||
return {
|
||||
id: agent,
|
||||
label: LABELS[agent],
|
||||
default: agent === 'claude',
|
||||
// Null: the agent's own default (its CLI picks; nothing is passed).
|
||||
defaultModel: models.find((model) => model.default)?.id ?? null,
|
||||
models
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/** The efforts the catalog lists for this agent's model, or null when it lists none (any is passed through). */
|
||||
export function knownEfforts(agent: AgentId, model: string): string[] | null {
|
||||
const found = CATALOGS[agent]?.models.find((candidate) => candidate.id === model)
|
||||
if (!found) {
|
||||
return null
|
||||
}
|
||||
const efforts = modelView(found).efforts
|
||||
return efforts.length > 0 ? efforts : []
|
||||
}
|
||||
@@ -99,6 +99,53 @@ const schemas: Record<string, object> = {
|
||||
preview: { type: ['string', 'null'], description: 'Last few lines of the session' }
|
||||
}
|
||||
},
|
||||
NewSession: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
handle: { type: 'string', description: 'Session handle (term_…): pass as `session` to send_message' },
|
||||
workspaceId: { type: 'string' },
|
||||
agent: { type: 'string', enum: [...AGENTS] },
|
||||
model: { type: ['string', 'null'] },
|
||||
effort: { type: ['string', 'null'] },
|
||||
name: { type: ['string', 'null'] }
|
||||
}
|
||||
},
|
||||
Attachment: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'string', description: 'att_… — pass in a message\'s `attachments`' },
|
||||
workspaceId: { type: 'string' },
|
||||
filename: { type: 'string', description: 'Sanitized file name' },
|
||||
contentType: { type: 'string' },
|
||||
byteSize: { type: 'integer' },
|
||||
path: { type: 'string', description: 'Where the file is on the workspace disk (outside the repo)' },
|
||||
createdAt: { type: 'integer' }
|
||||
}
|
||||
},
|
||||
AgentModels: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'string', enum: [...AGENTS] },
|
||||
label: { type: 'string' },
|
||||
default: { type: 'boolean', description: 'The agent used when none is given' },
|
||||
defaultModel: { type: ['string', 'null'], description: "Null: the agent CLI's own default" },
|
||||
models: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'string' },
|
||||
label: { type: 'string' },
|
||||
description: { type: ['string', 'null'] },
|
||||
default: { type: 'boolean' },
|
||||
efforts: { type: 'array', items: { type: 'string' }, description: 'Values for `effort`; empty when the model takes none' },
|
||||
defaultEffort: { type: ['string', 'null'] },
|
||||
fastMode: { type: 'boolean' }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
Routine: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
@@ -213,6 +260,14 @@ export const OPERATIONS: Record<string, Record<string, Op>> = {
|
||||
'/v1/me': {
|
||||
get: { tags: ['Account'], summary: 'Who the token acts as', responses: { 200: { description: 'Caller', schema: obj({ accountId: { type: 'string' }, userId: { type: 'string' }, role: { type: 'string' }, scopes: { type: 'array', items: { type: 'string' } } }) } } }
|
||||
},
|
||||
'/v1/models': {
|
||||
get: {
|
||||
tags: ['Agents'],
|
||||
summary: 'Agents and models a session can run',
|
||||
description: 'Every agent CLI a cloud workspace ships, with the models, effort levels, defaults and fast-mode support the model picker knows. Pass `agent`, `model` and `effort` when creating a session. A model id newer than this list is passed to the agent CLI as is.',
|
||||
responses: { 200: { description: 'Agents', schema: obj({ agents: { type: 'array', items: ref('AgentModels') } }) } }
|
||||
}
|
||||
},
|
||||
'/v1/api-keys': {
|
||||
get: { tags: ['API keys'], sessionOnly: true, summary: 'List Orca API keys', description: 'Owners and admins see every key on the team; members see their own.', responses: { 200: { description: 'Keys', schema: list('keys', 'ApiKey') } } },
|
||||
post: {
|
||||
@@ -341,6 +396,39 @@ export const OPERATIONS: Record<string, Record<string, Op>> = {
|
||||
'/v1/workspaces/{id}/archive': {
|
||||
post: { tags: ['Workspaces'], scope: 'workspaces:write', summary: 'Archive: sleep and hide from default lists', params: [WS], responses: { 200: { description: 'Archived', schema: one('workspace', 'Workspace') } } }
|
||||
},
|
||||
'/v1/workspaces/{id}/unarchive': {
|
||||
post: {
|
||||
tags: ['Workspaces'],
|
||||
scope: 'workspaces:write',
|
||||
summary: 'Unarchive: back in default lists and running again',
|
||||
description: 'Owner only. Idempotent: a workspace that is not archived is returned unchanged.',
|
||||
params: [WS],
|
||||
responses: { 200: { description: 'Running', schema: one('workspace', 'Workspace') } }
|
||||
}
|
||||
},
|
||||
'/v1/workspaces/{id}/rename': {
|
||||
post: {
|
||||
tags: ['Workspaces'],
|
||||
scope: 'workspaces:write',
|
||||
summary: 'Rename a workspace',
|
||||
description: 'Changes the display name everywhere (desktop Home, phone, API). The git branch is not renamed.',
|
||||
params: [WS],
|
||||
body: obj({ name: { type: 'string', minLength: 1, maxLength: 100 } }, ['name']),
|
||||
responses: { 200: { description: 'Renamed', schema: one('workspace', 'Workspace') } }
|
||||
}
|
||||
},
|
||||
'/v1/workspaces/{id}/attachments': {
|
||||
post: {
|
||||
tags: ['Agents'],
|
||||
scope: 'messages:write',
|
||||
summary: 'Upload a file for an agent',
|
||||
description:
|
||||
'Puts a file on the workspace disk (outside the repo) and returns its id; pass up to 10 ids as `attachments` when sending a message or creating a session, and the agent is told where each file is. Send the raw bytes (`--data-binary @file`, the file\'s Content-Type, `?filename=`; up to 25 MB) or JSON `{filename, contentType, data}` with base64 data (up to 5 MB, what MCP clients use). A sleeping workspace is woken first.',
|
||||
params: [WS, { name: 'filename', in: 'query', description: 'File name, for raw uploads', schema: { type: 'string' } }],
|
||||
body: obj({ filename: { type: 'string' }, contentType: { type: 'string' }, data: { type: 'string', contentEncoding: 'base64' } }, ['filename', 'data']),
|
||||
responses: { 201: { description: 'Uploaded', schema: one('attachment', 'Attachment') }, 413: 'File too large' }
|
||||
}
|
||||
},
|
||||
'/v1/workspaces/{id}/messages': {
|
||||
get: { tags: ['Agents'], scope: 'workspaces:read', summary: 'Recent messages sent to this workspace', params: [WS], responses: { 200: { description: 'Messages', schema: list('messages', 'Message') } } },
|
||||
post: {
|
||||
@@ -349,7 +437,15 @@ export const OPERATIONS: Record<string, Record<string, Op>> = {
|
||||
summary: 'Send a message to an agent',
|
||||
description: 'Queues the message and returns 202 at once. A sleeping workspace is woken first. Without `session` a new agent session starts with the text as its prompt; with `session` the text is typed into that session. Poll the message for `delivered`.',
|
||||
params: [WS],
|
||||
body: obj({ text: { type: 'string', maxLength: 32000 }, agent: { type: 'string', enum: [...AGENTS] }, session: { type: 'string' } }, ['text']),
|
||||
body: obj(
|
||||
{
|
||||
text: { type: 'string', maxLength: 32000 },
|
||||
agent: { type: 'string', enum: [...AGENTS] },
|
||||
session: { type: 'string' },
|
||||
attachments: { type: 'array', maxItems: 10, items: { type: 'string' }, description: 'Attachment ids from POST /attachments' }
|
||||
},
|
||||
['text']
|
||||
),
|
||||
responses: { 202: { description: 'Queued', schema: one('message', 'Message') } }
|
||||
}
|
||||
},
|
||||
@@ -357,7 +453,50 @@ export const OPERATIONS: Record<string, Record<string, Op>> = {
|
||||
get: { tags: ['Agents'], scope: 'workspaces:read', summary: 'Delivery status of a message', params: [WS, idParam('messageId', 'Message id')], responses: { 200: { description: 'Message', schema: one('message', 'Message') } } }
|
||||
},
|
||||
'/v1/workspaces/{id}/sessions': {
|
||||
get: { tags: ['Agents'], scope: 'workspaces:read', summary: 'Agent sessions in a running workspace', params: [WS], responses: { 200: { description: 'Sessions (empty while sleeping)', schema: obj({ workspaceStatus: { type: 'string' }, sessions: { type: 'array', items: ref('Session') } }) } } }
|
||||
get: { tags: ['Agents'], scope: 'workspaces:read', summary: 'Agent sessions in a running workspace', params: [WS], responses: { 200: { description: 'Sessions (empty while sleeping)', schema: obj({ workspaceStatus: { type: 'string' }, sessions: { type: 'array', items: ref('Session') } }) } } },
|
||||
post: {
|
||||
tags: ['Agents'],
|
||||
scope: 'messages:write',
|
||||
summary: 'Start a new agent session (a new chat)',
|
||||
description:
|
||||
'Starts another agent session in the workspace, waking it first if it sleeps, and returns its handle once the agent is up. Optional: `model` and `effort` (see GET /v1/models; a known model with an effort it does not take answers 400), `name`, and a first `message` with `attachments`. Without `message` the agent waits for send_message.',
|
||||
params: [WS],
|
||||
body: obj({
|
||||
agent: { type: 'string', enum: [...AGENTS], default: 'claude' },
|
||||
model: { type: 'string' },
|
||||
effort: { type: 'string', description: 'Requires model' },
|
||||
name: { type: 'string', maxLength: 100 },
|
||||
message: { type: 'string', maxLength: 32000 },
|
||||
attachments: { type: 'array', maxItems: 10, items: { type: 'string' }, description: 'Requires message' }
|
||||
}),
|
||||
responses: { 201: { description: 'Started', schema: one('session', 'NewSession') } }
|
||||
}
|
||||
},
|
||||
'/v1/workspaces/{id}/sessions/{handle}/cancel': {
|
||||
post: {
|
||||
tags: ['Agents'],
|
||||
scope: 'messages:write',
|
||||
summary: "Stop the agent's current turn",
|
||||
description: "Interrupts the running turn (an Escape, as a person would press) and drops this session's queued messages. Nothing is interrupted while the workspace sleeps; queued messages are still dropped.",
|
||||
params: [WS, idParam('handle', 'Session handle (term_…)')],
|
||||
responses: {
|
||||
200: {
|
||||
description: 'Canceled',
|
||||
schema: obj({ workspaceId: { type: 'string' }, session: { type: 'string' }, interrupted: { type: 'boolean' }, canceledQueuedMessages: { type: 'integer' } })
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'/v1/workspaces/{id}/sessions/{handle}/rename': {
|
||||
post: {
|
||||
tags: ['Agents'],
|
||||
scope: 'messages:write',
|
||||
summary: 'Rename an agent session',
|
||||
description: 'Sets the session (tab) title the desktop and phone show. 409 while the workspace sleeps.',
|
||||
params: [WS, idParam('handle', 'Session handle (term_…)')],
|
||||
body: obj({ name: { type: 'string', minLength: 1, maxLength: 100 } }, ['name']),
|
||||
responses: { 200: { description: 'Renamed', schema: obj({ session: obj({ handle: { type: 'string' }, workspaceId: { type: 'string' }, name: { type: 'string' } }) }) } }
|
||||
}
|
||||
},
|
||||
'/v1/workspaces/{id}/sessions/{handle}': {
|
||||
get: {
|
||||
@@ -503,7 +642,15 @@ curl -X DELETE ${o}/v1/workspaces/$ID -H "Authorization: Bearer $ORCA_API_
|
||||
<p>Point any MCP client at <code>${o}/mcp</code> (Streamable HTTP). Clients that support OAuth register themselves and open an approval page in the browser: approve with a one-time code from Orca → Settings → Orca API keys → <i>Approve an app</i>, or with one of your API keys. The app never gets more than that key may do. Clients without OAuth can send an API key as a bearer token.</p>
|
||||
<pre>claude mcp add --transport http orca-cloud ${o}/mcp
|
||||
claude mcp add --transport http orca-cloud ${o}/mcp --header "Authorization: Bearer $ORCA_API_KEY"</pre>
|
||||
<p>Tools: whoami, list_projects, list_workspaces, get_workspace, create_workspace, sleep_workspace, wake_workspace, archive_workspace, destroy_workspace, send_message, get_message, list_sessions, read_session, list_routines, run_routine. They use the same scopes, rate limits and audit log as the REST API.</p>
|
||||
<p>Tools: whoami, list_models, list_projects, list_workspaces, get_workspace, create_workspace, rename_workspace, sleep_workspace, wake_workspace, archive_workspace, unarchive_workspace, destroy_workspace, create_session, list_sessions, read_session, rename_session, cancel_session, upload_attachment, send_message, get_message, list_routines, run_routine. They use the same scopes, rate limits and audit log as the REST API.</p>
|
||||
<p>There is no SQL search over transcripts. Chats are end-to-end encrypted on the workspace's own disk, so the control plane cannot read them to index. Use <code>read_session</code> to see what an agent did.</p>
|
||||
<h2>New chat, files, stop</h2>
|
||||
<pre>curl -s ${o}/v1/models -H "Authorization: Bearer $ORCA_API_KEY"
|
||||
curl -s ${o}/v1/workspaces/$ID/attachments?filename=bug.png -H "Authorization: Bearer $ORCA_API_KEY" \\
|
||||
-H 'content-type: image/png' --data-binary @bug.png
|
||||
curl -s ${o}/v1/workspaces/$ID/sessions -H "Authorization: Bearer $ORCA_API_KEY" -H 'content-type: application/json' \\
|
||||
-d '{"agent":"codex","model":"gpt-5.5","effort":"high","message":"Fix what the screenshot shows","attachments":["att_…"]}'
|
||||
curl -X POST ${o}/v1/workspaces/$ID/sessions/$HANDLE/cancel -H "Authorization: Bearer $ORCA_API_KEY"</pre>
|
||||
<h2>Limits and errors</h2>
|
||||
<div class="grid">
|
||||
<div class="card"><b>Rate limits</b>120 requests/min per key, 30 messages/min per user, 10 workspace creates/min per team. 429 responses carry <code>Retry-After</code>.</div>
|
||||
|
||||
@@ -12,9 +12,20 @@ import { allowed, authorize, canSee, isOrgAdmin, isWorkspaceOwner } from './acce
|
||||
import { ApiError, actorOf, authenticateApi, isAdmin, requireAdmin, requireScope, scopesForRole, type ApiCaller } from './caller'
|
||||
import { auditCaller, auditView, consumeRate, listAudit, rateHeaders, RateLimitedError, type RateLimit } from './audit'
|
||||
import { API_SCOPES, ADMIN_SCOPES, apiKeyView, getApiKey, listApiKeys, mintApiKey, revokeApiKey, type ApiScope } from './keys'
|
||||
import { deliverMessage, getMessage, listMessages, MAX_MESSAGE_CHARS, messageView, queueMessage } from './messages'
|
||||
import { agentText, deliverMessage, getMessage, listMessages, MAX_MESSAGE_CHARS, messageView, queueMessage } from './messages'
|
||||
import { getAccountSettings, putAccountSettings } from './settings'
|
||||
import { listSessions, readSession, VmAgentError } from './vm-agent'
|
||||
import { interruptSession, launchAgent, listSessions, readSession, renameSession, VmAgentError } from './vm-agent'
|
||||
import {
|
||||
attachmentView,
|
||||
insertAttachment,
|
||||
MAX_ATTACHMENTS_PER_MESSAGE,
|
||||
newAttachment,
|
||||
readUpload,
|
||||
resolveAttachments,
|
||||
withAttachmentPaths
|
||||
} from './attachments'
|
||||
import { EFFORT_ID, knownEfforts, MODEL_ID, modelsView } from './models'
|
||||
import { resumeSandbox } from '../lifecycle'
|
||||
import {
|
||||
archiveProject,
|
||||
archiveWorkspace,
|
||||
@@ -85,14 +96,32 @@ const CreateWorkspaceBody = z
|
||||
message: z.object({ text: z.string().min(1).max(MAX_MESSAGE_CHARS), agent: z.enum(AGENTS).optional() }).strict().optional()
|
||||
})
|
||||
.strict()
|
||||
const SessionHandle = z.string().regex(/^term_[A-Za-z0-9-]{1,80}$/)
|
||||
const AttachmentIds = z.array(z.string().regex(/^att_[A-Za-z0-9]{1,64}$/)).min(1).max(MAX_ATTACHMENTS_PER_MESSAGE)
|
||||
const MessageBody = z
|
||||
.object({
|
||||
text: z.string().min(1).max(MAX_MESSAGE_CHARS),
|
||||
agent: z.enum(AGENTS).optional(),
|
||||
/** A session handle from GET /sessions or a previous message: continue that conversation. */
|
||||
session: z.string().regex(/^term_[A-Za-z0-9-]{1,80}$/).optional()
|
||||
session: SessionHandle.optional(),
|
||||
/** Files uploaded with POST /attachments: their on-disk paths are appended for the agent. */
|
||||
attachments: AttachmentIds.optional()
|
||||
})
|
||||
.strict()
|
||||
const CreateSessionBody = z
|
||||
.object({
|
||||
agent: z.enum(AGENTS).optional(),
|
||||
model: z.string().regex(MODEL_ID, 'a model id from GET /v1/models').optional(),
|
||||
effort: z.string().regex(EFFORT_ID).optional(),
|
||||
name: Name.optional(),
|
||||
/** Optional first prompt; without it the agent starts idle and waits for send_message. */
|
||||
message: z.string().min(1).max(MAX_MESSAGE_CHARS).optional(),
|
||||
attachments: AttachmentIds.optional()
|
||||
})
|
||||
.strict()
|
||||
.refine((body) => !body.effort || body.model, { message: 'effort requires model', path: ['effort'] })
|
||||
.refine((body) => !body.attachments || body.message, { message: 'attachments require message', path: ['attachments'] })
|
||||
const RenameBody = z.object({ name: Name }).strict()
|
||||
|
||||
function json(body: unknown, status = 200, headers: Record<string, string> = {}): Response {
|
||||
return Response.json(body, { status, headers: { 'cache-control': 'no-store', ...headers } })
|
||||
@@ -152,7 +181,7 @@ import { parseWakeWait } from '../wire'
|
||||
import { MachineSizeInput } from '../machine-size'
|
||||
|
||||
export function isApiPath(pathname: string): boolean {
|
||||
return /^\/v1\/(me|api-keys|settings|audit|projects|workspaces|routines|oauth-approvals|oauth-grants)(\/|$)/.test(pathname)
|
||||
return /^\/v1\/(me|models|api-keys|settings|audit|projects|workspaces|routines|oauth-approvals|oauth-grants)(\/|$)/.test(pathname)
|
||||
}
|
||||
|
||||
export async function handleApi(request: Request, url: URL, env: Parameters<typeof authenticateApi>[0], ctx: ApiContext): Promise<Response> {
|
||||
@@ -243,6 +272,11 @@ async function route(request: Request, url: URL, caller: ApiCaller, ctx: ApiCont
|
||||
})
|
||||
}
|
||||
|
||||
if (resource === 'models' && !id && method === 'GET') {
|
||||
// Static catalog, no account data: any authenticated caller may read it.
|
||||
return json(modelsView())
|
||||
}
|
||||
|
||||
if (resource === 'api-keys') {
|
||||
if (caller.via !== 'session') {
|
||||
// Keys are made and revoked by a signed-in person, never by another key.
|
||||
@@ -435,7 +469,7 @@ async function route(request: Request, url: URL, caller: ApiCaller, ctx: ApiCont
|
||||
const life = () => requireLife(ctx)
|
||||
const mutate = async (action: string, run: () => Promise<WorkspaceRow>) => {
|
||||
requireScope(caller, 'workspaces:write')
|
||||
authorize(caller, row, action === 'wake' ? 'owner' : 'manage')
|
||||
authorize(caller, row, action === 'wake' || action === 'unarchive' ? 'owner' : 'manage')
|
||||
if (caller.via === 'workspace' && row.id === caller.sandboxId) {
|
||||
// An agent must not put its own VM to sleep or delete it from under itself.
|
||||
throw new ApiError(403, 'forbidden', 'own_workspace')
|
||||
@@ -477,6 +511,117 @@ async function route(request: Request, url: URL, caller: ApiCaller, ctx: ApiCont
|
||||
if (sub === 'archive' && method === 'POST') {
|
||||
return mutate('archive', () => archiveWorkspace(life(), row))
|
||||
}
|
||||
if (sub === 'unarchive' && method === 'POST') {
|
||||
if (row.status !== 'archived' && row.archived_at === null) {
|
||||
// Idempotent: a retry after success (or a never-archived workspace) is not an error.
|
||||
requireScope(caller, 'workspaces:write')
|
||||
authorize(caller, row, 'owner')
|
||||
return json({ workspace: workspaceView(row) })
|
||||
}
|
||||
// Back in default lists and running again (same path as waking an archived workspace).
|
||||
return mutate('unarchive', () => wakeWorkspace(life(), row))
|
||||
}
|
||||
if (sub === 'rename' && method === 'POST') {
|
||||
requireScope(caller, 'workspaces:write')
|
||||
authorize(caller, row, 'manage')
|
||||
const body = parse(RenameBody, await ctx.readJson())
|
||||
await ctx.db.prepare('UPDATE sandboxes SET name = ? WHERE id = ?').bind(body.name, row.id).run()
|
||||
await auditCaller(ctx.db, caller, { action: 'workspace.rename', targetType: 'workspace', targetId: row.id, detail: { chars: body.name.length } }, now)
|
||||
return json({ workspace: workspaceView({ ...row, name: body.name }) })
|
||||
}
|
||||
// The agent's VM, woken if it sleeps (sessions and files need a running sandbox).
|
||||
const runningSession = async (): Promise<string> => {
|
||||
if (row.status === 'archived' || row.archived_at !== null) {
|
||||
throw new ApiError(409, 'conflict', 'workspace_archived')
|
||||
}
|
||||
if (row.status === 'running' && row.session_id) {
|
||||
return row.session_id
|
||||
}
|
||||
const ready = await resumeSandbox(life(), row)
|
||||
return ready.row.session_id!
|
||||
}
|
||||
if (sub === 'sessions' && !subId && method === 'POST') {
|
||||
// A new chat: start another agent session in this workspace (optionally with a first prompt).
|
||||
requireScope(caller, 'messages:write')
|
||||
authorize(caller, row, 'open')
|
||||
const body = parse(CreateSessionBody, await ctx.readJson())
|
||||
const agent = body.agent ?? 'claude'
|
||||
if (body.model && body.effort) {
|
||||
const efforts = knownEfforts(agent, body.model)
|
||||
if (efforts && !efforts.includes(body.effort)) {
|
||||
throw new ApiError(400, 'invalid_request', `effort: ${body.model} takes ${efforts.length ? efforts.join(', ') : 'no effort'}`)
|
||||
}
|
||||
}
|
||||
if (body.message) {
|
||||
await consumeRate(ctx.db, messageBucket(caller), MESSAGES_PER_MINUTE, now)
|
||||
}
|
||||
const attachments = await resolveAttachments(ctx.db, row.id, body.attachments ?? [])
|
||||
const started = performance.now()
|
||||
const sessionId = await runningSession()
|
||||
// A teammate's first prompt names its sender, exactly like a message (deliverMessage).
|
||||
const prompt = body.message ? await agentText(ctx.db, row, caller.userId, withAttachmentPaths(body.message, attachments)) : null
|
||||
const handle = await launchAgent(life().provider, sessionId, agent, prompt, { model: body.model, effort: body.effort })
|
||||
if (body.name) {
|
||||
await renameSession(life().provider, sessionId, handle, body.name)
|
||||
}
|
||||
await auditCaller(
|
||||
ctx.db,
|
||||
caller,
|
||||
{ action: 'workspace.session.create', targetType: 'workspace', targetId: row.id, detail: { handle, agent, model: body.model ?? null, prompt: Boolean(prompt), attachments: attachments.length, ms: Math.round(performance.now() - started) } },
|
||||
ctx.now()
|
||||
)
|
||||
return json({ session: { handle, workspaceId: row.id, agent, model: body.model ?? null, effort: body.effort ?? null, name: body.name ?? null } }, 201)
|
||||
}
|
||||
if (sub === 'sessions' && subId && parts[4] && method === 'POST') {
|
||||
requireScope(caller, 'messages:write')
|
||||
authorize(caller, row, 'open')
|
||||
if (!SessionHandle.safeParse(subId).success) {
|
||||
throw new ApiError(404, 'not_found')
|
||||
}
|
||||
if (parts[4] === 'cancel' && !parts[5]) {
|
||||
// Queued messages for this session never get typed; the running turn gets an interrupt.
|
||||
const dropped = await ctx.db
|
||||
.prepare(`UPDATE workspace_messages SET status = 'failed', error = 'canceled', updated_at = ? WHERE sandbox_id = ? AND session_handle = ? AND status = 'queued'`)
|
||||
.bind(now, row.id, subId)
|
||||
.run()
|
||||
const running = row.status === 'running' && row.session_id !== null
|
||||
if (running) {
|
||||
await interruptSession(life().provider, row.session_id!, subId)
|
||||
}
|
||||
const canceledQueuedMessages = dropped.meta.changes ?? 0
|
||||
await auditCaller(ctx.db, caller, { action: 'workspace.session.cancel', targetType: 'workspace', targetId: row.id, detail: { handle: subId, interrupted: running, canceledQueuedMessages } }, ctx.now())
|
||||
return json({ workspaceId: row.id, session: subId, interrupted: running, canceledQueuedMessages })
|
||||
}
|
||||
if (parts[4] === 'rename' && !parts[5]) {
|
||||
const body = parse(RenameBody, await ctx.readJson())
|
||||
if (row.status !== 'running' || !row.session_id) {
|
||||
throw new ApiError(409, 'conflict', 'workspace_not_running')
|
||||
}
|
||||
await renameSession(life().provider, row.session_id, subId, body.name)
|
||||
await auditCaller(ctx.db, caller, { action: 'workspace.session.rename', targetType: 'workspace', targetId: row.id, detail: { handle: subId } }, ctx.now())
|
||||
return json({ session: { handle: subId, workspaceId: row.id, name: body.name } })
|
||||
}
|
||||
}
|
||||
if (sub === 'attachments' && !subId && method === 'POST') {
|
||||
requireScope(caller, 'messages:write')
|
||||
authorize(caller, row, 'open')
|
||||
const provider = life().provider
|
||||
if (!provider.writeFile) {
|
||||
throw new ApiError(503, 'not_configured')
|
||||
}
|
||||
await consumeRate(ctx.db, messageBucket(caller), MESSAGES_PER_MINUTE, now)
|
||||
const upload = await readUpload(request, url)
|
||||
const sessionId = await runningSession()
|
||||
const attachment = newAttachment(
|
||||
{ sandboxId: row.id, accountId: row.account_id, uploadedBy: caller.userId, filename: upload.filename, contentType: upload.contentType, byteSize: upload.bytes.length },
|
||||
now
|
||||
)
|
||||
const started = performance.now()
|
||||
await provider.writeFile(sessionId, attachment.path, upload.bytes)
|
||||
await insertAttachment(ctx.db, attachment)
|
||||
await auditCaller(ctx.db, caller, { action: 'workspace.attachment', targetType: 'workspace', targetId: row.id, detail: { attachmentId: attachment.id, bytes: attachment.byte_size, ms: Math.round(performance.now() - started) } }, ctx.now())
|
||||
return json({ attachment: attachmentView(attachment) }, 201)
|
||||
}
|
||||
if (sub === 'sessions' && !subId && method === 'GET') {
|
||||
requireScope(caller, 'workspaces:read')
|
||||
authorize(caller, row, 'open')
|
||||
@@ -485,7 +630,7 @@ async function route(request: Request, url: URL, caller: ApiCaller, ctx: ApiCont
|
||||
}
|
||||
return json({ workspaceStatus: 'running', sessions: await listSessions(life().provider, row.session_id) })
|
||||
}
|
||||
if (sub === 'sessions' && subId && method === 'GET') {
|
||||
if (sub === 'sessions' && subId && !parts[4] && method === 'GET') {
|
||||
requireScope(caller, 'workspaces:read')
|
||||
authorize(caller, row, 'owner')
|
||||
if (!/^term_[A-Za-z0-9-]{1,80}$/.test(subId)) {
|
||||
@@ -518,8 +663,10 @@ async function route(request: Request, url: URL, caller: ApiCaller, ctx: ApiCont
|
||||
const life = requireLife(ctx)
|
||||
await consumeRate(ctx.db, messageBucket(caller), MESSAGES_PER_MINUTE, now)
|
||||
const body = parse(MessageBody, await ctx.readJson())
|
||||
const queued = await queueMessage(ctx.db, { workspace: row, sentBy: caller.userId, agent: body.agent ?? 'claude', text: body.text, session: body.session }, now)
|
||||
await auditCaller(ctx.db, caller, { action: 'workspace.message', targetType: 'workspace', targetId: row.id, detail: { messageId: queued.id, chars: body.text.length, continues: Boolean(body.session) } }, now)
|
||||
const attachments = await resolveAttachments(ctx.db, row.id, body.attachments ?? [])
|
||||
const text = withAttachmentPaths(body.text, attachments)
|
||||
const queued = await queueMessage(ctx.db, { workspace: row, sentBy: caller.userId, agent: body.agent ?? 'claude', text, session: body.session }, now)
|
||||
await auditCaller(ctx.db, caller, { action: 'workspace.message', targetType: 'workspace', targetId: row.id, detail: { messageId: queued.id, chars: body.text.length, continues: Boolean(body.session), attachments: attachments.length } }, now)
|
||||
// Queued now, delivered in the background (waking the VM if it sleeps); poll the message.
|
||||
ctx.waitUntil(deliverMessage(life, queued))
|
||||
return json({ message: messageView(queued) }, 202, { location: `/v1/workspaces/${row.id}/messages/${queued.id}` })
|
||||
|
||||
@@ -78,14 +78,28 @@ async function orca(provider: SandboxProviderApi, sessionId: string, args: strin
|
||||
|
||||
const LaunchResult = z.object({ outcome: z.object({ kind: z.string(), handle: z.string().optional() }).loose() }).loose()
|
||||
|
||||
/** Starts a new agent session with `prompt` in the workspace; returns its terminal handle. */
|
||||
export async function launchAgent(provider: SandboxProviderApi, sessionId: string, agent: AgentId, prompt: string): Promise<string> {
|
||||
const result = LaunchResult.safeParse(
|
||||
await orca(provider, sessionId, ['agent', 'launch', '--agent', agent, '--worktree', `path:${PROJECT_ROOT}`, '--surface', 'terminal', `--prompt=${prompt}`], {
|
||||
prepare: true,
|
||||
timeoutMs: 90_000
|
||||
})
|
||||
)
|
||||
/**
|
||||
* Starts a new agent session in the workspace, optionally with a first prompt and a model/effort
|
||||
* pick (the CLI maps them onto the agent's own flags); returns its terminal handle.
|
||||
*/
|
||||
export async function launchAgent(
|
||||
provider: SandboxProviderApi,
|
||||
sessionId: string,
|
||||
agent: AgentId,
|
||||
prompt: string | null,
|
||||
options: { model?: string; effort?: string } = {}
|
||||
): Promise<string> {
|
||||
const args = ['agent', 'launch', '--agent', agent, '--worktree', `path:${PROJECT_ROOT}`, '--surface', 'terminal']
|
||||
if (options.model) {
|
||||
args.push(`--model=${options.model}`)
|
||||
if (options.effort) {
|
||||
args.push(`--effort=${options.effort}`)
|
||||
}
|
||||
}
|
||||
if (prompt) {
|
||||
args.push(`--prompt=${prompt}`)
|
||||
}
|
||||
const result = LaunchResult.safeParse(await orca(provider, sessionId, args, { prepare: true, timeoutMs: 90_000 }))
|
||||
const handle = result.success ? result.data.outcome.handle : undefined
|
||||
if (!handle) {
|
||||
throw new VmAgentError('agent_launch_failed')
|
||||
@@ -98,6 +112,19 @@ export async function sendToSession(provider: SandboxProviderApi, sessionId: str
|
||||
await orca(provider, sessionId, ['terminal', 'send', '--terminal', handle, `--text=${text}`, '--enter'], { timeoutMs: 60_000 })
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the agent's current turn: one Escape, which the shipped agent CLIs treat as "interrupt"
|
||||
* and which never quits an idle agent (Ctrl+C can, on a second press). Raw byte, no Enter.
|
||||
*/
|
||||
export async function interruptSession(provider: SandboxProviderApi, sessionId: string, handle: string): Promise<void> {
|
||||
await orca(provider, sessionId, ['terminal', 'send', '--terminal', handle, '--text=\u001b'], { timeoutMs: 30_000 })
|
||||
}
|
||||
|
||||
/** Renames an agent session (its terminal tab title, which the desktop and phone show too). */
|
||||
export async function renameSession(provider: SandboxProviderApi, sessionId: string, handle: string, title: string): Promise<void> {
|
||||
await orca(provider, sessionId, ['terminal', 'rename', '--terminal', handle, `--title=${title}`], { timeoutMs: 30_000 })
|
||||
}
|
||||
|
||||
const TerminalList = z.object({
|
||||
terminals: z.array(
|
||||
z.object({
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
// Automatic environments: Conductor-style "the repo is already there". An environment build (golden +
|
||||
// the repo checked out, snapshotted) is opt-in for admins; without one every create of a repo cloned it
|
||||
// from scratch (stablyai/orca: ~55 s). So the first create of a repo that no environment of the account
|
||||
// lists makes a default environment for it (just the repo, blobless, no install script) and builds it in
|
||||
// the background. Later creates boot from its active build (environments.ts resolveEnvironmentBoot) and
|
||||
// only fetch what changed. Scoped per account like every environment; the usual golden refresh keeps
|
||||
// it on the current image. Unused for 14 days it is deleted with its snapshots, unless an admin edited
|
||||
// it (that makes it an ordinary 'org' environment).
|
||||
import type { SandboxCaller } from './auth'
|
||||
import { listBuilds, startBuild, TERMINAL, type BuildConfig, type BuildDeps } from './environment-builds'
|
||||
import { canonicalRepoUrl, parseRepos, repoDir, type EnvironmentRow } from './environments'
|
||||
import { normalizeRepo } from './secrets'
|
||||
|
||||
export const AUTO_ENVIRONMENT_USER = 'system:auto-environment'
|
||||
export const AUTO_ENVIRONMENT_UNUSED_MS = 14 * 24 * 60 * 60_000
|
||||
/** A failed automatic build is retried by a later create, at most this often. */
|
||||
export const AUTO_RETRY_AFTER_MS = 60 * 60_000
|
||||
/** Same cap as admin-made environments. */
|
||||
const MAX_ENVIRONMENTS = 20
|
||||
|
||||
const log = (event: string, fields: Record<string, unknown>) => console.log(JSON.stringify({ event, ...fields }))
|
||||
|
||||
function randomId(): string {
|
||||
const bytes = crypto.getRandomValues(new Uint8Array(10))
|
||||
return `env_${Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')}`
|
||||
}
|
||||
|
||||
function systemCaller(accountId: string): SandboxCaller {
|
||||
// An org-less caller is its own admin (canAdminEnvironments); the build is billed to the account.
|
||||
return { userId: AUTO_ENVIRONMENT_USER, accountId }
|
||||
}
|
||||
|
||||
function autoConfig(environment: EnvironmentRow): BuildConfig {
|
||||
return {
|
||||
revision: environment.revision,
|
||||
repos: parseRepos(environment),
|
||||
installScript: environment.install_script,
|
||||
envVarNames: [],
|
||||
machineSize: environment.machine_size,
|
||||
// History and trees only: a smaller snapshot and a faster build; file contents load on demand.
|
||||
cloneFilter: 'blob:none'
|
||||
}
|
||||
}
|
||||
|
||||
export type AutoEnvironmentOutcome = 'created' | 'rebuilt' | 'exists' | 'skipped'
|
||||
|
||||
/**
|
||||
* A create of `repoUrl` booted without an environment: make (or retry building) the account's automatic
|
||||
* environment for it. Never throws; the create it rides behind already succeeded.
|
||||
*/
|
||||
export async function ensureAutoEnvironment(deps: BuildDeps, accountId: string, repoUrl: string): Promise<AutoEnvironmentOutcome> {
|
||||
try {
|
||||
return await ensure(deps, accountId, repoUrl)
|
||||
} catch (error) {
|
||||
log('auto_environment_failed', { error: String(error).slice(0, 200) })
|
||||
return 'skipped'
|
||||
}
|
||||
}
|
||||
|
||||
async function ensure(deps: BuildDeps, accountId: string, repoUrl: string): Promise<AutoEnvironmentOutcome> {
|
||||
const url = canonicalRepoUrl(repoUrl)
|
||||
const wanted = normalizeRepo(url)
|
||||
if (!url || !wanted) {
|
||||
return 'skipped'
|
||||
}
|
||||
const { results: environments } = await deps.db
|
||||
.prepare('SELECT * FROM environments WHERE account_id = ? AND deleted_at IS NULL')
|
||||
.bind(accountId)
|
||||
.all<EnvironmentRow>()
|
||||
const listing = environments.filter((row) => parseRepos(row).some((repo) => normalizeRepo(repo.url) === wanted))
|
||||
if (listing.some((row) => row.kind !== 'auto')) {
|
||||
// An admin's environment lists the repo: theirs to build, never ours to shadow.
|
||||
return 'exists'
|
||||
}
|
||||
const auto = listing[0]
|
||||
if (auto) {
|
||||
await touchEnvironment(deps.db, auto.id, deps.now())
|
||||
return (await retryFailedBuild(deps, auto)) ? 'rebuilt' : 'exists'
|
||||
}
|
||||
if (environments.length >= MAX_ENVIRONMENTS) {
|
||||
return 'skipped'
|
||||
}
|
||||
const now = deps.now()
|
||||
const id = randomId()
|
||||
// UNIQUE(account_id, name): a concurrent first create of the same repo inserts nothing here.
|
||||
await deps.db
|
||||
.prepare(
|
||||
`INSERT OR IGNORE INTO environments (id, account_id, name, repos, install_script, env_var_names, machine_size,
|
||||
revision, next_build_number, created_by, updated_by, created_at, updated_at, kind, last_used_at)
|
||||
VALUES (?, ?, ?, ?, '', '[]', 'standard', 1, 1, ?, ?, ?, ?, 'auto', ?)`
|
||||
)
|
||||
.bind(id, accountId, repoDir(url), JSON.stringify([{ url, defaultBranch: null }]), AUTO_ENVIRONMENT_USER,
|
||||
AUTO_ENVIRONMENT_USER, now, now, now)
|
||||
.run()
|
||||
const environment = await deps.db
|
||||
.prepare('SELECT * FROM environments WHERE id = ? AND deleted_at IS NULL')
|
||||
.bind(id)
|
||||
.first<EnvironmentRow>()
|
||||
if (!environment) {
|
||||
return 'exists'
|
||||
}
|
||||
const build = await startBuild(deps, systemCaller(accountId), environment, { config: autoConfig(environment) })
|
||||
log('auto_environment_created', { environmentId: id, buildId: build.id })
|
||||
return 'created'
|
||||
}
|
||||
|
||||
/** No active build, none in flight, and the last one failed a while ago: try once more. */
|
||||
async function retryFailedBuild(deps: BuildDeps, environment: EnvironmentRow): Promise<boolean> {
|
||||
if (environment.active_build_id) {
|
||||
return false
|
||||
}
|
||||
const [last] = await listBuilds(deps.db, environment.id, 1)
|
||||
if (last && (!TERMINAL.has(last.status) || deps.now() - (last.finished_at ?? last.created_at) < AUTO_RETRY_AFTER_MS)) {
|
||||
return false
|
||||
}
|
||||
await startBuild(deps, systemCaller(environment.account_id), environment, { config: autoConfig(environment) })
|
||||
return true
|
||||
}
|
||||
|
||||
/** A create booted from (or asked for) this environment. */
|
||||
export async function touchEnvironment(db: D1Database, environmentId: string, now: number): Promise<void> {
|
||||
await db.prepare('UPDATE environments SET last_used_at = ? WHERE id = ?').bind(now, environmentId).run()
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the environment and every snapshot it built (live workspaces run on their own disks).
|
||||
* Shared by an admin's Delete and the automatic expiry.
|
||||
*/
|
||||
export async function deleteEnvironmentAndSnapshots(
|
||||
deps: Pick<BuildDeps, 'db' | 'provider' | 'now'>,
|
||||
environmentId: string
|
||||
): Promise<void> {
|
||||
await deps.db
|
||||
.prepare('UPDATE environments SET deleted_at = ?, active_build_id = NULL WHERE id = ?')
|
||||
.bind(deps.now(), environmentId)
|
||||
.run()
|
||||
const { results } = await deps.db
|
||||
.prepare(`SELECT id, snapshot_id FROM environment_builds WHERE environment_id = ? AND snapshot_id IS NOT NULL AND snapshot_deleted_at IS NULL`)
|
||||
.bind(environmentId)
|
||||
.all<{ id: string; snapshot_id: string }>()
|
||||
for (const row of results) {
|
||||
await deps.provider.deleteSnapshot(row.snapshot_id).catch(() => undefined)
|
||||
await deps.db.prepare('UPDATE environment_builds SET snapshot_deleted_at = ? WHERE id = ?').bind(deps.now(), row.id).run()
|
||||
}
|
||||
}
|
||||
|
||||
/** Cron: automatic environments no create used for 14 days go, with their snapshots. */
|
||||
export async function expireAutoEnvironments(deps: BuildDeps): Promise<number> {
|
||||
const cutoff = deps.now() - AUTO_ENVIRONMENT_UNUSED_MS
|
||||
const { results } = await deps.db
|
||||
.prepare(
|
||||
`SELECT id FROM environments WHERE kind = 'auto' AND deleted_at IS NULL
|
||||
AND COALESCE(last_used_at, created_at) < ? LIMIT 20`
|
||||
)
|
||||
.bind(cutoff)
|
||||
.all<{ id: string }>()
|
||||
let expired = 0
|
||||
for (const { id } of results) {
|
||||
const inFlight = (await listBuilds(deps.db, id, 5)).some((build) => !TERMINAL.has(build.status))
|
||||
if (inFlight) {
|
||||
continue
|
||||
}
|
||||
await deleteEnvironmentAndSnapshots(deps, id)
|
||||
log('auto_environment_expired', { environmentId: id })
|
||||
expired++
|
||||
}
|
||||
return expired
|
||||
}
|
||||
@@ -40,7 +40,8 @@ export function parseCloneStatus(stdout: string): CloneStatus {
|
||||
if (state === 'none' || state === '') {
|
||||
return { state: 'none' }
|
||||
}
|
||||
if (state === 'done') {
|
||||
if (state === 'done' || state.startsWith('done ')) {
|
||||
// "done stale": an update after an environment boot failed; the build's checkout still opens.
|
||||
return { state: 'done' }
|
||||
}
|
||||
if (state.startsWith('failed')) {
|
||||
|
||||
@@ -23,10 +23,18 @@ export type Env = {
|
||||
GOLDEN_SNAPSHOT_REGION?: string
|
||||
/** Non-prod only: pin this image over the rotated active one (preview versions testing new VM entry points). */
|
||||
GOLDEN_SNAPSHOT_OVERRIDE?: string
|
||||
/** 'off': no automatic environments (auto-environments.ts); creates without one keep cloning. */
|
||||
AUTO_ENVIRONMENTS?: string
|
||||
/** Git as the sender: `on`, `accounts:<id>,<id>` or off (default). See memberGitEnabled in index.ts. */
|
||||
MEMBER_GIT_IDENTITY?: string
|
||||
/** How long after a member's own send their GitHub identity stays usable (default 30). */
|
||||
MEMBER_GIT_WINDOW_MINUTES?: string
|
||||
/**
|
||||
* Who sees a member's daily activity heatmap on their profile. `opt_in` (default): only members
|
||||
* who turned on "Pokes and activity". `team`: every teammate (Conductor's default). Config only,
|
||||
* so flipping it needs no migration.
|
||||
*/
|
||||
TEAMMATE_ACTIVITY_SHARING?: string
|
||||
/** `release:latest` | `release:v1.2.3`: build golden images from Orca's released orca-server tarball. */
|
||||
GOLDEN_IMAGE_SOURCE?: string
|
||||
/** TTL for Worker-built golden images; unset/0 keeps them until rotated out. */
|
||||
@@ -124,6 +132,12 @@ export type Env = {
|
||||
|
||||
/** Operator routes (/v1/internal/*): kill switch, drain, bindings. Secret, >= 32 chars; unset = no routes. */
|
||||
OPERATOR_TOKEN?: string
|
||||
/**
|
||||
* Auth's bearer for POST /v1/internal/org-members/removed only (PropelAuth offboarding and
|
||||
* Orca-side removals). Secret, >= 32 chars; lets auth push removals without holding the
|
||||
* operator token. The operator token is still accepted on that route.
|
||||
*/
|
||||
MEMBER_REMOVED_TOKEN?: string
|
||||
/** `true` refuses every create/resume/rollover (static kill switch; the D1 flag is the runtime one). */
|
||||
SANDBOX_CREATES_DISABLED?: string
|
||||
/** Warm pool size (pool.ts); unset or 0 = off. */
|
||||
|
||||
@@ -91,6 +91,8 @@ export type BuildConfig = {
|
||||
installScript: string
|
||||
envVarNames: string[]
|
||||
machineSize: MachineSize
|
||||
/** `git clone --filter`: automatic environments clone blobless (auto-environments.ts). */
|
||||
cloneFilter?: 'blob:none'
|
||||
}
|
||||
|
||||
export type BuildResult = {
|
||||
@@ -338,7 +340,8 @@ async function bootBuild(deps: BuildDeps, row: BuildRow, config: BuildConfig): P
|
||||
ORCA_BUILD_REPOS: lines.join('\n'),
|
||||
ORCA_INSTALL_SCRIPT_B64: base64(config.installScript),
|
||||
ORCA_LOCKFILES: LOCKFILES.join(' '),
|
||||
ORCA_DEPS_HOOK_B64: base64(ENVIRONMENT_DEPS_HOOK)
|
||||
ORCA_DEPS_HOOK_B64: base64(ENVIRONMENT_DEPS_HOOK),
|
||||
...(config.cloneFilter ? { ORCA_CLONE_FILTER: config.cloneFilter } : {})
|
||||
}
|
||||
log('environment_build_secrets', { buildId: row.id, injected: Object.keys(secrets).length, named: config.envVarNames.length })
|
||||
const commandId = await deps.provider.startCommand(box.session.id, {
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
// GET /v1/environments/:id/builds/:bid/events -> ndjson stream (environment-builds.ts)
|
||||
// POST /v1/environments/:id/builds/:bid/cancel | /activate -> {build} | {environment}
|
||||
// GET /v1/environments/:id/staleness -> {staleness}
|
||||
import { deleteEnvironmentAndSnapshots } from './auto-environments'
|
||||
import type { SandboxCaller } from './auth'
|
||||
import {
|
||||
activateBuild,
|
||||
@@ -163,16 +164,8 @@ export async function handleEnvironmentRoute(
|
||||
await cancelBuild(deps, caller, row).catch(() => undefined)
|
||||
}
|
||||
}
|
||||
await db.prepare('UPDATE environments SET deleted_at = ?, active_build_id = NULL WHERE id = ?').bind(deps.now(), envId).run()
|
||||
// No kept window once deleted: every build snapshot goes (live workspaces run on their own disks).
|
||||
const { results } = await db
|
||||
.prepare(`SELECT * FROM environment_builds WHERE environment_id = ? AND snapshot_id IS NOT NULL AND snapshot_deleted_at IS NULL`)
|
||||
.bind(envId)
|
||||
.all<BuildRow>()
|
||||
for (const row of results) {
|
||||
await deps.provider.deleteSnapshot(row.snapshot_id!).catch(() => undefined)
|
||||
await db.prepare('UPDATE environment_builds SET snapshot_deleted_at = ? WHERE id = ?').bind(deps.now(), row.id).run()
|
||||
}
|
||||
await deleteEnvironmentAndSnapshots(deps, envId)
|
||||
return json({ deleted: true })
|
||||
}
|
||||
return json({ error: 'not_found' }, 404)
|
||||
|
||||
@@ -31,6 +31,12 @@ export type EnvironmentRow = {
|
||||
created_at: number
|
||||
updated_at: number
|
||||
deleted_at: number | null
|
||||
/**
|
||||
* 'org': made (or since edited) by an admin. 'auto': made by the first create of a repo no
|
||||
* environment listed (auto-environments.ts); deleted after 14 days unused unless an admin edits it.
|
||||
*/
|
||||
kind?: 'org' | 'auto'
|
||||
last_used_at?: number | null
|
||||
}
|
||||
|
||||
export class EnvironmentError extends Error {
|
||||
@@ -223,10 +229,11 @@ export async function updateEnvironment(
|
||||
next.install_script !== row.install_script ||
|
||||
next.env_var_names !== row.env_var_names ||
|
||||
next.machine_size !== row.machine_size
|
||||
// An admin's edit adopts an automatic environment: it stops expiring.
|
||||
const result = await db
|
||||
.prepare(
|
||||
`UPDATE environments SET name = ?, repos = ?, install_script = ?, env_var_names = ?, machine_size = ?,
|
||||
revision = revision + ?, updated_by = ?, updated_at = ? WHERE id = ? AND revision = ?`
|
||||
revision = revision + ?, updated_by = ?, updated_at = ?, kind = 'org' WHERE id = ? AND revision = ?`
|
||||
)
|
||||
.bind(next.name, next.repos, next.install_script, next.env_var_names, next.machine_size,
|
||||
buildInputsChanged ? 1 : 0, caller.userId, now, row.id, row.revision)
|
||||
@@ -246,6 +253,8 @@ export type BootSource = {
|
||||
machineSize: MachineSize
|
||||
/** The build's snapshot only boots here, so the workspace is created here too. */
|
||||
region: string
|
||||
/** An automatic environment (auto-environments.ts): the caller's machine size stands. */
|
||||
auto?: boolean
|
||||
}
|
||||
|
||||
type BootBuildRow = {
|
||||
@@ -288,7 +297,12 @@ function bootFrom(build: BootBuildRow, repoUrl: string | null | undefined): Boot
|
||||
export async function resolveEnvironmentBoot(
|
||||
db: D1Database,
|
||||
accountId: string,
|
||||
request: { repoUrl?: string | null; buildId?: string | null }
|
||||
request: {
|
||||
repoUrl?: string | null
|
||||
buildId?: string | null
|
||||
/** An automatic environment only boots in its build's region: an explicit other region skips it. */
|
||||
region?: string | null
|
||||
}
|
||||
): Promise<BootSource | null> {
|
||||
if (request.buildId) {
|
||||
const build = await db
|
||||
@@ -308,20 +322,25 @@ export async function resolveEnvironmentBoot(
|
||||
if (!wanted) {
|
||||
return null
|
||||
}
|
||||
// An admin's environment that lists the repo wins over an automatic one.
|
||||
const { results } = await db
|
||||
.prepare(
|
||||
`SELECT e.repos AS repos, b.* FROM environments e JOIN environment_builds b ON b.id = e.active_build_id
|
||||
WHERE e.account_id = ? AND e.deleted_at IS NULL ORDER BY e.updated_at DESC`
|
||||
`SELECT e.repos AS repos, e.kind AS kind, b.* FROM environments e JOIN environment_builds b ON b.id = e.active_build_id
|
||||
WHERE e.account_id = ? AND e.deleted_at IS NULL ORDER BY (e.kind = 'org') DESC, e.updated_at DESC`
|
||||
)
|
||||
.bind(accountId)
|
||||
.all<BootBuildRow & { repos: string }>()
|
||||
.all<BootBuildRow & { repos: string; kind: string }>()
|
||||
for (const row of results) {
|
||||
if (!parseRepos(row).some((repo) => normalizeRepo(repo.url) === wanted)) {
|
||||
continue
|
||||
}
|
||||
// An automatic environment is only a speed-up: an explicit other region skips it.
|
||||
if (row.kind === 'auto' && request.region && request.region !== row.region) {
|
||||
continue
|
||||
}
|
||||
const source = bootFrom(row, request.repoUrl)
|
||||
if (source?.repoDir) {
|
||||
return source
|
||||
return row.kind === 'auto' ? { ...source, auto: true } : source
|
||||
}
|
||||
}
|
||||
return null
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
// the public API's POST /v1/workspaces/:id/wake answers the same fields plus `workspace`)
|
||||
// POST /v1/sandboxes/:id/restart -> {sandbox, connection}
|
||||
// GET /v1/sandboxes/:id/status -> {sandbox, status} (live metrics, cost)
|
||||
// GET /v1/sandboxes/boot-plan?repo=<url> -> {repo: 'clone' | 'update'}
|
||||
// GET /v1/sandboxes/:id/clone -> {clone: {state, percent?, stage?, reason?}}
|
||||
// POST /v1/sandboxes/:id/archive {pullRequests?, checkouts?} -> {sandbox}
|
||||
// GET /v1/sandboxes/:id/archive -> {archive}
|
||||
@@ -24,10 +25,13 @@
|
||||
// POST /v1/device-sessions | GET | DELETE /:id per-phone access (see device-sessions.ts)
|
||||
// Phones sign their own EdDSA tokens (device-sessions.ts) and act as their user, except that they
|
||||
// cannot enroll devices, manage secrets or connect GitHub.
|
||||
// /v1/team/workspaces[/:id[/presence|wake|lease|grants[/:grantId]]], /v1/team/links/resolve, /v1/team/prompts
|
||||
// /v1/team/workspaces[/:id[/presence|wake|lease|grants[/:grantId]]], /v1/team/links/resolve, /v1/team/prompts,
|
||||
// /v1/team/prefs (src/workspace-prefs.ts), /v1/team/org (src/org-slugs.ts)
|
||||
// team workspace registry, presence, per-device grants (src/workspaces.ts, src/grants.ts)
|
||||
// POST /v1/team/workspaces/:id/wake?wait=30s: any member who can open it wakes it (single-flight,
|
||||
// billed to the account, counted on the owner's seat like every wake) -> {state, endpoint: null, …}
|
||||
// /v1/team/members/:userId/(profile|poke), /v1/team/pokes[/settings|/seen]
|
||||
// teammate profiles (usage heatmap, recent workspaces) and opt-in Pokes (src/team-presence.ts)
|
||||
// /v1/sandboxes/* is the owner's lifecycle API: only the workspace's owner (and, for suspend and
|
||||
// destroy, an org admin) can reach a row there, because resume hands back an orcad pairing offer.
|
||||
// Browser (GitHub redirects): GET /v1/github/setup, GET /v1/github/callback
|
||||
@@ -114,7 +118,7 @@ import { egressAccountRoutes, egressSecretHosts, placeholderValues, secretPlaceh
|
||||
import { SecretError, handleSecretsRoute, keyringFor, type SecretChange } from './secrets'
|
||||
import { refreshAfterSecretChange, refreshSandboxEnv } from './env-refresh'
|
||||
import { accountProvider, isSharedWorkspace } from './account-providers'
|
||||
import { handleAccountUnauthorized } from './agent-credential-checks'
|
||||
import { handleAccountUnauthorized, verifyAccountCredential } from './agent-credential-checks'
|
||||
import { codexBrokerTick, handleCodexBrokerRoute, type BrokerDeps } from './codex-broker'
|
||||
import { refreshCodexLeases } from './codex-credentials'
|
||||
import {
|
||||
@@ -141,6 +145,9 @@ import { credentialTargets, type CredentialTarget } from './provider-env'
|
||||
import type { Keyring } from './secrets-crypto'
|
||||
import { ProviderError, type SandboxProviderApi } from './sandbox-provider'
|
||||
import { readCloneStatus } from './clone-status'
|
||||
import { readIdempotencyKey, withIdempotency } from './api/idempotency'
|
||||
import { ApiError } from './api/caller'
|
||||
import { ensureAutoEnvironment, expireAutoEnvironments, touchEnvironment } from './auto-environments'
|
||||
import { DesktopCommandError, VmCommandError, startDesktop } from './sandbox-vm-commands'
|
||||
import { forgetShareLink, handleShareGateway } from './share-gateway'
|
||||
import { handleShareRoute, revokeSandboxShares, sharePathMode, shareSecret, shareSecrets } from './share-links'
|
||||
@@ -150,7 +157,7 @@ import { getSandbox, getSandboxByProviderName, listAccountSandboxes, markUserSle
|
||||
import { createVercelSandboxApi } from './vercel-sandbox-api'
|
||||
import { advanceAllBuilds, tickBuild, unfinishedBuilds, type BuildDeps } from './environment-builds'
|
||||
import { environmentErrorResponse, handleEnvironmentRoute, isEnvironmentRoute } from './environment-routes'
|
||||
import { EnvironmentError } from './environments'
|
||||
import { EnvironmentError, resolveEnvironmentBoot } from './environments'
|
||||
import type { GoldenImageProviderApi } from './golden-image-provider'
|
||||
import { CreateRequestSchema, LeaseRequestSchema, parseWakeWait, readyView, sandboxView } from './wire'
|
||||
import { ArchiveRequestSchema } from './sandbox-vm-inspect'
|
||||
@@ -185,7 +192,10 @@ import {
|
||||
userAuthorizeUrl
|
||||
} from './github-user-tokens'
|
||||
import { MEMBER_GIT_WINDOW_MS, memberGitRoutes, memberSentWithin, recordMemberSend } from './member-git'
|
||||
import { getWorkspacePrefs, putWorkspacePrefs } from './workspace-prefs'
|
||||
import { getOrgSlug, putOrgSlug } from './org-slugs'
|
||||
import {
|
||||
LinkOtherOrgError,
|
||||
PatchSchema,
|
||||
PresenceSchema,
|
||||
WORKSPACE_ERROR_STATUS,
|
||||
@@ -201,6 +211,7 @@ import {
|
||||
workspaceViews
|
||||
} from './workspaces'
|
||||
import { rememberCallerName } from './member-names'
|
||||
import { TeamPresenceError, teamPresenceRoute } from './team-presence'
|
||||
import { sweepSessionCpu } from './session-cpu'
|
||||
import type { SandboxCaller } from './auth'
|
||||
|
||||
@@ -529,6 +540,28 @@ async function agentCredentialsRoute(request: Request, url: URL, env: Env, deps:
|
||||
await refreshOwnersSandboxes(env, deps, caller.userId)
|
||||
return noStore(await agentCredentialsView(db, env, caller.userId, now))
|
||||
}
|
||||
// Pre-launch check (desktop): a recent pass answers at once; otherwise one rate-limited auth check with
|
||||
// the real token, revoking only on a definite auth failure (agent-credential-checks.ts).
|
||||
if (request.method === 'POST' && url.pathname === '/v1/agent-credentials/claude/verify') {
|
||||
const provider = accountProvider('claude')
|
||||
if (!providerEnabled(env).claude || !provider) {
|
||||
return fail('not_found', 404)
|
||||
}
|
||||
const result = await verifyAccountCredential({
|
||||
db,
|
||||
keyring: await keyring,
|
||||
provider,
|
||||
userId: caller.userId,
|
||||
now,
|
||||
fetch: deps.egressFetch ?? fetch
|
||||
})
|
||||
if (result.outcome === 'revoked') {
|
||||
forgetAccountCredential(caller.userId, 'claude')
|
||||
await refreshOwnersSandboxes(env, deps, caller.userId)
|
||||
}
|
||||
const view = await agentCredentialsView(db, env, caller.userId, now)
|
||||
return noStore({ claude: view.claude, verifiedAt: result.verifiedAt, checked: result.outcome !== 'fresh' && result.outcome !== 'skipped' })
|
||||
}
|
||||
if (url.pathname === '/v1/agent-credentials/codex/broker' || url.pathname.startsWith('/v1/agent-credentials/codex/broker/')) {
|
||||
return await handleCodexBrokerRoute(request, url, { enabled: providerEnabled(env).codex, deps: await codexBrokerDeps(env, deps), caller })
|
||||
}
|
||||
@@ -720,8 +753,8 @@ function devCredentials(env: Env): CredentialBroker {
|
||||
}
|
||||
|
||||
/** Ready answers carry phase timings as Server-Timing so clients and dashboards can see the slow step. */
|
||||
function readyResponse(ready: Ready): Response {
|
||||
const response = json(readyView(ready.row, ready.connection, ready.cloning))
|
||||
function readyResponse(ready: Ready, updateAware = false): Response {
|
||||
const response = json(readyView(ready.row, ready.connection, ready.cloning, updateAware))
|
||||
const timing = Object.entries(ready.timings ?? {})
|
||||
.map(([phase, ms]) => `${phase};dur=${ms}`)
|
||||
.join(', ')
|
||||
@@ -780,7 +813,7 @@ export async function lifecycleDeps(env: Env, deps: Deps): Promise<LifecycleDeps
|
||||
projectId: env.VERCEL_PROJECT_ID!,
|
||||
baseUrl: env.VERCEL_API_BASE
|
||||
})
|
||||
return {
|
||||
const life: LifecycleDeps = {
|
||||
db: env.SANDBOX_DB,
|
||||
provider,
|
||||
entitlements: deps.entitlements ?? withDevAccountBypass(env, createEntitlementClient(env)),
|
||||
@@ -812,6 +845,14 @@ export async function lifecycleDeps(env: Env, deps: Deps): Promise<LifecycleDeps
|
||||
env.SESSION_DEADLINE_MS && env.SANDBOX_ENV !== 'prod' ? Number(env.SESSION_DEADLINE_MS) : undefined
|
||||
}
|
||||
}
|
||||
// AUTO_ENVIRONMENTS=off: creates of repos without an environment keep cloning from scratch.
|
||||
if (env.AUTO_ENVIRONMENTS !== 'off') {
|
||||
life.autoEnvironment = {
|
||||
ensure: (accountId, repoUrl) => ensureAutoEnvironment(buildDeps(life, deps, env), accountId, repoUrl),
|
||||
touch: (environmentId) => touchEnvironment(env.SANDBOX_DB, environmentId, life.now())
|
||||
}
|
||||
}
|
||||
return life
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1109,7 +1150,12 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {})
|
||||
return await internalInstallUrl(env, deps, url)
|
||||
}
|
||||
if (url.pathname.startsWith('/v1/internal/')) {
|
||||
if (!(await isOperator(request, env.OPERATOR_TOKEN))) {
|
||||
// Auth's member-removed push holds a token good for that one route, not the operator token.
|
||||
const memberRemovedOnly =
|
||||
url.pathname === '/v1/internal/org-members/removed' &&
|
||||
request.method === 'POST' &&
|
||||
(await isOperator(request, env.MEMBER_REMOVED_TOKEN))
|
||||
if (!memberRemovedOnly && !(await isOperator(request, env.OPERATOR_TOKEN))) {
|
||||
return fail('not_found', 404)
|
||||
}
|
||||
const life = await lifecycleDeps(env, deps)
|
||||
@@ -1449,7 +1495,12 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {})
|
||||
url.pathname === '/v1/team/workspaces' ||
|
||||
url.pathname.startsWith('/v1/team/workspaces/') ||
|
||||
url.pathname === '/v1/team/links/resolve' ||
|
||||
url.pathname === '/v1/team/prompts'
|
||||
url.pathname === '/v1/team/prompts' ||
|
||||
url.pathname === '/v1/team/prefs' ||
|
||||
url.pathname === '/v1/team/org' ||
|
||||
url.pathname.startsWith('/v1/team/members/') ||
|
||||
url.pathname === '/v1/team/pokes' ||
|
||||
url.pathname.startsWith('/v1/team/pokes/')
|
||||
) {
|
||||
const caller = await authenticateDesktop(env, request, (deps.now ?? Date.now)())
|
||||
if (!caller) {
|
||||
@@ -1457,6 +1508,20 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {})
|
||||
}
|
||||
return await workspaceRoute(request, url, env, deps, caller)
|
||||
}
|
||||
if (url.pathname === '/v1/sandboxes/boot-plan' && request.method === 'GET') {
|
||||
// Whether a create of this repo would clone it or update a prebuilt copy, so the desktop names
|
||||
// its repository step once, before the create answers (environments.ts resolveEnvironmentBoot).
|
||||
const caller = await authenticateDesktop(env, request, (deps.now ?? Date.now)())
|
||||
if (!caller) {
|
||||
return fail('unauthorized', 401)
|
||||
}
|
||||
const repo = url.searchParams.get('repo') ?? ''
|
||||
if (repo.length === 0 || repo.length > 2048) {
|
||||
return fail('invalid_request', 400)
|
||||
}
|
||||
const source = await resolveEnvironmentBoot(env.SANDBOX_DB, caller.accountId, { repoUrl: repo }).catch(() => null)
|
||||
return json({ repo: source?.repoDir ? 'update' : 'clone' })
|
||||
}
|
||||
const match =
|
||||
/^\/v1\/sandboxes(?:\/([A-Za-z0-9_]+)(?:\/(suspend|resume|lease|rollover|wake|restart|status|clone|archive|unarchive|env\/refresh|egress\/hosts|ssh-keys|desktop))?)?$/.exec(
|
||||
url.pathname
|
||||
@@ -1492,14 +1557,39 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {})
|
||||
return fail('not_found', 404)
|
||||
}
|
||||
await consumeCreateToken(life.db, life.config.guardrails!, caller.accountId, life.now())
|
||||
const body = CreateRequestSchema.safeParse(await readJson(request))
|
||||
const raw = await readJson(request)
|
||||
const body = CreateRequestSchema.safeParse(raw)
|
||||
if (!body.success) {
|
||||
return fail('invalid_request', 400)
|
||||
}
|
||||
// Desktops that show the clone as its own step ask for it in the background (GET .../clone).
|
||||
const ready = await createSandbox(life, caller, { ...body.data, cloneInBackground: features.includes('clone-progress') })
|
||||
await recordOwnerDeviceAndSync(life, ready.row, ready.connection.pairingCode)
|
||||
return readyResponse(ready)
|
||||
// Idempotency-Key (one per Create press): a re-sent create with the same key and body answers
|
||||
// with the sandbox the first one made, for 24 h, instead of starting another (PC-8).
|
||||
let timings: Ready['timings']
|
||||
try {
|
||||
const response = await withIdempotency(
|
||||
life.db,
|
||||
{ accountId: caller.accountId, scope: `sandbox.create:${caller.userId}`, key: readIdempotencyKey(request), body: raw, now: life.now() },
|
||||
async () => {
|
||||
// Desktops that show the clone as its own step ask for it in the background (GET .../clone).
|
||||
const ready = await createSandbox(life, caller, { ...body.data, cloneInBackground: features.includes('clone-progress') })
|
||||
await recordOwnerDeviceAndSync(life, ready.row, ready.connection.pairingCode)
|
||||
timings = ready.timings
|
||||
return { status: 200, body: readyView(ready.row, ready.connection, ready.cloning, features.includes('repo-update')) }
|
||||
}
|
||||
)
|
||||
const timing = Object.entries(timings ?? {})
|
||||
.map(([phase, ms]) => `${phase};dur=${ms}`)
|
||||
.join(', ')
|
||||
if (timing) {
|
||||
response.headers.set('server-timing', timing)
|
||||
}
|
||||
return response
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError) {
|
||||
return fail(error.code, error.status, error.reason)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
const row = await getSandbox(env.SANDBOX_DB, id)
|
||||
const route = `${request.method} ${action ?? ''}`
|
||||
@@ -1787,7 +1877,32 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps,
|
||||
// Labels for teammates' lists; a failure here must never fail the request itself.
|
||||
await rememberCallerName(db, caller, now).catch((error: unknown) => console.warn('member_name_write_failed', String(error)))
|
||||
if (url.pathname === '/v1/team/links/resolve' && request.method === 'GET') {
|
||||
return json(await resolveLink(db, caller, url, now))
|
||||
try {
|
||||
return json(await resolveLink(db, caller, url, now))
|
||||
} catch (error) {
|
||||
if (error instanceof LinkOtherOrgError) {
|
||||
return json({ error: 'not_found', reason: 'other_org', orgId: error.orgId }, 404)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
if (url.pathname === '/v1/team/prefs') {
|
||||
if (request.method === 'GET') {
|
||||
return json(await getWorkspacePrefs(db, caller))
|
||||
}
|
||||
if (request.method === 'PUT') {
|
||||
return json(await putWorkspacePrefs(db, caller, await readJson(request), now))
|
||||
}
|
||||
return fail('not_found', 404)
|
||||
}
|
||||
if (url.pathname === '/v1/team/org') {
|
||||
if (request.method === 'GET') {
|
||||
return json(await getOrgSlug(db, caller, url, now))
|
||||
}
|
||||
if (request.method === 'PUT') {
|
||||
return json(await putOrgSlug(db, caller, await readJson(request), now))
|
||||
}
|
||||
return fail('not_found', 404)
|
||||
}
|
||||
if (url.pathname === '/v1/team/prompts') {
|
||||
if (request.method === 'GET') {
|
||||
@@ -1801,6 +1916,26 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps,
|
||||
if (url.pathname === '/v1/team/workspaces') {
|
||||
return request.method === 'GET' ? json(await listWorkspaces(db, caller, url, now)) : fail('not_found', 404)
|
||||
}
|
||||
if (url.pathname.startsWith('/v1/team/members/') || url.pathname.startsWith('/v1/team/pokes')) {
|
||||
try {
|
||||
const answer = await teamPresenceRoute(db, caller, request, url, now, () => readJson(request), {
|
||||
activitySharing: env.TEAMMATE_ACTIVITY_SHARING === 'team' ? 'team' : 'opt_in'
|
||||
})
|
||||
return answer === null ? fail('not_found', 404) : json(answer)
|
||||
} catch (error) {
|
||||
if (error instanceof TeamPresenceError) {
|
||||
const response = json(
|
||||
{ error: error.code, ...(error.reason ? { reason: error.reason } : {}), ...(error.retryAfterMs ? { retryAfterMs: error.retryAfterMs } : {}) },
|
||||
error.status
|
||||
)
|
||||
if (error.retryAfterMs) {
|
||||
response.headers.set('retry-after', String(Math.ceil(error.retryAfterMs / 1000)))
|
||||
}
|
||||
return response
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
const match = /^\/v1\/team\/workspaces\/(sbx_[0-9a-f]{24})(?:\/(presence|wake|lease|grants|sent|read-snapshot)(?:\/(grt_[0-9a-f]{24}))?)?$/.exec(url.pathname)
|
||||
if (!match) {
|
||||
return fail('not_found', 404)
|
||||
@@ -2116,6 +2251,11 @@ export default {
|
||||
if (refresh.stale > 0) {
|
||||
console.log(JSON.stringify({ event: 'environment_golden_refresh', ...refresh }))
|
||||
}
|
||||
// Automatic environments unused for 14 days go with their snapshots (storage).
|
||||
const expired = await expireAutoEnvironments(buildDeps(fresh, {}, env)).catch(() => 0)
|
||||
if (expired > 0) {
|
||||
console.log(JSON.stringify({ event: 'auto_environments_expired', expired }))
|
||||
}
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
ORCAD_PORT,
|
||||
SHARE_PROXY_PORT,
|
||||
VmCommandError,
|
||||
workspaceHostname,
|
||||
drainOrcad,
|
||||
runningOrcad,
|
||||
startOrcad,
|
||||
@@ -96,6 +97,14 @@ export type LifecycleDeps = {
|
||||
* error after boot. Absent: no check.
|
||||
*/
|
||||
publicRepoCheck?: (repoUrl: string) => Promise<boolean>
|
||||
/**
|
||||
* Automatic environments (auto-environments.ts): `ensure` after a create of a repo no environment
|
||||
* lists, `touch` when a create booted from an automatic one. Absent: neither happens.
|
||||
*/
|
||||
autoEnvironment?: {
|
||||
ensure(accountId: string, repoUrl: string): Promise<unknown>
|
||||
touch(environmentId: string): Promise<unknown>
|
||||
}
|
||||
/** Work that may finish after the response (Worker ctx.waitUntil); absent means fire-and-forget. */
|
||||
background?: (work: Promise<unknown>) => void
|
||||
/** Best-effort side effects of a session starting or ending (workspace tokens, see api/settings.ts). */
|
||||
@@ -156,8 +165,11 @@ export type Ready = {
|
||||
row: SandboxRow
|
||||
connection: OrcadReady
|
||||
timings?: Record<string, number>
|
||||
/** The repo is still cloning in the VM (create with cloneInBackground); GET /clone reports it. */
|
||||
cloning?: boolean
|
||||
/**
|
||||
* The repo is still being cloned ('clone') or, after an environment boot, brought up to date
|
||||
* ('update') in the VM (create with cloneInBackground); GET /clone reports it.
|
||||
*/
|
||||
cloning?: 'clone' | 'update'
|
||||
}
|
||||
|
||||
/** Phase durations for one lifecycle call (logged + Server-Timing); counts only, no ids or secrets. */
|
||||
@@ -376,6 +388,8 @@ async function boot(
|
||||
options.timer.time('orcad', async () =>
|
||||
startOrcad(deps.provider, state, {
|
||||
sandboxId: row.id,
|
||||
// The workspace's name, else its repo's: never the provider's per-boot VM id.
|
||||
hostname: workspaceHostname(row.name ?? (row.repo_url ? parseGitHubRepo(row.repo_url)?.repo : null)),
|
||||
repo: options.repo,
|
||||
// Repos hosted outside github.com get no GitHub credential, not even the placeholder.
|
||||
githubPlaceholder: deps.config.egressProxyUrl && parseGitHubRepo(row.repo_url ?? '') ? githubPlaceholderToken(row) : undefined,
|
||||
@@ -515,11 +529,13 @@ export async function createSandbox(
|
||||
? await timer.time('environment', () =>
|
||||
resolveEnvironmentBoot(deps.db, caller.accountId, {
|
||||
repoUrl: request.repo?.url,
|
||||
buildId: request.environmentBuildId
|
||||
buildId: request.environmentBuildId,
|
||||
region: request.region
|
||||
})
|
||||
)
|
||||
: null
|
||||
const machineSize = source?.machineSize ?? request.machineSize
|
||||
// An automatic environment is only the repo checked out: the caller's machine size stands.
|
||||
const machineSize = source && !source.auto ? source.machineSize : request.machineSize
|
||||
await timer.time('entitlement', () => requireStart(deps, caller.accountId, caller.userId, machineSize))
|
||||
// A snapshot only boots in its own region: an environment build pins the region it was built in.
|
||||
const region = source?.region ?? request.region ?? deps.config.defaultRegion
|
||||
@@ -541,12 +557,16 @@ export async function createSandbox(
|
||||
deps.background?.(refill)
|
||||
}
|
||||
const claimedAt = deps.now()
|
||||
// An environment build carries the repo prebuilt: nothing clones, so nothing runs in the background.
|
||||
const cloneInBackground = Boolean(request.repo && request.cloneInBackground && !source?.repoDir)
|
||||
// In the background after ready: a clone, or (an environment build carries the repo prebuilt) a fetch
|
||||
// of what changed since the build.
|
||||
const cloning: Ready['cloning'] = request.repo && request.cloneInBackground ? (source?.repoDir ? 'update' : 'clone') : undefined
|
||||
const prelude: StartInputs['prelude'] = request.repo
|
||||
? {
|
||||
script: WORKSPACE_PRELUDE_SCRIPT,
|
||||
env: source?.repoDir ? { ORCA_ENV_REPO_DIR: source.repoDir } : cloneInBackground ? { ORCA_CLONE_BACKGROUND: '1' } : {}
|
||||
env: {
|
||||
...(source?.repoDir ? { ORCA_ENV_REPO_DIR: source.repoDir } : {}),
|
||||
...(cloning ? { ORCA_CLONE_BACKGROUND: '1' } : {})
|
||||
}
|
||||
}
|
||||
: undefined
|
||||
const id = pooled?.id ?? randomId()
|
||||
@@ -590,6 +610,18 @@ export async function createSandbox(
|
||||
throw error
|
||||
}
|
||||
})
|
||||
// The repo is reachable: the next create of it should find it prebuilt (auto-environments.ts).
|
||||
if (request.repo && deps.autoEnvironment && !request.environmentBuildId && request.useEnvironment !== false) {
|
||||
const work = source?.auto
|
||||
? deps.autoEnvironment.touch(source.environmentId)
|
||||
: !source
|
||||
? deps.autoEnvironment.ensure(caller.accountId, request.repo.url)
|
||||
: null
|
||||
if (work) {
|
||||
const settled = work.catch(() => undefined)
|
||||
deps.background?.(settled)
|
||||
}
|
||||
}
|
||||
if (pooled) {
|
||||
try {
|
||||
const state = await timer.time('vm', () =>
|
||||
@@ -597,7 +629,7 @@ export async function createSandbox(
|
||||
)
|
||||
const ready = await boot(deps, row, state, prep, { repo: request.repo, policyApplied: true, timer, billFrom: claimedAt, prelude })
|
||||
console.log(JSON.stringify({ event: 'lifecycle_timing', op: 'create', pooled: true, ms: timer.timings }))
|
||||
return cloneInBackground ? { ...ready, cloning: true } : ready
|
||||
return cloning ? { ...ready, cloning } : ready
|
||||
} catch (error) {
|
||||
// A pooled VM that will not take the session is discarded; the caller still gets a workspace.
|
||||
console.log(JSON.stringify({ event: 'pool_adopt_failed', error: String(error).slice(0, 200) }))
|
||||
@@ -647,7 +679,7 @@ export async function createSandbox(
|
||||
try {
|
||||
const ready = await boot(deps, row, state, prep, { repo: request.repo, policyApplied: true, timer, prelude })
|
||||
console.log(JSON.stringify({ event: 'lifecycle_timing', op: 'create', fromBuild: source?.buildId ?? null, ms: timer.timings }))
|
||||
return cloneInBackground ? { ...ready, cloning: true } : ready
|
||||
return cloning ? { ...ready, cloning } : ready
|
||||
} catch (error) {
|
||||
await failAndRelease(deps, (await getSandbox(deps.db, row.id)) ?? row, createFailureReason(error))
|
||||
throw error
|
||||
|
||||
@@ -5,7 +5,8 @@ import type { ApiCaller } from '../api/caller'
|
||||
import { callTool, hasTool, toolError, toolList, type ApiCall } from './tools'
|
||||
|
||||
export const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'] as const
|
||||
const MAX_BODY_BYTES = 256 * 1024
|
||||
// upload_attachment carries up to 5 MB as base64 (~6.7 MB of JSON); everything else is tiny.
|
||||
const MAX_BODY_BYTES = 7 * 1024 * 1024 + 512 * 1024
|
||||
|
||||
const SERVER_INFO = {
|
||||
name: 'orca-cloud',
|
||||
@@ -16,7 +17,8 @@ const SERVER_INFO = {
|
||||
|
||||
const INSTRUCTIONS =
|
||||
'Orca Cloud runs coding agents (Claude Code, Codex) in cloud workspaces. Typical flow: list_projects or list_workspaces; ' +
|
||||
'create_workspace (optionally with a first message); send_message to give an agent a task; list_sessions to read its progress; ' +
|
||||
'create_workspace (optionally with a first message); send_message to give an agent a task; list_sessions and read_session to read its progress; ' +
|
||||
'create_session for another chat (pick models with list_models), upload_attachment to hand an agent a file, cancel_session to stop a turn; ' +
|
||||
'sleep_workspace when idle and destroy_workspace when done. Destroying is permanent.'
|
||||
|
||||
type JsonRpcId = string | number | null
|
||||
|
||||
@@ -32,6 +32,7 @@ type ToolDef<T extends z.ZodObject> = {
|
||||
// Ids go into URL paths: restrict them so a tool argument can never address another route.
|
||||
const Id = (what: string) => z.string().regex(/^[A-Za-z0-9_-]{1,64}$/, `a ${what} id`).describe(`The ${what} id.`)
|
||||
const WorkspaceId = z.object({ workspaceId: Id('workspace') }).strict()
|
||||
const SessionHandle = z.string().regex(/^term_[A-Za-z0-9-]{1,80}$/).describe('Session handle (term_…) from list_sessions, create_session or a message.')
|
||||
const Agent = z.enum(AGENTS).describe(`Agent CLI to run: ${AGENTS.join(', ')} (claude, Claude Code, is the default).`)
|
||||
const MAX_WAIT_SECONDS = 45
|
||||
|
||||
@@ -92,6 +93,14 @@ export const TOOLS = [
|
||||
annotations: read('Who am I'),
|
||||
run: async (_args, api) => fromApi(await api('GET', '/v1/me'))
|
||||
}),
|
||||
tool({
|
||||
name: 'list_models',
|
||||
description:
|
||||
'Lists the coding agents a cloud workspace runs (claude, codex, opencode, gemini, cursor, copilot) and, for each, the model ids, effort levels, defaults and fast-mode support. Pass agent, model and effort to create_session.',
|
||||
input: z.object({}).strict(),
|
||||
annotations: read('List agents and models'),
|
||||
run: async (_args, api) => fromApi(await api('GET', '/v1/models'))
|
||||
}),
|
||||
tool({
|
||||
name: 'list_projects',
|
||||
description: 'Lists the Orca Cloud projects in this account. A project is a repository plus default sandbox settings; pass its id to create_workspace to start a workspace from it.',
|
||||
@@ -153,6 +162,13 @@ export const TOOLS = [
|
||||
})
|
||||
)
|
||||
}),
|
||||
tool({
|
||||
name: 'rename_workspace',
|
||||
description: 'Renames a workspace (the name shown on desktop Home, the phone and in list_workspaces). The git branch keeps its name.',
|
||||
input: z.object({ workspaceId: Id('workspace'), name: z.string().trim().min(1).max(100).describe('New display name.') }).strict(),
|
||||
annotations: { title: 'Rename workspace', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
||||
run: async (args, api) => fromApi(await api('POST', `/v1/workspaces/${args.workspaceId}/rename`, { name: args.name }))
|
||||
}),
|
||||
tool({
|
||||
name: 'sleep_workspace',
|
||||
description: 'Puts a running workspace to sleep: its files are kept and no sandbox hours are used until wake_workspace. Running agents are interrupted.',
|
||||
@@ -174,6 +190,13 @@ export const TOOLS = [
|
||||
annotations: { title: 'Archive workspace', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
||||
run: async (args, api) => fromApi(await api('POST', `/v1/workspaces/${args.workspaceId}/archive`))
|
||||
}),
|
||||
tool({
|
||||
name: 'unarchive_workspace',
|
||||
description: 'Restores an archived workspace: it is back in default lists and its sandbox is started again with its files intact. A workspace that is not archived is returned unchanged.',
|
||||
input: WorkspaceId,
|
||||
annotations: { title: 'Unarchive workspace', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
||||
run: async (args, api) => fromApi(await api('POST', `/v1/workspaces/${args.workspaceId}/unarchive`))
|
||||
}),
|
||||
tool({
|
||||
name: 'destroy_workspace',
|
||||
description: 'Deletes a workspace and its sandbox for good. Uncommitted and unpushed work in it is lost. This cannot be undone.',
|
||||
@@ -181,6 +204,53 @@ export const TOOLS = [
|
||||
annotations: { title: 'Delete workspace', readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
|
||||
run: async (args, api) => fromApi(await api('DELETE', `/v1/workspaces/${args.workspaceId}`))
|
||||
}),
|
||||
tool({
|
||||
name: 'create_session',
|
||||
description:
|
||||
'Starts a new agent session (a new chat) in an existing workspace, waking it first if it sleeps, and returns its handle once the agent is up. Optionally pick the model and effort (see list_models), name it, and give it a first `message` (with `attachments` from upload_attachment). Continue it with send_message and `session` = the handle.',
|
||||
input: z
|
||||
.object({
|
||||
workspaceId: Id('workspace'),
|
||||
agent: Agent.optional(),
|
||||
model: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:/@[\]-]{0,127}$/).optional().describe('Model id from list_models (default: the agent\'s own default).'),
|
||||
effort: z.string().regex(/^[a-z]{2,16}$/).optional().describe('Effort level the model takes (list_models); needs `model`.'),
|
||||
name: z.string().trim().min(1).max(100).optional().describe('Session (tab) title.'),
|
||||
message: z.string().min(1).max(32_000).optional().describe('First prompt. Without it the agent starts idle.'),
|
||||
attachments: z.array(Id('attachment')).min(1).max(10).optional().describe('Attachment ids from upload_attachment; needs `message`.')
|
||||
})
|
||||
.strict(),
|
||||
annotations: { title: 'Start agent session', readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
||||
run: async ({ workspaceId, ...body }, api) => fromApi(await api('POST', `/v1/workspaces/${workspaceId}/sessions`, body))
|
||||
}),
|
||||
tool({
|
||||
name: 'cancel_session',
|
||||
description: "Stops an agent's current turn in a session (like pressing Escape) and drops any of that session's messages still queued. The session stays open for the next send_message.",
|
||||
input: z.object({ workspaceId: Id('workspace'), session: SessionHandle }).strict(),
|
||||
annotations: { title: 'Cancel agent turn', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
||||
run: async (args, api) => fromApi(await api('POST', `/v1/workspaces/${args.workspaceId}/sessions/${args.session}/cancel`))
|
||||
}),
|
||||
tool({
|
||||
name: 'rename_session',
|
||||
description: 'Renames an agent session (the tab title the desktop and phone show). The workspace must be running.',
|
||||
input: z.object({ workspaceId: Id('workspace'), session: SessionHandle, name: z.string().trim().min(1).max(100).describe('New title.') }).strict(),
|
||||
annotations: { title: 'Rename agent session', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
||||
run: async (args, api) => fromApi(await api('POST', `/v1/workspaces/${args.workspaceId}/sessions/${args.session}/rename`, { name: args.name }))
|
||||
}),
|
||||
tool({
|
||||
name: 'upload_attachment',
|
||||
description:
|
||||
'Uploads a file (base64, up to 5 MB) to a workspace for an agent to read, e.g. a screenshot or log. Returns an attachment id; pass it in `attachments` to send_message or create_session and the agent is told where the file is. The file sits outside the repo, so it is never committed.',
|
||||
input: z
|
||||
.object({
|
||||
workspaceId: Id('workspace'),
|
||||
filename: z.string().min(1).max(255).describe('File name, e.g. bug.png.'),
|
||||
contentType: z.string().max(127).optional().describe('MIME type, e.g. image/png.'),
|
||||
data: z.string().min(1).describe('The file bytes, base64-encoded.')
|
||||
})
|
||||
.strict(),
|
||||
annotations: { title: 'Upload attachment', readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
||||
run: async ({ workspaceId, ...body }, api) => fromApi(await api('POST', `/v1/workspaces/${workspaceId}/attachments`, body))
|
||||
}),
|
||||
tool({
|
||||
name: 'send_message',
|
||||
description:
|
||||
@@ -191,6 +261,7 @@ export const TOOLS = [
|
||||
text: z.string().min(1).max(32_000).describe('The message or task for the agent.'),
|
||||
agent: Agent.optional(),
|
||||
session: z.string().regex(/^term_[A-Za-z0-9-]{1,80}$/).optional().describe('Session handle to continue (from list_sessions or a previous message).'),
|
||||
attachments: z.array(Id('attachment')).min(1).max(10).optional().describe('Attachment ids from upload_attachment.'),
|
||||
waitSeconds: z.number().int().min(0).max(MAX_WAIT_SECONDS).optional().describe(`How long to wait for delivery (0-${MAX_WAIT_SECONDS}, default 20).`)
|
||||
})
|
||||
.strict(),
|
||||
@@ -199,7 +270,8 @@ export const TOOLS = [
|
||||
const response = await api('POST', `/v1/workspaces/${args.workspaceId}/messages`, {
|
||||
text: args.text,
|
||||
...(args.agent ? { agent: args.agent } : {}),
|
||||
...(args.session ? { session: args.session } : {})
|
||||
...(args.session ? { session: args.session } : {}),
|
||||
...(args.attachments ? { attachments: args.attachments } : {})
|
||||
})
|
||||
if (!response.ok) {
|
||||
return fromApi(response)
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { LifecycleDeps } from './lifecycle'
|
||||
import { memberChangeTime, recordMemberChange } from './member-changes'
|
||||
import { revokeMemberReaderKeys } from './read-snapshots'
|
||||
import { disableMemberRoutines } from './routines/runs'
|
||||
import { forgetMemberPokes } from './team-presence'
|
||||
|
||||
export type MemberRemoval = {
|
||||
keysRevoked: number
|
||||
@@ -41,6 +42,8 @@ export async function removeMember(
|
||||
const devicesRevoked = await revokeMemberDeviceSessions(life.db, accountId, userId, now)
|
||||
// No device of theirs can open a sleeping workspace's read snapshot again (wrapped keys deleted).
|
||||
const readerKeysRevoked = await revokeMemberReaderKeys(life.db, accountId, userId, now)
|
||||
// Their Pokes opt-in goes (it doubles as proof of membership for receiving one).
|
||||
await forgetMemberPokes(life.db, accountId, userId, now)
|
||||
const grants = await revokeGrantsForMember(life, accountId, userId)
|
||||
// Routines run with their creator's secrets: a departed member's stop, and nothing of theirs keeps running.
|
||||
const routines = await disableMemberRoutines({ life }, accountId, userId)
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
// Model spend by member and UTC hour, for teammate profiles' heatmap (team-presence.ts). The
|
||||
// workspace registry keeps only a cumulative per-workspace total; this dates each increase and
|
||||
// credits whoever's client reported it.
|
||||
const HOUR_MS = 3_600_000
|
||||
|
||||
/** Records the reporter's new model spend: the growth of a workspace's cumulative token total. */
|
||||
export async function recordTokenSpend(
|
||||
db: D1Database,
|
||||
accountId: string,
|
||||
userId: string,
|
||||
previousUsdMicros: number | null,
|
||||
nextUsdMicros: number,
|
||||
now: number
|
||||
): Promise<void> {
|
||||
const delta = nextUsdMicros - (previousUsdMicros ?? 0)
|
||||
if (delta <= 0) {
|
||||
return
|
||||
}
|
||||
await db
|
||||
.prepare(
|
||||
`INSERT INTO member_usage_hours (account_id, user_id, hour, token_usd_micros) VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT (account_id, user_id, hour) DO UPDATE SET token_usd_micros = token_usd_micros + excluded.token_usd_micros`
|
||||
)
|
||||
.bind(accountId, userId, Math.floor(now / HOUR_MS), delta)
|
||||
.run()
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// Org URL slugs for workspace links (orca://cloud/<slug>/W-123).
|
||||
// GET /v1/team/org?name=<org display name> -> {slug, orgId}; the first call names it from `name`
|
||||
// PUT /v1/team/org {slug} org owner/admin renames it (409 when another org has it)
|
||||
// Auth owns orgs and knows their names; this Worker only sees ids. So the first member to ask
|
||||
// proposes a slug from the name their client shows, and the Worker makes it unique. Personal
|
||||
// accounts have no slug: their links keep the sandbox id form (orca://cloud/w/<sbx>).
|
||||
import { z } from 'zod'
|
||||
import type { SandboxCaller } from './auth'
|
||||
import { WorkspaceError, isOrgAdmin } from './workspaces'
|
||||
|
||||
/** Path words a slug can't take: they'd read as a different link form. */
|
||||
const RESERVED = new Set(['w', 'c', 'me', 'api', 'app', 'new', 'org', 'team', 'settings', 'cloud', 'orca', 'admin', 'help', 'setup'])
|
||||
|
||||
export const SLUG = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/
|
||||
|
||||
export function isValidSlug(value: string): boolean {
|
||||
return SLUG.test(value) && !value.includes('--') && !RESERVED.has(value)
|
||||
}
|
||||
|
||||
/** "Acme Labs, Inc." → "acme-labs-inc"; falls back to "team" when nothing usable is left. */
|
||||
export function slugify(name: string): string {
|
||||
const base = name
|
||||
.normalize('NFKD')
|
||||
.replace(/[̀-ͯ]/g, '')
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
.slice(0, 32)
|
||||
.replace(/-+$/g, '')
|
||||
return base.length >= 2 && !RESERVED.has(base) ? base : base ? `${base}-team` : 'team'
|
||||
}
|
||||
|
||||
type Row = { account_id: string; slug: string }
|
||||
|
||||
/** `org:abc` / `dev:org:abc` → `abc` (the id the desktop's org list uses). */
|
||||
export function orgIdOf(accountId: string): string | null {
|
||||
const match = /^(?:dev:)?org:(.+)$/.exec(accountId)
|
||||
return match ? match[1]! : null
|
||||
}
|
||||
|
||||
export async function slugForAccount(db: D1Database, accountId: string): Promise<string | null> {
|
||||
const row = await db.prepare('SELECT slug FROM org_slugs WHERE account_id = ?').bind(accountId).first<{ slug: string }>()
|
||||
return row?.slug ?? null
|
||||
}
|
||||
|
||||
export async function accountForSlug(db: D1Database, slug: string): Promise<string | null> {
|
||||
if (!isValidSlug(slug)) {
|
||||
return null
|
||||
}
|
||||
const row = await db.prepare('SELECT account_id FROM org_slugs WHERE slug = ?').bind(slug).first<Row>()
|
||||
return row?.account_id ?? null
|
||||
}
|
||||
|
||||
const NameQuery = z.string().trim().min(1).max(120)
|
||||
|
||||
export async function getOrgSlug(db: D1Database, caller: SandboxCaller, url: URL, now: number) {
|
||||
const orgId = caller.orgId ? orgIdOf(caller.accountId) : null
|
||||
if (!orgId) {
|
||||
return { slug: null, orgId: null }
|
||||
}
|
||||
const existing = await slugForAccount(db, caller.accountId)
|
||||
if (existing) {
|
||||
return { slug: existing, orgId }
|
||||
}
|
||||
const name = NameQuery.safeParse(url.searchParams.get('name') ?? '')
|
||||
if (!name.success) {
|
||||
// Nothing to name it from yet; the next client that knows the org's name will.
|
||||
return { slug: null, orgId }
|
||||
}
|
||||
const base = slugify(name.data)
|
||||
for (let attempt = 0; attempt < 20; attempt += 1) {
|
||||
const candidate = attempt === 0 ? base : `${base.slice(0, 32)}-${attempt + 1}`
|
||||
const result = await db
|
||||
.prepare('INSERT OR IGNORE INTO org_slugs (account_id, slug, created_at, created_by, updated_at) VALUES (?, ?, ?, ?, ?)')
|
||||
.bind(caller.accountId, candidate, now, caller.userId, now)
|
||||
.run()
|
||||
if (result.meta.changes === 1) {
|
||||
return { slug: candidate, orgId }
|
||||
}
|
||||
// Either another org holds this slug, or a teammate just named ours (then use theirs).
|
||||
const raced = await slugForAccount(db, caller.accountId)
|
||||
if (raced) {
|
||||
return { slug: raced, orgId }
|
||||
}
|
||||
}
|
||||
throw new WorkspaceError('conflict', 'slug_exhausted')
|
||||
}
|
||||
|
||||
const PutSchema = z.object({ slug: z.string().min(1).max(40) }).strict()
|
||||
|
||||
export async function putOrgSlug(db: D1Database, caller: SandboxCaller, body: unknown, now: number) {
|
||||
const orgId = caller.orgId ? orgIdOf(caller.accountId) : null
|
||||
if (!orgId) {
|
||||
throw new WorkspaceError('invalid_request', 'personal_account')
|
||||
}
|
||||
if (!isOrgAdmin(caller)) {
|
||||
throw new WorkspaceError('forbidden', 'admin_only')
|
||||
}
|
||||
const parsed = PutSchema.safeParse(body)
|
||||
if (!parsed.success || !isValidSlug(parsed.data.slug)) {
|
||||
throw new WorkspaceError('invalid_request', 'invalid_slug')
|
||||
}
|
||||
const slug = parsed.data.slug
|
||||
const holder = await accountForSlug(db, slug)
|
||||
if (holder && holder !== caller.accountId) {
|
||||
throw new WorkspaceError('conflict', 'slug_taken')
|
||||
}
|
||||
await db
|
||||
.prepare(
|
||||
`INSERT INTO org_slugs (account_id, slug, created_at, created_by, updated_at) VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT (account_id) DO UPDATE SET slug = excluded.slug, updated_at = excluded.updated_at`
|
||||
)
|
||||
.bind(caller.accountId, slug, now, caller.userId, now)
|
||||
.run()
|
||||
.catch((error: unknown) => {
|
||||
// The UNIQUE index lost a race with another org claiming the same slug.
|
||||
if (String(error).includes('UNIQUE')) {
|
||||
throw new WorkspaceError('conflict', 'slug_taken')
|
||||
}
|
||||
throw error
|
||||
})
|
||||
return { slug, orgId }
|
||||
}
|
||||
@@ -111,6 +111,11 @@ export type SandboxProviderApi = {
|
||||
updateSnapshotExpiration(name: string, expirationMs: number): Promise<void>
|
||||
/** A small text file from the VM (files API: not kept as command logs). Null when absent. */
|
||||
readFile(sessionId: string, path: string): Promise<string | null>
|
||||
/**
|
||||
* Writes one file (absolute path, parents created) into a running session through the files API,
|
||||
* so the bytes never pass through argv, env or command logs. Optional: only API attachments use it.
|
||||
*/
|
||||
writeFile?(sessionId: string, path: string, bytes: Uint8Array): Promise<void>
|
||||
/** Resolves when already gone. */
|
||||
deleteSandbox(name: string): Promise<void>
|
||||
listSnapshots(name: string): Promise<ProviderSnapshot[]>
|
||||
|
||||
@@ -49,8 +49,33 @@ export type StartInputs = {
|
||||
prelude?: { script: string; env?: Record<string, string> }
|
||||
/** This session's share-proxy key (src/share-crypto.ts); the proxy keeps it in memory only. */
|
||||
shareProxyKey?: string
|
||||
/**
|
||||
* The VM's hostname for this boot (workspaceHostname): terminal prompts read `ubuntu@<workspace>`
|
||||
* instead of the provider's VM id, which changes on every wake (JA-27). Set before orcad starts, so
|
||||
* every shell it opens sees it. Best effort: a failure keeps the provider's name.
|
||||
*/
|
||||
hostname?: string
|
||||
}
|
||||
|
||||
/** A hostname label from a workspace name: lowercase letters, digits and dashes, at most 63 chars. */
|
||||
export function workspaceHostname(name: string | null | undefined): string | undefined {
|
||||
const label = (name ?? '')
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9-]+/g, '-')
|
||||
.replace(/-+/g, '-')
|
||||
.replace(/^-+/, '')
|
||||
.slice(0, 63)
|
||||
.replace(/-+$/, '')
|
||||
return label.length > 0 ? label : undefined
|
||||
}
|
||||
|
||||
// Inline per boot, no image change: hostname plus an /etc/hosts entry (sudo would warn without one).
|
||||
const HOSTNAME_STEP = [
|
||||
'{ [ -n "${ORCA_HOSTNAME:-}" ] && sudo -n hostname "$ORCA_HOSTNAME" &&',
|
||||
'{ grep -q "[[:space:]]$ORCA_HOSTNAME\\$" /etc/hosts || printf "127.0.1.1 %s\\n" "$ORCA_HOSTNAME" | sudo -n tee -a /etc/hosts; }; }',
|
||||
'>/dev/null 2>&1 || true; unset ORCA_HOSTNAME'
|
||||
].join(' ')
|
||||
|
||||
/** `NAME=<base64 utf-8 value>` lines, so values with newlines or quotes survive bash intact. */
|
||||
export function encodeSecretEnv(env: Record<string, string>): string {
|
||||
return Object.entries(env)
|
||||
@@ -100,6 +125,10 @@ export async function startOrcad(
|
||||
if (inputs.shareProxyKey) {
|
||||
env.ORCA_SHARE_PROXY_KEY = inputs.shareProxyKey
|
||||
}
|
||||
if (inputs.hostname) {
|
||||
env.ORCA_HOSTNAME = inputs.hostname
|
||||
}
|
||||
const hostnameStep = inputs.hostname ? `${HOSTNAME_STEP}; ` : ''
|
||||
// The prelude rides in an env var (the start script's `env -i` keeps it out of orcad) so one
|
||||
// round trip both prepares the checkout and starts orcad.
|
||||
const result = await provider.runCommand(
|
||||
@@ -108,11 +137,16 @@ export async function startOrcad(
|
||||
? {
|
||||
command: 'bash',
|
||||
// The prelude never sees the share-proxy or ready keys; only the start script gets them.
|
||||
args: ['-c', `env -u ORCA_SHARE_PROXY_KEY -u ORCA_READY_KEY bash -c "$ORCA_PRELUDE" 1>&2 || true; unset ORCA_PRELUDE; exec ${START_COMMAND}`],
|
||||
args: [
|
||||
'-c',
|
||||
`${hostnameStep}env -u ORCA_SHARE_PROXY_KEY -u ORCA_READY_KEY bash -c "$ORCA_PRELUDE" 1>&2 || true; unset ORCA_PRELUDE; exec ${START_COMMAND}`
|
||||
],
|
||||
env: { ...env, ...inputs.prelude.env, ORCA_PRELUDE: inputs.prelude.script },
|
||||
timeoutMs: START_TIMEOUT_MS
|
||||
}
|
||||
: { command: START_COMMAND, env, timeoutMs: START_TIMEOUT_MS }
|
||||
: hostnameStep
|
||||
? { command: 'bash', args: ['-c', `${hostnameStep}exec ${START_COMMAND}`], env, timeoutMs: START_TIMEOUT_MS }
|
||||
: { command: START_COMMAND, env, timeoutMs: START_TIMEOUT_MS }
|
||||
)
|
||||
if (result.exitCode !== 0) {
|
||||
throw new VmCommandError('orcad_start_failed')
|
||||
|
||||
@@ -71,6 +71,8 @@ export type SandboxRow = {
|
||||
last_activity_at: number | null
|
||||
last_activity_by: string | null
|
||||
token_usd_micros: number | null
|
||||
/** 0051: this workspace's number in its account (shown as W-123); null only on rows from before it. */
|
||||
number?: number | null
|
||||
}
|
||||
|
||||
export type WorkspaceVisibility = 'private' | 'team'
|
||||
@@ -118,18 +120,28 @@ export async function insertSandbox(
|
||||
Partial<Pick<SandboxRow, 'environment_id' | 'environment_build_id' | 'source_snapshot_id' | 'name' | 'repo_branch' | 'visibility' | 'section'>>,
|
||||
now: number
|
||||
): Promise<SandboxRow> {
|
||||
await db
|
||||
.prepare(
|
||||
`INSERT INTO sandboxes (id, account_id, user_id, workspace_id, provider, provider_name, status,
|
||||
machine_size, region, generation, created_at, updated_at, repo_url, environment_id, environment_build_id,
|
||||
source_snapshot_id, created_by, name, repo_branch, visibility, section, last_activity_at, last_activity_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, 'creating', ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
)
|
||||
.bind(row.id, row.account_id, row.user_id, row.workspace_id, row.provider, row.provider_name,
|
||||
row.machine_size, row.region, now, now, row.repo_url, row.environment_id ?? null,
|
||||
row.environment_build_id ?? null, row.source_snapshot_id ?? null, row.user_id, row.name ?? null,
|
||||
row.repo_branch ?? null, row.visibility ?? 'private', row.section ?? null, now, row.user_id)
|
||||
.run()
|
||||
// One transaction: bump the account's counter, then take its value as this row's number (W-123).
|
||||
// A failed insert rolls the bump back; a destroyed row keeps its number, so none is ever reused.
|
||||
await db.batch([
|
||||
db
|
||||
.prepare(
|
||||
`INSERT INTO org_workspace_counters (account_id, last_number) VALUES (?, 1)
|
||||
ON CONFLICT (account_id) DO UPDATE SET last_number = last_number + 1`
|
||||
)
|
||||
.bind(row.account_id),
|
||||
db
|
||||
.prepare(
|
||||
`INSERT INTO sandboxes (id, account_id, user_id, workspace_id, provider, provider_name, status,
|
||||
machine_size, region, generation, created_at, updated_at, repo_url, environment_id, environment_build_id,
|
||||
source_snapshot_id, created_by, name, repo_branch, visibility, section, last_activity_at, last_activity_by, number)
|
||||
VALUES (?, ?, ?, ?, ?, ?, 'creating', ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
|
||||
(SELECT last_number FROM org_workspace_counters WHERE account_id = ?))`
|
||||
)
|
||||
.bind(row.id, row.account_id, row.user_id, row.workspace_id, row.provider, row.provider_name,
|
||||
row.machine_size, row.region, now, now, row.repo_url, row.environment_id ?? null,
|
||||
row.environment_build_id ?? null, row.source_snapshot_id ?? null, row.user_id, row.name ?? null,
|
||||
row.repo_branch ?? null, row.visibility ?? 'private', row.section ?? null, now, row.user_id, row.account_id)
|
||||
])
|
||||
const inserted = await getSandbox(db, row.id)
|
||||
if (!inserted) {
|
||||
throw new Error('sandbox insert lost')
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
// Minimal ustar writer for the Vercel files API (POST .../fs/write takes a gzipped tarball, the same
|
||||
// format @vercel/sandbox's FileWriter streams). Workers have no tar library; one regular file plus
|
||||
// its parent directories is all the control plane ever writes.
|
||||
|
||||
const BLOCK = 512
|
||||
|
||||
function octal(value: number, width: number): string {
|
||||
// width includes the trailing NUL.
|
||||
return value.toString(8).padStart(width - 1, '0')
|
||||
}
|
||||
|
||||
function header(path: string, entry: { type: 'file' | 'dir'; size: number; mode: number; mtime: number }): Uint8Array {
|
||||
const block = new Uint8Array(BLOCK)
|
||||
const encoder = new TextEncoder()
|
||||
const put = (offset: number, text: string, width: number) => {
|
||||
const bytes = encoder.encode(text)
|
||||
if (bytes.length > width) {
|
||||
throw new Error('tar_field_too_long')
|
||||
}
|
||||
block.set(bytes, offset)
|
||||
}
|
||||
// Long paths split at a slash: prefix (155) + "/" + name (100).
|
||||
let name = path
|
||||
let prefix = ''
|
||||
if (encoder.encode(path).length > 100) {
|
||||
const cut = path.lastIndexOf('/', path.length - 2)
|
||||
if (cut <= 0) {
|
||||
throw new Error('tar_name_too_long')
|
||||
}
|
||||
prefix = path.slice(0, cut)
|
||||
name = path.slice(cut + 1)
|
||||
}
|
||||
put(0, name, 100)
|
||||
put(100, octal(entry.mode, 8), 8)
|
||||
put(108, octal(0, 8), 8)
|
||||
put(116, octal(0, 8), 8)
|
||||
put(124, octal(entry.size, 12), 12)
|
||||
put(136, octal(Math.floor(entry.mtime / 1000), 12), 12)
|
||||
block.fill(0x20, 148, 156) // checksum field counts as spaces while summing
|
||||
put(156, entry.type === 'dir' ? '5' : '0', 1)
|
||||
put(257, 'ustar\u000000', 8)
|
||||
put(345, prefix, 155)
|
||||
const sum = block.reduce((total, byte) => total + byte, 0)
|
||||
put(148, `${octal(sum, 7)}\u0000 `, 8)
|
||||
return block
|
||||
}
|
||||
|
||||
/**
|
||||
* A gzipped tarball holding `dirs` (created first, mode 0755) and one file at `path` (0644). Paths
|
||||
* are relative to the extraction directory and must not contain `..` segments.
|
||||
*/
|
||||
export async function tarGzipFile(input: { dirs: string[]; path: string; bytes: Uint8Array; mtime: number }): Promise<ArrayBuffer> {
|
||||
for (const p of [...input.dirs, input.path]) {
|
||||
if (p.startsWith('/') || p.split('/').some((segment) => segment === '..' || segment === '')) {
|
||||
throw new Error('tar_bad_path')
|
||||
}
|
||||
}
|
||||
const padding = (BLOCK - (input.bytes.length % BLOCK)) % BLOCK
|
||||
const parts: Uint8Array[] = [
|
||||
...input.dirs.map((dir) => header(`${dir}/`, { type: 'dir', size: 0, mode: 0o755, mtime: input.mtime })),
|
||||
header(input.path, { type: 'file', size: input.bytes.length, mode: 0o644, mtime: input.mtime }),
|
||||
input.bytes,
|
||||
new Uint8Array(padding),
|
||||
new Uint8Array(BLOCK * 2) // end-of-archive marker
|
||||
]
|
||||
const stream = new Blob(parts as BlobPart[]).stream().pipeThrough(new CompressionStream('gzip'))
|
||||
return new Response(stream).arrayBuffer()
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
// Teammate profiles and Pokes (Conductor 0.91 parity).
|
||||
// GET /v1/team/members/:userId/profile?utcOffsetMin=<-840..840>
|
||||
// POST /v1/team/members/:userId/poke
|
||||
// GET /v1/team/pokes the caller's unseen pokes (last 24 h) and their opt-in
|
||||
// PUT /v1/team/pokes/settings {enabled}
|
||||
// POST /v1/team/pokes/seen {ids}
|
||||
// Privacy: a profile shows what a teammate can already see (name, role from the roster, workspaces
|
||||
// they can open). The 0–4 intensity per day is shared only by people who turned on "Pokes and
|
||||
// activity" (the same opt-in as Pokes); exact amounts only ever go to the person themself. The
|
||||
// heatmap counts the member's sandbox time (usage_outbox, attributed to the workspace owner) plus
|
||||
// model spend their own client reported (member_usage_hours).
|
||||
import { z } from 'zod'
|
||||
import type { SandboxCaller } from './auth'
|
||||
import { memberNamesFor } from './member-names'
|
||||
import type { SandboxRow } from './store'
|
||||
import { canSee, COMPUTE_USD_MICROS_PER_HOUR, workspaceViews } from './workspaces'
|
||||
import {
|
||||
POKE_INBOX_TTL_MS,
|
||||
POKE_PAIR_COOLDOWN_MS,
|
||||
POKE_SENDER_HOURLY_LIMIT,
|
||||
TEAMMATE_HEATMAP_DAYS,
|
||||
TEAMMATE_RECENT_WORKSPACES,
|
||||
type PokeRefusal
|
||||
} from '../../../../src/shared/cloud-workspaces/team-presence-wire'
|
||||
|
||||
const DAY_MS = 86_400_000
|
||||
const HOUR_MS = 3_600_000
|
||||
|
||||
export class TeamPresenceError extends Error {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
readonly code: string,
|
||||
readonly reason?: PokeRefusal | string,
|
||||
readonly retryAfterMs?: number
|
||||
) {
|
||||
super(reason ? `${code}:${reason}` : code)
|
||||
this.name = 'TeamPresenceError'
|
||||
}
|
||||
}
|
||||
|
||||
export const MEMBER_ID = /^[A-Za-z0-9_.:-]{1,128}$/
|
||||
|
||||
function isoDate(dayIndex: number): string {
|
||||
return new Date(dayIndex * DAY_MS).toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
/** 0 for nothing; otherwise 1–4 relative to the member's own busiest day in the window. */
|
||||
export function usageLevel(value: number, max: number): number {
|
||||
if (value <= 0 || max <= 0) {
|
||||
return 0
|
||||
}
|
||||
return Math.min(4, Math.max(1, Math.ceil((value / max) * 4)))
|
||||
}
|
||||
|
||||
/**
|
||||
* Per local day: sandbox time on workspaces the member owns, and model spend they reported. Days
|
||||
* are the viewer's calendar days (utcOffsetMin); a segment crossing midnight is split.
|
||||
*/
|
||||
export async function memberDailyUsage(
|
||||
db: D1Database,
|
||||
accountId: string,
|
||||
userId: string,
|
||||
now: number,
|
||||
utcOffsetMin: number,
|
||||
days = TEAMMATE_HEATMAP_DAYS
|
||||
) {
|
||||
const offsetMs = utcOffsetMin * 60_000
|
||||
const today = Math.floor((now + offsetMs) / DAY_MS)
|
||||
const firstDay = today - days + 1
|
||||
const windowStart = firstDay * DAY_MS - offsetMs
|
||||
const computeMs = new Array<number>(days).fill(0)
|
||||
const tokenUsd = new Array<number>(days).fill(0)
|
||||
const { results: segments } = await db
|
||||
.prepare(
|
||||
`SELECT u.started_at, u.ended_at FROM usage_outbox u JOIN sandboxes s ON s.id = u.sandbox_id
|
||||
WHERE u.account_id = ? AND u.started_at < ? AND u.ended_at > ? AND s.user_id = ?`
|
||||
)
|
||||
.bind(accountId, now, windowStart, userId)
|
||||
.all<{ started_at: number; ended_at: number }>()
|
||||
for (const seg of segments) {
|
||||
let from = Math.max(seg.started_at, windowStart)
|
||||
const to = Math.min(seg.ended_at, now)
|
||||
while (from < to) {
|
||||
const day = Math.floor((from + offsetMs) / DAY_MS)
|
||||
const dayEnd = (day + 1) * DAY_MS - offsetMs
|
||||
const end = Math.min(to, dayEnd)
|
||||
const index = day - firstDay
|
||||
if (index >= 0 && index < days) {
|
||||
computeMs[index]! += end - from
|
||||
}
|
||||
from = end
|
||||
}
|
||||
}
|
||||
const { results: hours } = await db
|
||||
.prepare(
|
||||
`SELECT hour, token_usd_micros FROM member_usage_hours WHERE account_id = ? AND user_id = ? AND hour >= ?`
|
||||
)
|
||||
.bind(accountId, userId, Math.floor(windowStart / HOUR_MS))
|
||||
.all<{ hour: number; token_usd_micros: number }>()
|
||||
for (const row of hours) {
|
||||
const index = Math.floor((row.hour * HOUR_MS + offsetMs) / DAY_MS) - firstDay
|
||||
if (index >= 0 && index < days) {
|
||||
tokenUsd[index]! += row.token_usd_micros
|
||||
}
|
||||
}
|
||||
const rate = COMPUTE_USD_MICROS_PER_HOUR.standard
|
||||
const usdMicros = computeMs.map((ms, i) => Math.round((ms / HOUR_MS) * rate) + tokenUsd[i]!)
|
||||
const max = Math.max(0, ...usdMicros)
|
||||
return {
|
||||
start: isoDate(firstDay),
|
||||
levels: usdMicros.map((value) => usageLevel(value, max)),
|
||||
activeDays: usdMicros.filter((value) => value > 0).length,
|
||||
computeMs,
|
||||
usdMicros
|
||||
}
|
||||
}
|
||||
|
||||
async function pokesEnabled(db: D1Database, accountId: string, userId: string): Promise<boolean> {
|
||||
const row = await db
|
||||
.prepare('SELECT enabled FROM member_poke_prefs WHERE account_id = ? AND user_id = ?')
|
||||
.bind(accountId, userId)
|
||||
.first<{ enabled: number }>()
|
||||
return row?.enabled === 1
|
||||
}
|
||||
|
||||
function requireTeam(caller: SandboxCaller): void {
|
||||
if (!caller.orgId) {
|
||||
throw new TeamPresenceError(400, 'invalid_request', 'personal_account')
|
||||
}
|
||||
}
|
||||
|
||||
export type ActivitySharing = 'opt_in' | 'team'
|
||||
|
||||
export async function memberProfile(
|
||||
db: D1Database,
|
||||
caller: SandboxCaller,
|
||||
userId: string,
|
||||
url: URL,
|
||||
now: number,
|
||||
activitySharing: ActivitySharing = 'opt_in'
|
||||
) {
|
||||
const self = userId === caller.userId
|
||||
if (!self && !caller.orgId) {
|
||||
// A personal account has no teammates.
|
||||
throw new TeamPresenceError(404, 'not_found')
|
||||
}
|
||||
const offset = Number(url.searchParams.get('utcOffsetMin') ?? '0')
|
||||
const utcOffsetMin = Number.isInteger(offset) && Math.abs(offset) <= 14 * 60 ? offset : 0
|
||||
const { results } = await db
|
||||
.prepare(
|
||||
`SELECT * FROM sandboxes WHERE account_id = ? AND status <> 'destroyed' AND archived_at IS NULL
|
||||
AND (user_id = ? OR created_by = ?) ORDER BY COALESCE(last_activity_at, updated_at) DESC LIMIT 100`
|
||||
)
|
||||
.bind(caller.accountId, userId, userId)
|
||||
.all<SandboxRow>()
|
||||
// Only workspaces the viewer could already open from Home: a teammate's private ones stay private.
|
||||
const rows = results.filter((row) => !row.hidden && canSee(caller, row)).slice(0, TEAMMATE_RECENT_WORKSPACES)
|
||||
const [names, recentWorkspaces, mine, theirs] = await Promise.all([
|
||||
memberNamesFor(db, caller.accountId, [userId]),
|
||||
workspaceViews(db, caller, rows, now),
|
||||
caller.orgId ? pokesEnabled(db, caller.accountId, caller.userId) : Promise.resolve(false),
|
||||
caller.orgId && !self ? pokesEnabled(db, caller.accountId, userId) : Promise.resolve(false)
|
||||
])
|
||||
// Your own heatmap always; a teammate's only when they chose to share it.
|
||||
const usage = self || theirs || activitySharing === 'team' ? await memberDailyUsage(db, caller.accountId, userId, now, utcOffsetMin) : null
|
||||
return {
|
||||
profile: {
|
||||
userId,
|
||||
self,
|
||||
name: names.get(userId) ?? null,
|
||||
usage: usage && {
|
||||
start: usage.start,
|
||||
levels: usage.levels,
|
||||
activeDays: usage.activeDays,
|
||||
own: self ? { computeMs: usage.computeMs, usdMicros: usage.usdMicros } : null
|
||||
},
|
||||
recentWorkspaces,
|
||||
pokes: { enabled: mine, teammateEnabled: self ? null : theirs }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const PokeSettingsBody = z.object({ enabled: z.boolean() }).strict()
|
||||
export const PokesSeenBody = z.object({ ids: z.array(z.string().regex(/^pok_[0-9a-f]{24}$/)).min(1).max(50) }).strict()
|
||||
|
||||
export async function setPokeSettings(db: D1Database, caller: SandboxCaller, enabled: boolean, now: number) {
|
||||
requireTeam(caller)
|
||||
const statements = [
|
||||
db
|
||||
.prepare(
|
||||
`INSERT INTO member_poke_prefs (account_id, user_id, enabled, updated_at) VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT (account_id, user_id) DO UPDATE SET enabled = excluded.enabled, updated_at = excluded.updated_at`
|
||||
)
|
||||
.bind(caller.accountId, caller.userId, enabled ? 1 : 0, now)
|
||||
]
|
||||
if (!enabled) {
|
||||
// Turning it off drops anything waiting, so turning it back on doesn't replay old pokes.
|
||||
statements.push(
|
||||
db
|
||||
.prepare('UPDATE member_pokes SET seen_at = ? WHERE account_id = ? AND to_user_id = ? AND seen_at IS NULL')
|
||||
.bind(now, caller.accountId, caller.userId)
|
||||
)
|
||||
}
|
||||
await db.batch(statements)
|
||||
return { enabled }
|
||||
}
|
||||
|
||||
export async function pokeInbox(db: D1Database, caller: SandboxCaller, now: number) {
|
||||
if (!caller.orgId) {
|
||||
return { enabled: false, pokes: [] }
|
||||
}
|
||||
const enabled = await pokesEnabled(db, caller.accountId, caller.userId)
|
||||
if (!enabled) {
|
||||
return { enabled, pokes: [] }
|
||||
}
|
||||
const { results } = await db
|
||||
.prepare(
|
||||
`SELECT id, from_user_id, created_at FROM member_pokes
|
||||
WHERE account_id = ? AND to_user_id = ? AND seen_at IS NULL AND created_at > ?
|
||||
ORDER BY created_at DESC LIMIT 20`
|
||||
)
|
||||
.bind(caller.accountId, caller.userId, now - POKE_INBOX_TTL_MS)
|
||||
.all<{ id: string; from_user_id: string; created_at: number }>()
|
||||
const names = await memberNamesFor(db, caller.accountId, results.map((r) => r.from_user_id))
|
||||
return {
|
||||
enabled,
|
||||
pokes: results.map((r) => ({ id: r.id, fromUserId: r.from_user_id, fromName: names.get(r.from_user_id) ?? null, at: r.created_at }))
|
||||
}
|
||||
}
|
||||
|
||||
export async function markPokesSeen(db: D1Database, caller: SandboxCaller, ids: readonly string[], now: number) {
|
||||
await db
|
||||
.prepare(
|
||||
`UPDATE member_pokes SET seen_at = ? WHERE account_id = ? AND to_user_id = ? AND seen_at IS NULL
|
||||
AND id IN (${ids.map(() => '?').join(', ')})`
|
||||
)
|
||||
.bind(now, caller.accountId, caller.userId, ...ids)
|
||||
.run()
|
||||
return { ok: true as const }
|
||||
}
|
||||
|
||||
function pokeId(): string {
|
||||
const bytes = crypto.getRandomValues(new Uint8Array(12))
|
||||
return `pok_${[...bytes].map((b) => b.toString(16).padStart(2, '0')).join('')}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Both people must have Pokes on. The teammate's own opt-in (written with their token in this
|
||||
* account, and dropped when they leave it) is also what proves they are a member.
|
||||
*/
|
||||
export async function sendPoke(db: D1Database, caller: SandboxCaller, toUserId: string, now: number) {
|
||||
requireTeam(caller)
|
||||
if (toUserId === caller.userId) {
|
||||
throw new TeamPresenceError(400, 'invalid_request', 'self')
|
||||
}
|
||||
if (!(await pokesEnabled(db, caller.accountId, caller.userId))) {
|
||||
throw new TeamPresenceError(409, 'conflict', 'pokes_off')
|
||||
}
|
||||
if (!(await pokesEnabled(db, caller.accountId, toUserId))) {
|
||||
throw new TeamPresenceError(409, 'conflict', 'teammate_pokes_off')
|
||||
}
|
||||
const recent = await db
|
||||
.prepare(
|
||||
`SELECT COUNT(*) AS sent, MAX(CASE WHEN to_user_id = ? THEN created_at END) AS last_to_them
|
||||
FROM member_pokes WHERE account_id = ? AND from_user_id = ? AND created_at > ?`
|
||||
)
|
||||
.bind(toUserId, caller.accountId, caller.userId, now - HOUR_MS)
|
||||
.first<{ sent: number; last_to_them: number | null }>()
|
||||
const lastToThem = recent?.last_to_them ?? null
|
||||
if (lastToThem !== null && now - lastToThem < POKE_PAIR_COOLDOWN_MS) {
|
||||
throw new TeamPresenceError(429, 'rate_limited', 'poke_cooldown', POKE_PAIR_COOLDOWN_MS - (now - lastToThem))
|
||||
}
|
||||
if ((recent?.sent ?? 0) >= POKE_SENDER_HOURLY_LIMIT) {
|
||||
throw new TeamPresenceError(429, 'rate_limited', 'poke_rate', HOUR_MS)
|
||||
}
|
||||
const id = pokeId()
|
||||
await db.batch([
|
||||
db
|
||||
.prepare('INSERT INTO member_pokes (id, account_id, from_user_id, to_user_id, created_at) VALUES (?, ?, ?, ?, ?)')
|
||||
.bind(id, caller.accountId, caller.userId, toUserId, now),
|
||||
// Keep the table small: nothing older than a day is ever read.
|
||||
db.prepare('DELETE FROM member_pokes WHERE account_id = ? AND created_at < ?').bind(caller.accountId, now - 2 * POKE_INBOX_TTL_MS)
|
||||
])
|
||||
return { poke: { id, at: now } }
|
||||
}
|
||||
|
||||
/** A member left: their opt-in and anything waiting for them goes; pokes they sent stop showing. */
|
||||
export async function forgetMemberPokes(db: D1Database, accountId: string, userId: string, now: number): Promise<void> {
|
||||
await db.batch([
|
||||
db.prepare('DELETE FROM member_poke_prefs WHERE account_id = ? AND user_id = ?').bind(accountId, userId),
|
||||
db
|
||||
.prepare('UPDATE member_pokes SET seen_at = ? WHERE account_id = ? AND (to_user_id = ? OR from_user_id = ?) AND seen_at IS NULL')
|
||||
.bind(now, accountId, userId, userId)
|
||||
])
|
||||
}
|
||||
|
||||
/** Routes under /v1/team/members and /v1/team/pokes; null when the path isn't one of them. */
|
||||
export async function teamPresenceRoute(
|
||||
db: D1Database,
|
||||
caller: SandboxCaller,
|
||||
request: Request,
|
||||
url: URL,
|
||||
now: number,
|
||||
readJson: () => Promise<unknown>,
|
||||
options: { activitySharing?: ActivitySharing } = {}
|
||||
): Promise<unknown | null> {
|
||||
const member = /^\/v1\/team\/members\/([^/]+)\/(profile|poke)$/.exec(url.pathname)
|
||||
if (member) {
|
||||
let userId: string
|
||||
try {
|
||||
userId = decodeURIComponent(member[1]!)
|
||||
} catch {
|
||||
throw new TeamPresenceError(400, 'invalid_request')
|
||||
}
|
||||
if (!MEMBER_ID.test(userId)) {
|
||||
throw new TeamPresenceError(400, 'invalid_request')
|
||||
}
|
||||
if (member[2] === 'profile' && request.method === 'GET') {
|
||||
return memberProfile(db, caller, userId, url, now, options.activitySharing)
|
||||
}
|
||||
if (member[2] === 'poke' && request.method === 'POST') {
|
||||
return sendPoke(db, caller, userId, now)
|
||||
}
|
||||
return null
|
||||
}
|
||||
if (url.pathname === '/v1/team/pokes' && request.method === 'GET') {
|
||||
return pokeInbox(db, caller, now)
|
||||
}
|
||||
if (url.pathname === '/v1/team/pokes/settings') {
|
||||
if (request.method === 'GET') {
|
||||
return { enabled: caller.orgId ? await pokesEnabled(db, caller.accountId, caller.userId) : false }
|
||||
}
|
||||
if (request.method === 'PUT') {
|
||||
const body = PokeSettingsBody.safeParse(await readJson())
|
||||
if (!body.success) {
|
||||
throw new TeamPresenceError(400, 'invalid_request')
|
||||
}
|
||||
return setPokeSettings(db, caller, body.data.enabled, now)
|
||||
}
|
||||
return null
|
||||
}
|
||||
if (url.pathname === '/v1/team/pokes/seen' && request.method === 'POST') {
|
||||
const body = PokesSeenBody.safeParse(await readJson())
|
||||
if (!body.success) {
|
||||
throw new TeamPresenceError(400, 'invalid_request')
|
||||
}
|
||||
return markPokesSeen(db, caller, body.data.ids, now)
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
import { z } from 'zod'
|
||||
import type { NetworkPolicy } from './network-policy'
|
||||
import type { GoldenImageProviderApi } from './golden-image-provider'
|
||||
import { tarGzipFile } from './tar-gzip'
|
||||
import {
|
||||
ProviderError,
|
||||
type CommandResult,
|
||||
@@ -265,6 +266,27 @@ export function createVercelSandboxApi(
|
||||
}
|
||||
},
|
||||
|
||||
async writeFile(sessionId, path, bytes) {
|
||||
// Same call @vercel/sandbox's writeFiles makes: a gzipped tarball extracted at `/`.
|
||||
const relative = path.replace(/^\/+/, '')
|
||||
const segments = relative.split('/')
|
||||
const dirs = segments.slice(0, -1).map((_, i) => segments.slice(0, i + 1).join('/'))
|
||||
const body = await tarGzipFile({ dirs, path: relative, bytes, mtime: Date.now() })
|
||||
const url = new URL(`${base}/v2/sandboxes/sessions/${encodeURIComponent(sessionId)}/fs/write`)
|
||||
url.searchParams.set('teamId', config.teamId)
|
||||
const response = await doFetch(url, {
|
||||
method: 'POST',
|
||||
headers: { authorization: `Bearer ${config.token}`, 'content-type': 'application/gzip', 'x-cwd': '/' },
|
||||
body,
|
||||
redirect: 'manual'
|
||||
})
|
||||
if (!response.ok) {
|
||||
const parsed = ErrorBody.safeParse(await response.json().catch(() => null))
|
||||
throw new ProviderError(response.status, parsed.success ? (parsed.data.error?.code ?? null) : null)
|
||||
}
|
||||
await response.body?.cancel()
|
||||
},
|
||||
|
||||
deleteSandbox: (name) =>
|
||||
missingOk(() =>
|
||||
request('DELETE', `/v2/sandboxes/${encodeURIComponent(name)}`, {
|
||||
|
||||
@@ -75,7 +75,13 @@ export function sandboxView(row: SandboxRow, archivedAware = false) {
|
||||
}
|
||||
}
|
||||
|
||||
export function readyView(row: SandboxRow, connection: OrcadReady, cloning = false) {
|
||||
export function readyView(
|
||||
row: SandboxRow,
|
||||
connection: OrcadReady,
|
||||
cloning?: 'clone' | 'update',
|
||||
/** The client knows `mode` (feature `repo-update`); older ones show an update as a clone. */
|
||||
updateAware = false
|
||||
) {
|
||||
return {
|
||||
sandbox: sandboxView(row),
|
||||
connection: {
|
||||
@@ -84,7 +90,9 @@ export function readyView(row: SandboxRow, connection: OrcadReady, cloning = fal
|
||||
projectRoot: connection.projectRoot
|
||||
},
|
||||
// Only for a create that asked (feature `clone-progress`): the repo is still cloning.
|
||||
...(cloning ? { clone: { state: 'running' as const } } : {})
|
||||
...(cloning
|
||||
? { clone: { state: 'running' as const, ...(cloning === 'update' && updateAware ? { mode: 'update' as const } : {}) } }
|
||||
: {})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
// A member's own sidebar arrangement of cloud workspaces, stored on the account so every device
|
||||
// (desktops and the phone) shows the same pins, order and sections.
|
||||
// GET /v1/team/prefs -> {document, revision, updatedAt}
|
||||
// PUT /v1/team/prefs {document, revision} `revision` is the one the client edited (compare-and-set:
|
||||
// a stale write gets 409 and the client re-applies its edit)
|
||||
// Per member, per account: switching teams switches arrangements. Ids that no longer exist are
|
||||
// harmless (clients skip them) and are dropped the next time that client writes.
|
||||
import { z } from 'zod'
|
||||
import type { SandboxCaller } from './auth'
|
||||
import { WorkspaceError } from './workspaces'
|
||||
|
||||
const SandboxId = z.string().regex(/^sbx_[0-9a-f]{24}$/)
|
||||
const SectionName = z.string().trim().min(1).max(64).regex(/^[^\u0000-\u001f]+$/)
|
||||
|
||||
const unique = (list: readonly string[]) => new Set(list).size === list.length
|
||||
|
||||
export const WorkspacePrefsDocumentSchema = z
|
||||
.object({
|
||||
/** Pinned workspaces, top to bottom. */
|
||||
pinned: z.array(SandboxId).max(200).refine(unique, 'duplicate id'),
|
||||
/** Manual order of the rest (drag to reorder); workspaces not listed follow, newest first. */
|
||||
order: z.array(SandboxId).max(500).refine(unique, 'duplicate id'),
|
||||
/** Section order, including sections that are empty right now. */
|
||||
sections: z.array(SectionName).max(50).refine(unique, 'duplicate section'),
|
||||
/** Sections this member keeps collapsed. */
|
||||
collapsed: z.array(SectionName).max(50).refine(unique, 'duplicate section')
|
||||
})
|
||||
.strict()
|
||||
.refine((doc) => !doc.pinned.some((id) => doc.order.includes(id)), 'pinned ids stay out of order')
|
||||
|
||||
export type WorkspacePrefsDocument = z.infer<typeof WorkspacePrefsDocumentSchema>
|
||||
|
||||
const PutSchema = z
|
||||
.object({
|
||||
document: WorkspacePrefsDocumentSchema,
|
||||
revision: z.number().int().min(0),
|
||||
/** Which device wrote it (a label for debugging sync, never trusted for access). */
|
||||
deviceId: z.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/).optional()
|
||||
})
|
||||
.strict()
|
||||
|
||||
export const EMPTY_PREFS: WorkspacePrefsDocument = { pinned: [], order: [], sections: [], collapsed: [] }
|
||||
|
||||
type Row = { document: string; revision: number; updated_at: number }
|
||||
|
||||
export async function getWorkspacePrefs(db: D1Database, caller: SandboxCaller) {
|
||||
const row = await db
|
||||
.prepare('SELECT document, revision, updated_at FROM workspace_prefs WHERE account_id = ? AND user_id = ?')
|
||||
.bind(caller.accountId, caller.userId)
|
||||
.first<Row>()
|
||||
if (!row) {
|
||||
return { document: EMPTY_PREFS, revision: 0, updatedAt: null }
|
||||
}
|
||||
// A document from a newer schema parses leniently: unknown keys are ignored, bad ones reset.
|
||||
const parsed = WorkspacePrefsDocumentSchema.safeParse(JSON.parse(row.document))
|
||||
return { document: parsed.success ? parsed.data : EMPTY_PREFS, revision: row.revision, updatedAt: row.updated_at }
|
||||
}
|
||||
|
||||
export async function putWorkspacePrefs(db: D1Database, caller: SandboxCaller, body: unknown, now: number) {
|
||||
const parsed = PutSchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
throw new WorkspaceError('invalid_request')
|
||||
}
|
||||
const { document, revision, deviceId } = parsed.data
|
||||
const text = JSON.stringify(document)
|
||||
const result =
|
||||
revision === 0
|
||||
? await db
|
||||
.prepare(
|
||||
`INSERT OR IGNORE INTO workspace_prefs (account_id, user_id, document, revision, updated_at, updated_by_device)
|
||||
VALUES (?, ?, ?, 1, ?, ?)`
|
||||
)
|
||||
.bind(caller.accountId, caller.userId, text, now, deviceId ?? null)
|
||||
.run()
|
||||
: await db
|
||||
.prepare(
|
||||
`UPDATE workspace_prefs SET document = ?, revision = revision + 1, updated_at = ?, updated_by_device = ?
|
||||
WHERE account_id = ? AND user_id = ? AND revision = ?`
|
||||
)
|
||||
.bind(text, now, deviceId ?? null, caller.accountId, caller.userId, revision)
|
||||
.run()
|
||||
if (result.meta.changes !== 1) {
|
||||
throw new WorkspaceError('conflict', 'stale_revision')
|
||||
}
|
||||
return getWorkspacePrefs(db, caller)
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
// Team workspace registry: the cloud-owned list of an org's workspaces (who made it, who owns it,
|
||||
// repo/branch, state, last activity, visibility, section, cost) and who is in each one right now.
|
||||
// GET /v1/team/workspaces?scope=mine|team|all&by=<userId>&repo=<url>§ion=<s>&archived=exclude|include|only
|
||||
// GET /v1/team/workspaces?scope=mine|team|all&by=<userId>&repo=<url>§ion=<s>&archived=exclude|include|only&routines=exclude|include
|
||||
// GET /v1/team/workspaces/:id
|
||||
// PATCH /v1/team/workspaces/:id {title?, branch?, visibility?, section?, archived?, ownerUserId?, tokenUsdMicros?}
|
||||
// POST /v1/team/workspaces/:id/presence {clientId, state: viewing|typing|left, chatId?}
|
||||
// GET /v1/team/links/resolve?w=<sandboxId>&c=<chatId>
|
||||
// GET /v1/team/links/resolve?w=<sandboxId>&c=<chatId> or ?org=<slug>&n=<number>&c=<chatId>
|
||||
// Access rule: a workspace is visible to its owner, and to every member of the owning org when
|
||||
// visibility is `team`. Org owners/admins additionally see private rows' metadata (scope=all) so a
|
||||
// departed member's workspaces can be reassigned or archived — metadata only, never access.
|
||||
@@ -13,8 +13,10 @@ import type { SandboxCaller } from './auth'
|
||||
import type { MachineSize } from './entitlements'
|
||||
import { getSandbox, touchActivity, updateRegistry, type SandboxRow } from './store'
|
||||
import { memberNamesFor } from './member-names'
|
||||
import { recordTokenSpend } from './member-usage'
|
||||
import { readSnapshotTimes } from './read-snapshots'
|
||||
import { sandboxView } from './wire'
|
||||
import { accountForSlug, orgIdOf, slugForAccount } from './org-slugs'
|
||||
import { ORCA_CLOUD_OVERAGE_CENTS_PER_HOUR } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire'
|
||||
|
||||
export const PRESENCE_TTL_MS = 45_000
|
||||
@@ -170,11 +172,12 @@ function repoView(row: SandboxRow) {
|
||||
|
||||
export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows: readonly SandboxRow[], now: number) {
|
||||
const ids = rows.map((r) => r.id)
|
||||
const [presence, compute, granted, readAt] = await Promise.all([
|
||||
const [presence, compute, granted, readAt, slug] = await Promise.all([
|
||||
presenceFor(db, ids, now),
|
||||
computeMsFor(db, ids),
|
||||
activeGrantUsers(db, ids, caller.userId),
|
||||
readSnapshotTimes(db, ids)
|
||||
readSnapshotTimes(db, ids),
|
||||
rows.length > 0 ? slugForAccount(db, caller.accountId) : Promise.resolve(null)
|
||||
])
|
||||
const referenced = (row: SandboxRow, live: readonly PresenceRow[]) =>
|
||||
[row.user_id, row.created_by, row.last_activity_by, ...live.map((p) => p.user_id)].filter(
|
||||
@@ -196,6 +199,10 @@ export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows
|
||||
return {
|
||||
...sandboxView(row),
|
||||
title: row.name,
|
||||
// W-123 in its account; null only for a row that predates numbering and was never backfilled.
|
||||
number: row.number ?? null,
|
||||
// The link to copy: org slug + number when both exist, else the sandbox id form.
|
||||
link: workspaceLink(row, slug),
|
||||
repo: repoView(row),
|
||||
visibility: row.visibility,
|
||||
section: row.section,
|
||||
@@ -210,7 +217,9 @@ export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows
|
||||
// Display names (token `name` claim) for the ids above; the roster wins where it has one.
|
||||
memberNames,
|
||||
// When its sleeping read-only copy was saved ("As of"); only for those who may read it.
|
||||
readSnapshotAt: canOpen(caller, row) ? (readAt.get(row.id) ?? null) : null
|
||||
readSnapshotAt: canOpen(caller, row) ? (readAt.get(row.id) ?? null) : null,
|
||||
// Started by a routine run (Home hides these unless its Routine runs filter is on).
|
||||
fromRoutine: isRoutineRun(row)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -220,9 +229,16 @@ const ListQuery = z.object({
|
||||
by: z.string().min(1).max(128).optional(),
|
||||
repo: z.string().min(1).max(2048).optional(),
|
||||
section: z.string().min(1).max(64).optional(),
|
||||
archived: z.enum(['exclude', 'include', 'only']).default('exclude')
|
||||
archived: z.enum(['exclude', 'include', 'only']).default('exclude'),
|
||||
/** Routine runs stay off Home unless asked for (`include`), like Conductor's routine filter. */
|
||||
routines: z.enum(['exclude', 'include']).default('exclude')
|
||||
})
|
||||
|
||||
/** A routine run's VM: tagged at create, and keyed `routine-…` while it boots. */
|
||||
export function isRoutineRun(row: SandboxRow): boolean {
|
||||
return (row as { origin?: string | null }).origin === 'routine' || row.workspace_id.startsWith('routine-')
|
||||
}
|
||||
|
||||
export async function listWorkspaces(db: D1Database, caller: SandboxCaller, url: URL, now: number) {
|
||||
const query = ListQuery.safeParse(Object.fromEntries(url.searchParams))
|
||||
if (!query.success) {
|
||||
@@ -236,7 +252,7 @@ export async function listWorkspaces(db: D1Database, caller: SandboxCaller, url:
|
||||
.prepare(`SELECT * FROM sandboxes WHERE account_id = ? AND status <> 'destroyed' ORDER BY COALESCE(last_activity_at, updated_at) DESC LIMIT 500`)
|
||||
.bind(caller.accountId)
|
||||
.all<SandboxRow>()
|
||||
const rows = results.filter((row) => {
|
||||
const matching = results.filter((row) => {
|
||||
if (q.scope === 'mine' ? row.user_id !== caller.userId : q.scope === 'team' ? !canSee(caller, row) : false) {
|
||||
return false
|
||||
}
|
||||
@@ -246,7 +262,8 @@ export async function listWorkspaces(db: D1Database, caller: SandboxCaller, url:
|
||||
if (q.repo && row.repo_url !== q.repo) {
|
||||
return false
|
||||
}
|
||||
if (row.hidden) {
|
||||
// Hidden rows are machine-made: only routine runs ever come back (below), and only when asked for.
|
||||
if (row.hidden && !isRoutineRun(row)) {
|
||||
return false
|
||||
}
|
||||
if (q.section && row.section !== q.section) {
|
||||
@@ -254,7 +271,47 @@ export async function listWorkspaces(db: D1Database, caller: SandboxCaller, url:
|
||||
}
|
||||
return q.archived === 'include' || (q.archived === 'only') === (row.archived_at !== null)
|
||||
})
|
||||
return { workspaces: await workspaceViews(db, caller, rows, now) }
|
||||
const runs = matching.filter(isRoutineRun)
|
||||
const rows = q.routines === 'include' ? matching : matching.filter((row) => !isRoutineRun(row))
|
||||
const hidden = q.routines === 'include' ? [] : runs
|
||||
const [views, routineCount, hiddenCompute, routineNames] = await Promise.all([
|
||||
workspaceViews(db, caller, rows, now),
|
||||
db.prepare('SELECT COUNT(*) AS n FROM routines WHERE account_id = ? AND deleted_at IS NULL').bind(caller.accountId).first<{ n: number }>(),
|
||||
computeMsFor(db, hidden.map((row) => row.id)),
|
||||
routineNamesFor(db, caller.accountId, rows.filter(isRoutineRun))
|
||||
])
|
||||
return {
|
||||
workspaces: views.map((view, i) => ({ ...view, routineName: routineNames.get(rows[i]!.id) ?? null })),
|
||||
// Home: offer the Routine runs switch only when the team has routines, and say what it hides
|
||||
// (its count and hours still belong in the team's totals).
|
||||
routineRuns: {
|
||||
routines: routineCount?.n ?? 0,
|
||||
hidden: hidden.length,
|
||||
hiddenRunning: hidden.filter((row) => row.status === 'running' || row.status === 'creating').length,
|
||||
hiddenComputeMs: hidden.reduce((sum, row) => sum + costView(row, hiddenCompute.get(row.id) ?? 0, now).computeMs, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** sandbox id -> its routine's name, for routine runs being listed. */
|
||||
async function routineNamesFor(db: D1Database, accountId: string, rows: readonly SandboxRow[]): Promise<Map<string, string>> {
|
||||
const refs = [...new Set(rows.flatMap((row) => ((row as { origin_ref?: string | null }).origin_ref ? [(row as { origin_ref: string }).origin_ref] : [])))]
|
||||
if (refs.length === 0) {
|
||||
return new Map()
|
||||
}
|
||||
const { results } = await db
|
||||
.prepare(`SELECT id, name FROM routines WHERE account_id = ? AND id IN (${refs.map(() => '?').join(', ')})`)
|
||||
.bind(accountId, ...refs)
|
||||
.all<{ id: string; name: string }>()
|
||||
const byRoutine = new Map(results.map((r) => [r.id, r.name]))
|
||||
const out = new Map<string, string>()
|
||||
for (const row of rows) {
|
||||
const name = byRoutine.get((row as { origin_ref?: string | null }).origin_ref ?? '')
|
||||
if (name) {
|
||||
out.set(row.id, name)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const SECTION = z.string().trim().min(1).max(64).regex(/^[^\u0000-\u001f]+$/)
|
||||
@@ -322,6 +379,12 @@ export async function patchWorkspace(
|
||||
if (!next) {
|
||||
throw new WorkspaceError('not_found')
|
||||
}
|
||||
if (patch.tokenUsdMicros !== undefined) {
|
||||
// Dated per reporter for teammate profiles' heatmap; the label above is only a running total.
|
||||
await recordTokenSpend(db, row.account_id, caller.userId, row.token_usd_micros, patch.tokenUsdMicros, now).catch((error: unknown) =>
|
||||
console.warn('member_usage_write_failed', String(error))
|
||||
)
|
||||
}
|
||||
const ownerChanged = patch.ownerUserId !== undefined && patch.ownerUserId !== row.user_id
|
||||
const wentPrivate = row.visibility === 'team' && next.visibility === 'private'
|
||||
const archived = patch.archived === true && row.archived_at === null
|
||||
@@ -368,27 +431,56 @@ export async function reportPresence(
|
||||
return { presence: view!.presence }
|
||||
}
|
||||
|
||||
const LinkQuery = z.object({
|
||||
w: z.string().regex(/^sbx_[0-9a-f]{24}$/),
|
||||
c: z.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/).optional()
|
||||
})
|
||||
const ChatParam = z.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/).optional()
|
||||
const LinkQuery = z.union([
|
||||
z.object({ w: z.string().regex(/^sbx_[0-9a-f]{24}$/), c: ChatParam }),
|
||||
z.object({ org: z.string().min(1).max(40), n: z.coerce.number().int().min(1).max(1e9), c: ChatParam })
|
||||
])
|
||||
|
||||
/** orca://cloud/w/<id>[/c/<chat>] → the workspace if the caller can see it; otherwise not_found. */
|
||||
/** A slug link that names a different org than the caller's current one. */
|
||||
export class LinkOtherOrgError extends WorkspaceError {
|
||||
constructor(readonly orgId: string | null) {
|
||||
super('not_found', 'other_org')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* orca://cloud/w/<id>[/c/<chat>] or orca://cloud/<slug>/W-<n>[/c/<chat>] → the workspace if the caller
|
||||
* can see it; otherwise not_found. A slug link for another org answers not_found with reason
|
||||
* `other_org` and that org's id, so a client that belongs to it can offer to switch teams.
|
||||
*/
|
||||
export async function resolveLink(db: D1Database, caller: SandboxCaller, url: URL, now: number) {
|
||||
const query = LinkQuery.safeParse(Object.fromEntries(url.searchParams))
|
||||
if (!query.success) {
|
||||
throw new WorkspaceError('invalid_request')
|
||||
}
|
||||
const row = await getSandbox(db, query.data.w)
|
||||
const q = query.data
|
||||
let row: SandboxRow | null
|
||||
if ('w' in q) {
|
||||
row = await getSandbox(db, q.w)
|
||||
} else {
|
||||
const accountId = await accountForSlug(db, q.org)
|
||||
if (!accountId) {
|
||||
throw new WorkspaceError('not_found')
|
||||
}
|
||||
if (accountId !== caller.accountId) {
|
||||
throw new LinkOtherOrgError(orgIdOf(accountId))
|
||||
}
|
||||
row = await db
|
||||
.prepare('SELECT * FROM sandboxes WHERE account_id = ? AND number = ?')
|
||||
.bind(accountId, q.n)
|
||||
.first<SandboxRow>()
|
||||
}
|
||||
if (!row || !canSee(caller, row)) {
|
||||
// Private, other org, or gone: the link reveals nothing about which.
|
||||
throw new WorkspaceError('not_found')
|
||||
}
|
||||
const [view] = await workspaceViews(db, caller, [row], now)
|
||||
return { workspace: view, chatId: query.data.c ?? null }
|
||||
return { workspace: view, chatId: q.c ?? null }
|
||||
}
|
||||
|
||||
/** Canonical deep link for a workspace (and optionally a chat in it). */
|
||||
export function workspaceLink(id: string, chatId?: string): string {
|
||||
return `orca://cloud/w/${id}${chatId ? `/c/${encodeURIComponent(chatId)}` : ''}`
|
||||
export function workspaceLink(row: Pick<SandboxRow, 'id' | 'number'>, slug: string | null, chatId?: string): string {
|
||||
const chat = chatId ? `/c/${encodeURIComponent(chatId)}` : ''
|
||||
return slug && row.number ? `orca://cloud/${slug}/W-${row.number}${chat}` : `orca://cloud/w/${row.id}${chat}`
|
||||
}
|
||||
|
||||
@@ -334,3 +334,53 @@ describe('a provider 401 revokes only when confirmed', () => {
|
||||
expect(await auditRows()).toEqual([{ action: 'revoked', reason: 'provider_401_confirmed_by_check', upstream_path: '/v1/messages' }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /v1/agent-credentials/claude/verify (pre-launch check)', () => {
|
||||
it('a pass is remembered: the next calls answer without asking the provider', async () => {
|
||||
const { h, as, check } = await setup()
|
||||
const mia = await as('mia')
|
||||
await h.call('PUT', '/v1/agent-credentials/claude', { bearer: mia, body: { token: SETUP_TOKEN } })
|
||||
check.status = 200
|
||||
check.body = '{"input_tokens":3}'
|
||||
const first = await h.call('POST', '/v1/agent-credentials/claude/verify', { bearer: mia })
|
||||
expect(first.body).toMatchObject({ claude: { state: 'active' }, checked: true })
|
||||
expect(first.body.verifiedAt).toEqual(expect.any(Number))
|
||||
const again = await h.call('POST', '/v1/agent-credentials/claude/verify', { bearer: mia })
|
||||
expect(again.body).toMatchObject({ claude: { state: 'active' }, checked: false, verifiedAt: first.body.verifiedAt })
|
||||
expect(check.calls).toBe(1)
|
||||
})
|
||||
|
||||
it('a dead token is revoked (and audited); an inconclusive check keeps it', async () => {
|
||||
const dead = await setup()
|
||||
const mia = await dead.as('mia')
|
||||
await dead.h.call('PUT', '/v1/agent-credentials/claude', { bearer: mia, body: { token: SETUP_TOKEN } })
|
||||
const revoked = await dead.h.call('POST', '/v1/agent-credentials/claude/verify', { bearer: mia })
|
||||
expect(revoked.body).toMatchObject({ claude: { state: 'revoked' }, checked: true, verifiedAt: null })
|
||||
const rows = (await dead.h.env.SANDBOX_DB.prepare('SELECT action, reason FROM agent_credential_audit').all()).results
|
||||
expect(rows).toEqual([{ action: 'revoked', reason: 'verify_confirmed_auth_failure' }])
|
||||
|
||||
const flaky = await setup()
|
||||
const ada = await flaky.as('ada')
|
||||
await flaky.h.call('PUT', '/v1/agent-credentials/claude', { bearer: ada, body: { token: SETUP_TOKEN } })
|
||||
flaky.check.status = 529
|
||||
flaky.check.body = '{"type":"error","error":{"type":"overloaded_error"}}'
|
||||
const kept = await flaky.h.call('POST', '/v1/agent-credentials/claude/verify', { bearer: ada })
|
||||
expect(kept.body).toMatchObject({ claude: { state: 'active' }, checked: true, verifiedAt: null })
|
||||
// Rate limited: a second call within the minute doesn't ask again.
|
||||
await flaky.h.call('POST', '/v1/agent-credentials/claude/verify', { bearer: ada })
|
||||
expect(flaky.check.calls).toBe(1)
|
||||
})
|
||||
|
||||
it('storing a new token forgets the old verification', async () => {
|
||||
const { h, as, check } = await setup()
|
||||
const mia = await as('mia')
|
||||
await h.call('PUT', '/v1/agent-credentials/claude', { bearer: mia, body: { token: SETUP_TOKEN } })
|
||||
check.status = 200
|
||||
check.body = '{}'
|
||||
await h.call('POST', '/v1/agent-credentials/claude/verify', { bearer: mia })
|
||||
await h.call('PUT', '/v1/agent-credentials/claude', { bearer: mia, body: { token: SETUP_TOKEN } })
|
||||
const after = await h.call('POST', '/v1/agent-credentials/claude/verify', { bearer: mia })
|
||||
expect(after.body.checked).toBe(true)
|
||||
expect(check.calls).toBe(2)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
import { gunzipSync } from 'node:zlib'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { safeFilename } from '../src/api/attachments'
|
||||
import { tarGzipFile } from '../src/tar-gzip'
|
||||
import { createHarness } from './harness'
|
||||
|
||||
async function harness() {
|
||||
const pending: Promise<unknown>[] = []
|
||||
const h = await createHarness({ PUBLIC_API_URL: 'https://api.test' }, { waitUntil: (p) => void pending.push(p) })
|
||||
/** Answers the in-VM orca CLI: launches return `term_new`, other terminal commands succeed. */
|
||||
h.vercel.commandHandler = (params) => {
|
||||
const args = params.args ?? []
|
||||
if (args.includes('launch')) {
|
||||
return { exitCode: 0, stdout: JSON.stringify({ ok: true, result: { outcome: { kind: 'terminal', handle: 'term_new' } } }), stderr: '' }
|
||||
}
|
||||
if (args.includes('terminal')) {
|
||||
return { exitCode: 0, stdout: JSON.stringify({ ok: true, result: {} }), stderr: '' }
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
const orcaArgs = (verb: string) => h.vercel.commands.filter((c) => c.args?.includes(verb)).map((c) => c.args!.slice(c.args!.indexOf('orca') + 1))
|
||||
return { ...h, settle: () => Promise.all(pending.splice(0)), orcaArgs }
|
||||
}
|
||||
|
||||
async function upload(h: Awaited<ReturnType<typeof harness>>, wsId: string, init: { body: BodyInit; contentType: string; query?: string; as?: string }) {
|
||||
const bearer = await h.token(init.as ?? 'alice')
|
||||
const response = await h.send(
|
||||
new Request(`https://sandbox.test/v1/workspaces/${wsId}/attachments${init.query ?? ''}`, {
|
||||
method: 'POST',
|
||||
headers: { authorization: `Bearer ${bearer}`, 'content-type': init.contentType },
|
||||
body: init.body
|
||||
})
|
||||
)
|
||||
return { status: response.status, body: (await response.json()) as any }
|
||||
}
|
||||
|
||||
describe('public API: models', () => {
|
||||
it('lists every image agent with its catalog models, efforts and defaults', async () => {
|
||||
const h = await harness()
|
||||
const res = await h.call('GET', '/v1/models')
|
||||
expect(res.status).toBe(200)
|
||||
const agents = res.body.agents as { id: string; default: boolean; defaultModel: string | null; models: { id: string; efforts: string[]; fastMode: boolean }[] }[]
|
||||
expect(agents.map((a) => a.id)).toEqual(['claude', 'codex', 'opencode', 'gemini', 'cursor', 'copilot'])
|
||||
const claude = agents.find((a) => a.id === 'claude')!
|
||||
expect(claude.default).toBe(true)
|
||||
expect(claude.defaultModel).toBe('sonnet')
|
||||
expect(claude.models.find((m) => m.id === 'opus')).toMatchObject({ efforts: expect.arrayContaining(['high', 'max']), fastMode: true })
|
||||
expect(agents.find((a) => a.id === 'codex')!.models.find((m) => m.id === 'gpt-5.5')!.efforts).toContain('xhigh')
|
||||
// Agents without a seed catalog still appear: their CLI picks the model.
|
||||
expect(agents.find((a) => a.id === 'copilot')).toMatchObject({ models: [], defaultModel: null })
|
||||
})
|
||||
})
|
||||
|
||||
describe('public API: sessions', () => {
|
||||
it('starts a new session with model, effort, name and a first prompt, waking a sleeping workspace', async () => {
|
||||
const h = await harness()
|
||||
const ws = (await h.call('POST', '/v1/workspaces', { body: {} })).body.workspace
|
||||
await h.call('POST', `/v1/workspaces/${ws.id}/sleep`)
|
||||
const res = await h.call('POST', `/v1/workspaces/${ws.id}/sessions`, {
|
||||
body: { agent: 'codex', model: 'gpt-5.5', effort: 'high', name: 'Review', message: 'review the diff; $(rm -rf /)' }
|
||||
})
|
||||
expect(res.status).toBe(201)
|
||||
expect(res.body.session).toEqual({ handle: 'term_new', workspaceId: ws.id, agent: 'codex', model: 'gpt-5.5', effort: 'high', name: 'Review' })
|
||||
expect((await h.call('GET', `/v1/workspaces/${ws.id}`)).body.workspace.status).toBe('running')
|
||||
const [launch] = h.orcaArgs('launch')
|
||||
expect(launch).toEqual(expect.arrayContaining(['--agent', 'codex', '--model=gpt-5.5', '--effort=high', '--prompt=review the diff; $(rm -rf /)']))
|
||||
expect(h.orcaArgs('rename')[0]).toEqual(expect.arrayContaining(['--terminal', 'term_new', '--title=Review']))
|
||||
const actions = (await h.call('GET', '/v1/audit')).body.entries.map((e: { action: string }) => e.action)
|
||||
expect(actions[0]).toBe('workspace.session.create')
|
||||
})
|
||||
|
||||
it('starts an idle session without a prompt and rejects bad model picks', async () => {
|
||||
const h = await harness()
|
||||
const ws = (await h.call('POST', '/v1/workspaces', { body: {} })).body.workspace
|
||||
expect((await h.call('POST', `/v1/workspaces/${ws.id}/sessions`, { body: {} })).status).toBe(201)
|
||||
expect(h.orcaArgs('launch')[0]!.some((arg) => arg.startsWith('--prompt'))).toBe(false)
|
||||
const badEffort = await h.call('POST', `/v1/workspaces/${ws.id}/sessions`, { body: { agent: 'claude', model: 'haiku', effort: 'high' } })
|
||||
expect(badEffort).toMatchObject({ status: 400, body: { error: 'invalid_request', reason: 'effort: haiku takes no effort' } })
|
||||
expect((await h.call('POST', `/v1/workspaces/${ws.id}/sessions`, { body: { effort: 'high' } })).status).toBe(400)
|
||||
expect((await h.call('POST', `/v1/workspaces/${ws.id}/sessions`, { body: { model: 'x y' } })).status).toBe(400)
|
||||
// A model newer than the catalog is passed through to the agent CLI.
|
||||
expect((await h.call('POST', `/v1/workspaces/${ws.id}/sessions`, { body: { model: 'claude-fable-9', effort: 'max' } })).status).toBe(201)
|
||||
})
|
||||
|
||||
it('cancels a turn: drops the session\'s queued messages and interrupts with Escape', async () => {
|
||||
const h = await harness()
|
||||
const ws = (await h.call('POST', '/v1/workspaces', { body: {} })).body.workspace
|
||||
// Two messages still waiting for delivery (e.g. a retry backlog): one for this session, one not.
|
||||
const insert = h.raw.prepare(
|
||||
`INSERT INTO workspace_messages (id, sandbox_id, account_id, sent_by, agent, session_handle, body, status, created_at, updated_at) VALUES (?, ?, 'user:alice', 'alice', 'claude', ?, 'x', 'queued', 0, 0)`
|
||||
)
|
||||
insert.run('msg_q1', ws.id, 'term_abc')
|
||||
insert.run('msg_q2', ws.id, 'term_other')
|
||||
const res = await h.call('POST', `/v1/workspaces/${ws.id}/sessions/term_abc/cancel`)
|
||||
expect(res.body).toEqual({ workspaceId: ws.id, session: 'term_abc', interrupted: true, canceledQueuedMessages: 1 })
|
||||
expect((await h.call('GET', `/v1/workspaces/${ws.id}/messages/msg_q1`)).body.message).toMatchObject({ status: 'failed', error: 'canceled' })
|
||||
expect((await h.call('GET', `/v1/workspaces/${ws.id}/messages/msg_q2`)).body.message.status).toBe('queued')
|
||||
const send = h.orcaArgs('send').at(-1)!
|
||||
expect(send).toEqual(expect.arrayContaining(['--terminal', 'term_abc', '--text=\u001b']))
|
||||
expect(send).not.toContain('--enter')
|
||||
// Asleep: nothing to interrupt, and the VM is not woken for it.
|
||||
await h.call('POST', `/v1/workspaces/${ws.id}/sleep`)
|
||||
const asleep = await h.call('POST', `/v1/workspaces/${ws.id}/sessions/term_abc/cancel`)
|
||||
expect(asleep.body).toMatchObject({ interrupted: false, canceledQueuedMessages: 0 })
|
||||
expect((await h.call('GET', `/v1/workspaces/${ws.id}`)).body.workspace.status).toBe('sleeping')
|
||||
expect((await h.call('POST', `/v1/workspaces/${ws.id}/sessions/nope/cancel`)).status).toBe(404)
|
||||
})
|
||||
|
||||
it('renames a session while running and 409s while asleep', async () => {
|
||||
const h = await harness()
|
||||
const ws = (await h.call('POST', '/v1/workspaces', { body: {} })).body.workspace
|
||||
const res = await h.call('POST', `/v1/workspaces/${ws.id}/sessions/term_abc/rename`, { body: { name: 'Docs pass' } })
|
||||
expect(res.body.session).toEqual({ handle: 'term_abc', workspaceId: ws.id, name: 'Docs pass' })
|
||||
await h.call('POST', `/v1/workspaces/${ws.id}/sleep`)
|
||||
expect((await h.call('POST', `/v1/workspaces/${ws.id}/sessions/term_abc/rename`, { body: { name: 'x' } })).status).toBe(409)
|
||||
})
|
||||
|
||||
it('keeps teammates out of a private workspace\'s sessions', async () => {
|
||||
const h = await harness()
|
||||
const owner = await h.token('olive', 'acme', 'sandbox', { orgRole: 'owner' })
|
||||
const member = await h.token('mel', 'acme', 'sandbox', { orgRole: 'member' })
|
||||
const ws = (await h.call('POST', '/v1/workspaces', { bearer: owner, body: {} })).body.workspace
|
||||
expect((await h.call('POST', `/v1/workspaces/${ws.id}/sessions`, { bearer: member, body: {} })).status).toBe(404)
|
||||
expect((await h.call('POST', `/v1/workspaces/${ws.id}/sessions/term_abc/cancel`, { bearer: member })).status).toBe(404)
|
||||
expect((await h.call('POST', `/v1/workspaces/${ws.id}/rename`, { bearer: member, body: { name: 'x' } })).status).toBe(404)
|
||||
})
|
||||
})
|
||||
|
||||
describe('public API: rename and unarchive', () => {
|
||||
it('renames a workspace everywhere it is listed', async () => {
|
||||
const h = await harness()
|
||||
const ws = (await h.call('POST', '/v1/workspaces', { body: { name: 'old' } })).body.workspace
|
||||
const res = await h.call('POST', `/v1/workspaces/${ws.id}/rename`, { body: { name: ' New name ' } })
|
||||
expect(res.body.workspace.name).toBe('New name')
|
||||
expect((await h.call('GET', `/v1/workspaces/${ws.id}`)).body.workspace.name).toBe('New name')
|
||||
expect((await h.call('GET', '/v1/team/workspaces')).body.workspaces[0].title).toBe('New name')
|
||||
expect((await h.call('POST', `/v1/workspaces/${ws.id}/rename`, { body: { name: '' } })).status).toBe(400)
|
||||
})
|
||||
|
||||
it('unarchives back into lists and running, idempotently', async () => {
|
||||
const h = await harness()
|
||||
const ws = (await h.call('POST', '/v1/workspaces', { body: {} })).body.workspace
|
||||
await h.call('POST', `/v1/workspaces/${ws.id}/archive`)
|
||||
expect((await h.call('GET', '/v1/workspaces')).body.workspaces).toHaveLength(0)
|
||||
const res = await h.call('POST', `/v1/workspaces/${ws.id}/unarchive`)
|
||||
expect(res.body.workspace).toMatchObject({ status: 'running', archived: false })
|
||||
expect((await h.call('GET', '/v1/workspaces')).body.workspaces).toHaveLength(1)
|
||||
const again = await h.call('POST', `/v1/workspaces/${ws.id}/unarchive`)
|
||||
expect(again).toMatchObject({ status: 200, body: { workspace: { status: 'running', archived: false } } })
|
||||
const actions = (await h.call('GET', '/v1/audit')).body.entries.map((e: { action: string }) => e.action)
|
||||
expect(actions.filter((a: string) => a === 'workspace.unarchive')).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('public API: attachments', () => {
|
||||
it('writes raw and base64 uploads to the workspace disk and points the agent at them', async () => {
|
||||
const h = await harness()
|
||||
const ws = (await h.call('POST', '/v1/workspaces', { body: {} })).body.workspace
|
||||
const raw = await upload(h, ws.id, { body: new Uint8Array([0x89, 0x50, 0x4e, 0x47]), contentType: 'image/png', query: '?filename=../../etc/Screen%20Shot%201.png' })
|
||||
expect(raw.status).toBe(201)
|
||||
const att = raw.body.attachment
|
||||
expect(att).toMatchObject({ workspaceId: ws.id, filename: 'Screen Shot 1.png', contentType: 'image/png', byteSize: 4 })
|
||||
expect(att.path).toBe(`/vercel/sandbox/attachments/${att.id}/Screen Shot 1.png`)
|
||||
const box = [...h.vercel.boxes.values()][0]!
|
||||
expect(Buffer.from(box.files.get(att.path)!, 'latin1')).toEqual(Buffer.from([0x89, 0x50, 0x4e, 0x47]))
|
||||
|
||||
const json = await upload(h, ws.id, { body: JSON.stringify({ filename: 'log.txt', contentType: 'text/plain', data: Buffer.from('boom').toString('base64') }), contentType: 'application/json' })
|
||||
expect(json.body.attachment).toMatchObject({ filename: 'log.txt', byteSize: 4 })
|
||||
|
||||
const sent = await h.call('POST', `/v1/workspaces/${ws.id}/messages`, { body: { text: 'see files', attachments: [att.id, json.body.attachment.id] } })
|
||||
expect(sent.status).toBe(202)
|
||||
await h.settle()
|
||||
const prompt = h.orcaArgs('launch')[0]!.at(-1)!
|
||||
expect(prompt).toContain('see files\n\nAttached files (read them from disk):')
|
||||
expect(prompt).toContain(`- ${att.path} (image/png, 4 bytes)`)
|
||||
expect(prompt).toContain(`- ${json.body.attachment.path} (text/plain, 4 bytes)`)
|
||||
})
|
||||
|
||||
it('rejects unknown, foreign and oversized attachments', async () => {
|
||||
const h = await harness()
|
||||
const a = (await h.call('POST', '/v1/workspaces', { body: {} })).body.workspace
|
||||
const b = (await h.call('POST', '/v1/workspaces', { body: {} })).body.workspace
|
||||
const att = (await upload(h, b.id, { body: 'x', contentType: 'text/plain', query: '?filename=x.txt' })).body.attachment
|
||||
const foreign = await h.call('POST', `/v1/workspaces/${a.id}/messages`, { body: { text: 'hi', attachments: [att.id] } })
|
||||
expect(foreign).toMatchObject({ status: 400, body: { error: 'invalid_request' } })
|
||||
expect((await h.call('POST', `/v1/workspaces/${a.id}/messages`, { body: { text: 'hi', attachments: ['att_nope'] } })).status).toBe(400)
|
||||
expect((await upload(h, a.id, { body: 'x', contentType: 'text/plain' })).status).toBe(400)
|
||||
const big = await upload(h, a.id, { body: JSON.stringify({ filename: 'big.bin', data: Buffer.alloc(5 * 1024 * 1024 + 1).toString('base64') }), contentType: 'application/json' })
|
||||
expect(big.status).toBe(413)
|
||||
// Another account cannot upload into it.
|
||||
expect((await upload(h, a.id, { body: 'x', contentType: 'text/plain', query: '?filename=x', as: 'mallory' })).status).toBe(404)
|
||||
// Attachments need a message on session create.
|
||||
expect((await h.call('POST', `/v1/workspaces/${b.id}/sessions`, { body: { attachments: [att.id] } })).status).toBe(400)
|
||||
})
|
||||
|
||||
it('keeps file names to one safe path segment', () => {
|
||||
expect(safeFilename('../../.ssh/id_rsa')).toBe('id_rsa')
|
||||
expect(safeFilename('.env')).toBe('env')
|
||||
expect(safeFilename('résumé $(x).pdf')).toBe('resume __x_.pdf')
|
||||
expect(safeFilename('')).toBe('file')
|
||||
expect(safeFilename(`${'a'.repeat(300)}.png`)).toMatch(/^a{80}\.png$/)
|
||||
})
|
||||
|
||||
it('packs a valid ustar archive the files API can extract', async () => {
|
||||
const bytes = new TextEncoder().encode('hello')
|
||||
const tgz = new Uint8Array(await tarGzipFile({ dirs: ['vercel', 'vercel/sandbox'], path: 'vercel/sandbox/a.txt', bytes, mtime: 1_700_000_000_000 }))
|
||||
const tar = gunzipSync(tgz)
|
||||
expect(tar.length % 512).toBe(0)
|
||||
const field = (block: number, offset: number, width: number) => tar.subarray(block * 512 + offset, block * 512 + offset + width).toString('latin1').replace(/\0.*$/s, '')
|
||||
expect([field(0, 0, 100), field(0, 156, 1), field(1, 0, 100), field(2, 0, 100), field(2, 156, 1)]).toEqual(['vercel/', '5', 'vercel/sandbox/', 'vercel/sandbox/a.txt', '0'])
|
||||
expect(parseInt(field(2, 124, 12), 8)).toBe(5)
|
||||
expect(field(2, 257, 6)).toBe('ustar')
|
||||
for (const block of [0, 1, 2]) {
|
||||
const header = Buffer.from(tar.subarray(block * 512, block * 512 + 512))
|
||||
const stored = parseInt(field(block, 148, 8), 8)
|
||||
header.fill(0x20, 148, 156)
|
||||
expect(header.reduce((sum, b) => sum + b, 0)).toBe(stored)
|
||||
}
|
||||
expect(tar.subarray(3 * 512, 3 * 512 + 5).toString()).toBe('hello')
|
||||
await expect(tarGzipFile({ dirs: [], path: '../x', bytes, mtime: 0 })).rejects.toThrow('tar_bad_path')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,141 @@
|
||||
// Automatic environments: the first create of a repo builds it in the background; later creates boot
|
||||
// with the repo checked out and only fetch what changed.
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { HostedSandboxReadyResponseSchema } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire'
|
||||
import { AUTO_ENVIRONMENT_UNUSED_MS, expireAutoEnvironments } from '../src/auto-environments'
|
||||
import { START_COMMAND } from '../src/sandbox-vm-commands'
|
||||
import { GOLDEN, createHarness } from './harness'
|
||||
|
||||
const REPO = 'https://github.com/acme/web.git'
|
||||
const RESULT = JSON.stringify({
|
||||
durationSec: 3,
|
||||
repos: [{ url: REPO, dir: 'acme/web', branch: 'main', commit: 'a'.repeat(40), lockfiles: {} }],
|
||||
diskUsedBytes: 3_000_000_000,
|
||||
diskTotalBytes: 34_000_000_000
|
||||
})
|
||||
const FEATURES = { 'x-orca-sandbox-features': 'clone-progress,repo-update' }
|
||||
|
||||
async function setup() {
|
||||
const pending: Promise<unknown>[] = []
|
||||
const h = await createHarness({ AUTO_ENVIRONMENTS: 'on' }, { waitUntil: (work: Promise<unknown>) => void pending.push(work) })
|
||||
h.vercel.buildResult = RESULT
|
||||
const settle = async () => {
|
||||
while (pending.length > 0) {
|
||||
await Promise.all(pending.splice(0))
|
||||
}
|
||||
}
|
||||
const environments = () =>
|
||||
h.raw.prepare('SELECT id, account_id, kind, name, active_build_id, deleted_at, last_used_at FROM environments').all() as {
|
||||
id: string
|
||||
account_id: string
|
||||
kind: string
|
||||
name: string
|
||||
active_build_id: string | null
|
||||
deleted_at: number | null
|
||||
last_used_at: number | null
|
||||
}[]
|
||||
/** Lets the auto build's VM command succeed and finalizes it. */
|
||||
async function finishBuild(as = 'alice') {
|
||||
const env = environments().find((row) => row.deleted_at === null && !row.active_build_id)!
|
||||
const build = h.raw.prepare('SELECT id FROM environment_builds WHERE environment_id = ? ORDER BY number DESC').get(env.id) as { id: string }
|
||||
const command = [...h.vercel.buildCommands.values()].at(-1)!
|
||||
command.logs = `${JSON.stringify({ data: '::orca-step:: clone\n', stream: 'stdout' })}\n`
|
||||
command.exitCode = 0
|
||||
h.advance(1000)
|
||||
const done = await h.call('GET', `/v1/environments/${env.id}/builds/${build.id}`, { as })
|
||||
expect(done.body.build.status).toBe('succeeded')
|
||||
return { env, buildId: build.id }
|
||||
}
|
||||
return { h, settle, environments, finishBuild }
|
||||
}
|
||||
|
||||
describe('automatic environments', () => {
|
||||
it('the first create of a repo builds it (blobless); the next boots with it checked out and fetches only changes', async () => {
|
||||
const { h, settle, environments, finishBuild } = await setup()
|
||||
const first = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'w1', machineSize: 'standard', repo: { url: REPO } }, headers: FEATURES })
|
||||
expect(first.body.clone).toEqual({ state: 'running' })
|
||||
await settle()
|
||||
expect(environments()).toMatchObject([{ kind: 'auto', name: 'acme/web', active_build_id: null }])
|
||||
const command = [...h.vercel.buildCommands.values()].at(-1)!
|
||||
expect(command.env.ORCA_CLONE_FILTER).toBe('blob:none')
|
||||
const { buildId } = await finishBuild()
|
||||
|
||||
h.vercel.commands.length = 0
|
||||
const second = await h.call('POST', '/v1/sandboxes', {
|
||||
body: { workspaceId: 'w2', machineSize: 'standard', repo: { url: REPO, ref: 'feature' } },
|
||||
headers: FEATURES
|
||||
})
|
||||
expect(second.status).toBe(200)
|
||||
expect(second.body.sandbox.environmentBuildId).toBe(buildId)
|
||||
expect(second.body.clone).toEqual({ state: 'running', mode: 'update' })
|
||||
expect(HostedSandboxReadyResponseSchema.safeParse({ ...second.body, clone: { state: 'running' } }).success).toBe(true)
|
||||
const start = h.vercel.commands.find((c) => c.command === START_COMMAND)!
|
||||
expect(start.env).toMatchObject({ ORCA_ENV_REPO_DIR: 'acme/web', ORCA_CLONE_BACKGROUND: '1' })
|
||||
const box = [...h.vercel.boxes.values()].find((b) => b.params.tags.orcaSandbox === second.body.sandbox.id)!
|
||||
expect(box.params.snapshotId).not.toBe(GOLDEN)
|
||||
await settle()
|
||||
expect(environments()[0]!.last_used_at).toBe(h.now())
|
||||
// A desktop without `repo-update` sees the plain clone shape it knows.
|
||||
const older = await h.call('POST', '/v1/sandboxes', {
|
||||
body: { workspaceId: 'w3', machineSize: 'standard', repo: { url: REPO } },
|
||||
headers: { 'x-orca-sandbox-features': 'clone-progress' }
|
||||
})
|
||||
expect(older.body.clone).toEqual({ state: 'running' })
|
||||
})
|
||||
|
||||
it('is per account, never shadows an admin environment, and makes one environment per repo', async () => {
|
||||
const { h, settle, environments } = await setup()
|
||||
await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'a1', machineSize: 'standard', repo: { url: REPO } } })
|
||||
await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'a2', machineSize: 'standard', repo: { url: 'acme/web' } } })
|
||||
await settle()
|
||||
const bob = await h.call('POST', '/v1/sandboxes', { as: 'bob', body: { workspaceId: 'b1', machineSize: 'standard', repo: { url: REPO } } })
|
||||
await settle()
|
||||
expect(bob.body.sandbox.environmentBuildId).toBeUndefined()
|
||||
const rows = environments()
|
||||
expect(rows).toHaveLength(2)
|
||||
expect(new Set(rows.map((row) => row.account_id)).size).toBe(2)
|
||||
|
||||
// An org whose admin lists the repo: no automatic one next to it.
|
||||
const admin = await h.token('carol', 'acme', 'sandbox', { orgRole: 'admin' })
|
||||
expect(
|
||||
(await h.call('POST', '/v1/environments', { bearer: admin, body: { name: 'Web', repos: [{ url: 'acme/web' }], installScript: '' } })).status
|
||||
).toBe(200)
|
||||
await h.call('POST', '/v1/sandboxes', { bearer: admin, body: { workspaceId: 'c1', machineSize: 'standard', repo: { url: REPO } } })
|
||||
await settle()
|
||||
expect(environments().filter((row) => row.kind === 'auto')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('boot-plan says clone before the environment exists and update after (PC-4)', async () => {
|
||||
const { h, settle, finishBuild } = await setup()
|
||||
const plan = async () => (await h.call('GET', `/v1/sandboxes/boot-plan?repo=${encodeURIComponent(REPO)}`)).body
|
||||
expect(await plan()).toEqual({ repo: 'clone' })
|
||||
await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'w1', machineSize: 'standard', repo: { url: REPO } } })
|
||||
await settle()
|
||||
expect(await plan()).toEqual({ repo: 'clone' })
|
||||
await finishBuild()
|
||||
expect(await plan()).toEqual({ repo: 'update' })
|
||||
// Another account's environment is never theirs to boot.
|
||||
expect((await h.call('GET', `/v1/sandboxes/boot-plan?repo=${encodeURIComponent(REPO)}`, { as: 'bob' })).body).toEqual({
|
||||
repo: 'clone'
|
||||
})
|
||||
})
|
||||
|
||||
it('goes after 14 days unused, with its snapshot', async () => {
|
||||
const { h, settle, environments, finishBuild } = await setup()
|
||||
await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'w1', machineSize: 'standard', repo: { url: REPO } } })
|
||||
await settle()
|
||||
const { buildId } = await finishBuild()
|
||||
const snapshotId = (h.raw.prepare('SELECT snapshot_id FROM environment_builds WHERE id = ?').get(buildId) as { snapshot_id: string }).snapshot_id
|
||||
h.advance(AUTO_ENVIRONMENT_UNUSED_MS + 60_000)
|
||||
const deps = {
|
||||
db: h.env.SANDBOX_DB,
|
||||
provider: h.vercel,
|
||||
entitlements: { checkStart: async () => h.billing.decision, reportUsage: async () => h.billing.usageAnswer, listSuspensions: async () => [] },
|
||||
now: h.now,
|
||||
config: { environment: 'test', goldenSnapshotId: GOLDEN, region: 'iad1' }
|
||||
}
|
||||
expect(await expireAutoEnvironments(deps as never)).toBe(1)
|
||||
expect(environments()[0]!.deleted_at).not.toBeNull()
|
||||
expect(h.vercel.snapshots.get(snapshotId)?.status).not.toBe('created')
|
||||
})
|
||||
})
|
||||
@@ -137,6 +137,28 @@ describe('repo-backed create', () => {
|
||||
expect(h.billing.requests[0]).toMatchObject({ runningSandboxes: 3, runningSandboxesForUser: 3 })
|
||||
})
|
||||
|
||||
it('an Idempotency-Key makes one sandbox per intent, for that account and member only (PC-8)', async () => {
|
||||
const h = await createHarness()
|
||||
const key = { 'idempotency-key': 'create-press-0001' }
|
||||
const first = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'w-a', machineSize: 'standard' }, headers: key })
|
||||
expect(first.status).toBe(200)
|
||||
// A re-fired start of the same press (same key, same body): the same sandbox, nothing new.
|
||||
const again = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'w-a', machineSize: 'standard' }, headers: key })
|
||||
expect(again.status).toBe(200)
|
||||
expect(again.body.sandbox.id).toBe(first.body.sandbox.id)
|
||||
expect(h.vercel.boxes.size).toBe(1)
|
||||
// Same key, different request: refused, not silently merged.
|
||||
const other = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'w-b', machineSize: 'standard' }, headers: key })
|
||||
expect(other.status).toBe(422)
|
||||
// Keys are per member: someone else's press with the same key is their own create.
|
||||
const bob = await h.call('POST', '/v1/sandboxes', { as: 'bob', body: { workspaceId: 'w-a', machineSize: 'standard' }, headers: key })
|
||||
expect(bob.status).toBe(200)
|
||||
expect(bob.body.sandbox.id).not.toBe(first.body.sandbox.id)
|
||||
// A bad key is a 400, before anything starts.
|
||||
const bad = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'w-c', machineSize: 'standard' }, headers: { 'idempotency-key': 'x' } })
|
||||
expect(bad.status).toBe(400)
|
||||
})
|
||||
|
||||
it('a create whose Worker was cut off is failed after 5 minutes, not 15', async () => {
|
||||
const h = await createHarness()
|
||||
const { body } = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-1', machineSize: 'standard' } })
|
||||
@@ -153,3 +175,18 @@ describe('repo-backed create', () => {
|
||||
expect(h.vercel.boxes.size).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('VM hostname (JA-27)', () => {
|
||||
it('is the workspace name (else the repo), as a hostname label, set at every start', async () => {
|
||||
const { workspaceHostname } = await import('../src/sandbox-vm-commands')
|
||||
expect(workspaceHostname('Fix Login Bug!')).toBe('fix-login-bug')
|
||||
expect(workspaceHostname('--ja_hello--')).toBe('ja-hello')
|
||||
expect(workspaceHostname('🙂')).toBeUndefined()
|
||||
expect(workspaceHostname('a'.repeat(80))).toHaveLength(63)
|
||||
const h = await createHarness()
|
||||
await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'w1', machineSize: 'standard', title: 'Ja Hello', repo } })
|
||||
const start = h.vercel.commands.find((c) => c.command === START_COMMAND)!
|
||||
expect(start.env.ORCA_HOSTNAME).toBe('ja-hello')
|
||||
expect(start.args?.[1]).toContain('sudo -n hostname "$ORCA_HOSTNAME"')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -369,6 +369,13 @@ export function createFakeVercel(now: () => number): FakeVercel {
|
||||
async readFile(sessionId, path) {
|
||||
return bySession(sessionId).files.get(path) ?? null
|
||||
},
|
||||
async writeFile(sessionId, path, bytes) {
|
||||
const box = bySession(sessionId)
|
||||
if (box.status !== 'running') {
|
||||
throw new ProviderError(410, 'sandbox_stopped')
|
||||
}
|
||||
box.files.set(path, Buffer.from(bytes).toString('latin1'))
|
||||
},
|
||||
async deleteSandbox(name) {
|
||||
const box = boxes.get(name)
|
||||
if (box?.status === 'running') {
|
||||
|
||||
@@ -50,6 +50,8 @@ export async function createHarness(overrides: Partial<Env> = {}, extraDeps: Par
|
||||
GOLDEN_SNAPSHOT_ID: GOLDEN,
|
||||
VERCEL_TEAM_ID: 'team_orca',
|
||||
VERCEL_PROJECT_ID: 'prj_orca',
|
||||
// Off unless a test turns it on (auto-environments.test.ts): it starts builds behind creates.
|
||||
AUTO_ENVIRONMENTS: 'off',
|
||||
...overrides
|
||||
}
|
||||
// No live github.com from tests: repos count as public unless a test says otherwise.
|
||||
|
||||
@@ -130,9 +130,13 @@ describe('MCP protocol', () => {
|
||||
const list = await h.rpc(key, 'tools/list', {}, { 'mcp-protocol-version': '2025-11-25' })
|
||||
const tools = list.body.result.tools as { name: string; inputSchema: any; annotations: any; description: string }[]
|
||||
expect(tools.map((t) => t.name)).toEqual([
|
||||
'whoami', 'list_projects', 'list_workspaces', 'get_workspace', 'create_workspace', 'sleep_workspace', 'wake_workspace',
|
||||
'archive_workspace', 'destroy_workspace', 'send_message', 'get_message', 'list_sessions', 'read_session', 'list_routines', 'run_routine'
|
||||
'whoami', 'list_models', 'list_projects', 'list_workspaces', 'get_workspace', 'create_workspace', 'rename_workspace',
|
||||
'sleep_workspace', 'wake_workspace', 'archive_workspace', 'unarchive_workspace', 'destroy_workspace', 'create_session',
|
||||
'cancel_session', 'rename_session', 'upload_attachment', 'send_message', 'get_message', 'list_sessions', 'read_session',
|
||||
'list_routines', 'run_routine'
|
||||
])
|
||||
// Conductor's 20 tools minus run_sql (transcripts are end-to-end encrypted on the VM), plus Orca's own.
|
||||
expect(tools).toHaveLength(22)
|
||||
for (const t of tools) {
|
||||
expect(t.inputSchema.type).toBe('object')
|
||||
expect(t.description.length).toBeGreaterThan(40)
|
||||
@@ -144,6 +148,38 @@ describe('MCP protocol', () => {
|
||||
expect(byName.send_message!.inputSchema.required).toEqual(['workspaceId', 'text'])
|
||||
})
|
||||
|
||||
it('starts, renames and cancels sessions, uploads files and lists models through the new tools', async () => {
|
||||
const h = await harness()
|
||||
const key = await h.apiKey(['workspaces:read', 'workspaces:write', 'messages:write'])
|
||||
h.vercel.commandHandler = (params) => {
|
||||
const args = params.args ?? []
|
||||
if (args.includes('launch')) {
|
||||
return { exitCode: 0, stdout: JSON.stringify({ ok: true, result: { outcome: { kind: 'terminal', handle: 'term_mcp1' } } }), stderr: '' }
|
||||
}
|
||||
if (args.includes('terminal')) {
|
||||
return { exitCode: 0, stdout: JSON.stringify({ ok: true, result: {} }), stderr: '' }
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
const models = (await h.tool(key, 'list_models')).structuredContent.agents
|
||||
expect(models.map((a: { id: string }) => a.id)).toContain('codex')
|
||||
const ws = (await h.tool(key, 'create_workspace', { name: 'm' })).structuredContent.workspace
|
||||
expect((await h.tool(key, 'rename_workspace', { workspaceId: ws.id, name: 'renamed' })).structuredContent.workspace.name).toBe('renamed')
|
||||
const file = await h.tool(key, 'upload_attachment', { workspaceId: ws.id, filename: 'shot.png', contentType: 'image/png', data: Buffer.from('PNGDATA').toString('base64') })
|
||||
expect(file.isError).toBeUndefined()
|
||||
const attachment = file.structuredContent.attachment
|
||||
expect(attachment).toMatchObject({ filename: 'shot.png', byteSize: 7, contentType: 'image/png' })
|
||||
const session = await h.tool(key, 'create_session', { workspaceId: ws.id, agent: 'codex', model: 'gpt-5.5', effort: 'high', name: 'Second', message: 'look', attachments: [attachment.id] })
|
||||
expect(session.structuredContent.session).toMatchObject({ handle: 'term_mcp1', agent: 'codex', model: 'gpt-5.5', name: 'Second' })
|
||||
const launch = h.vercel.commands.find((c) => c.args?.includes('launch'))!
|
||||
expect(launch.args).toContain('--model=gpt-5.5')
|
||||
expect(launch.args!.at(-1)).toContain(attachment.path)
|
||||
expect((await h.tool(key, 'rename_session', { workspaceId: ws.id, session: 'term_mcp1', name: 'Third' })).structuredContent.session.name).toBe('Third')
|
||||
expect((await h.tool(key, 'cancel_session', { workspaceId: ws.id, session: 'term_mcp1' })).structuredContent).toMatchObject({ interrupted: true, canceledQueuedMessages: 0 })
|
||||
await h.tool(key, 'archive_workspace', { workspaceId: ws.id })
|
||||
expect((await h.tool(key, 'unarchive_workspace', { workspaceId: ws.id })).structuredContent.workspace).toMatchObject({ status: 'running', archived: false })
|
||||
})
|
||||
|
||||
it('rejects bad transport input: method, origin, version header, JSON, unknown method/tool', async () => {
|
||||
const h = await harness()
|
||||
const key = await h.apiKey(['workspaces:read'])
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { usageLevel } from '../src/team-presence'
|
||||
import { createHarness } from './harness'
|
||||
|
||||
const MIN = 60_000
|
||||
const HOUR = 60 * MIN
|
||||
const DAY = 24 * HOUR
|
||||
|
||||
async function team() {
|
||||
const h = await createHarness({ OPERATOR_TOKEN: 'o'.repeat(40) })
|
||||
type Who = { sub: string; orgRole: 'owner' | 'admin' | 'member'; org?: string; name?: string }
|
||||
const req = async (who: Who, method: string, path: string, body?: unknown) =>
|
||||
h.call(method, path, {
|
||||
bearer: await h.token(who.sub, who.org === undefined ? 'acme' : who.org || undefined, 'sandbox', {
|
||||
org_role: who.orgRole,
|
||||
...(who.name ? { name: who.name } : {})
|
||||
}),
|
||||
body
|
||||
})
|
||||
const alice: Who = { sub: 'alice', orgRole: 'member', name: 'Alice Doe' }
|
||||
const bob: Who = { sub: 'bob', orgRole: 'member', name: 'Bob Roe' }
|
||||
return { h, req, alice, bob }
|
||||
}
|
||||
|
||||
describe('teammate profiles', () => {
|
||||
it('shows a teammate only their team workspaces and a 0–4 heatmap, never amounts', async () => {
|
||||
const t = await team()
|
||||
const shared = await t.req(t.alice, 'POST', '/v1/sandboxes', { workspaceId: 'ws-1', machineSize: 'standard', title: 'Shared' })
|
||||
const secret = await t.req(t.alice, 'POST', '/v1/sandboxes', { workspaceId: 'ws-2', machineSize: 'standard', title: 'Secret' })
|
||||
expect(shared.status).toBe(200)
|
||||
const sharedId = shared.body.sandbox.id as string
|
||||
const secretId = secret.body.sandbox.id as string
|
||||
await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${sharedId}`, { visibility: 'team' })
|
||||
const now = t.h.now()
|
||||
// Two hours of sandbox time yesterday on the private one, half an hour today on the shared one.
|
||||
const outbox = t.h.raw.prepare(
|
||||
`INSERT INTO usage_outbox (usage_id, sandbox_id, account_id, machine_size, started_at, ended_at) VALUES (?, ?, ?, 'standard', ?, ?)`
|
||||
)
|
||||
const accountId = (t.h.raw.prepare('SELECT account_id FROM sandboxes WHERE id = ?').get(sharedId) as { account_id: string }).account_id
|
||||
outbox.run('u1', secretId, accountId, now - DAY - 2 * HOUR, now - DAY)
|
||||
outbox.run('u2', sharedId, accountId, now - 30 * MIN, now)
|
||||
|
||||
// Not shared until Alice turns on "Pokes and activity"; workspaces she shared still show.
|
||||
const hidden = (await t.req(t.bob, 'GET', '/v1/team/members/alice/profile?utcOffsetMin=0')).body.profile
|
||||
expect(hidden).toMatchObject({ usage: null, pokes: { enabled: false, teammateEnabled: false } })
|
||||
expect(hidden.recentWorkspaces).toHaveLength(1)
|
||||
await t.req(t.alice, 'PUT', '/v1/team/pokes/settings', { enabled: true })
|
||||
|
||||
const seen = await t.req(t.bob, 'GET', '/v1/team/members/alice/profile?utcOffsetMin=0')
|
||||
expect(seen.status).toBe(200)
|
||||
const profile = seen.body.profile
|
||||
expect(profile).toMatchObject({ userId: 'alice', self: false, name: 'Alice Doe', pokes: { enabled: false, teammateEnabled: true } })
|
||||
expect(profile.recentWorkspaces.map((w: { id: string }) => w.id)).toEqual([sharedId])
|
||||
expect(profile.usage.own).toBeNull()
|
||||
expect(profile.usage.levels).toHaveLength(182)
|
||||
expect(profile.usage.activeDays).toBe(2)
|
||||
// Relative to her own busiest day: yesterday is the max (4), today a quarter of it (1).
|
||||
expect(profile.usage.levels.slice(-2)).toEqual([4, 1])
|
||||
expect(JSON.stringify(profile.usage)).not.toMatch(/usdMicros|computeMs/)
|
||||
|
||||
const own = await t.req(t.alice, 'GET', '/v1/team/members/alice/profile?utcOffsetMin=0')
|
||||
expect(own.body.profile.self).toBe(true)
|
||||
expect(own.body.profile.recentWorkspaces).toHaveLength(2)
|
||||
expect(own.body.profile.usage.own.computeMs.slice(-2)).toEqual([2 * HOUR, 30 * MIN])
|
||||
expect(own.body.profile.usage.own.usdMicros.at(-1)).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('splits a session across local midnight and dates reported model spend', async () => {
|
||||
const t = await team()
|
||||
const created = await t.req(t.alice, 'POST', '/v1/sandboxes', { workspaceId: 'ws-1', machineSize: 'standard' })
|
||||
const id = created.body.sandbox.id as string
|
||||
const now = t.h.now()
|
||||
const accountId = (t.h.raw.prepare('SELECT account_id FROM sandboxes WHERE id = ?').get(id) as { account_id: string }).account_id
|
||||
const midnight = Math.floor(now / DAY) * DAY
|
||||
t.h.raw
|
||||
.prepare(`INSERT INTO usage_outbox (usage_id, sandbox_id, account_id, machine_size, started_at, ended_at) VALUES ('u1', ?, ?, 'standard', ?, ?)`)
|
||||
.run(id, accountId, midnight - HOUR, midnight + HOUR)
|
||||
expect((await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${id}`, { tokenUsdMicros: 500_000 })).status).toBe(200)
|
||||
expect((await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${id}`, { tokenUsdMicros: 400_000 })).status).toBe(200)
|
||||
expect((await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${id}`, { tokenUsdMicros: 700_000 })).status).toBe(200)
|
||||
const own = (await t.req(t.alice, 'GET', '/v1/team/members/alice/profile?utcOffsetMin=0')).body.profile.usage.own
|
||||
const today = own.computeMs.length - 1
|
||||
const tokenAndCompute = own.usdMicros[today]
|
||||
expect(own.computeMs[today - 1]).toBe(HOUR)
|
||||
// Only increases count: 500k, then nothing for the drop to 400k, then 300k more.
|
||||
expect(tokenAndCompute - own.usdMicros[today - 1]).toBe(500_000 + 300_000)
|
||||
})
|
||||
|
||||
it('shares every teammate\'s activity when the account config says team', async () => {
|
||||
const h = await createHarness({ TEAMMATE_ACTIVITY_SHARING: 'team' })
|
||||
const bob = await h.token('bob', 'acme', 'sandbox', { org_role: 'member' })
|
||||
const seen = await h.call('GET', '/v1/team/members/alice/profile', { bearer: bob })
|
||||
expect(seen.body.profile.usage.levels).toHaveLength(182)
|
||||
expect(seen.body.profile.usage.own).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps personal accounts to themselves and rejects bad ids', async () => {
|
||||
const t = await team()
|
||||
const solo = { sub: 'solo', orgRole: 'owner' as const, org: '' }
|
||||
expect((await t.req(solo, 'GET', '/v1/team/members/alice/profile')).status).toBe(404)
|
||||
expect((await t.req(solo, 'GET', '/v1/team/members/solo/profile')).status).toBe(200)
|
||||
expect((await t.req(t.bob, 'GET', '/v1/team/members/a%20b/profile')).status).toBe(400)
|
||||
const stranger = { sub: 'eve', orgRole: 'owner' as const, org: 'other' }
|
||||
expect((await t.req(stranger, 'GET', '/v1/team/members/alice/profile')).body.profile.recentWorkspaces).toEqual([])
|
||||
})
|
||||
|
||||
it('levels are relative to the busiest day', () => {
|
||||
expect([0, 1, 25, 26, 50, 100].map((v) => usageLevel(v, 100))).toEqual([0, 1, 1, 2, 2, 4])
|
||||
expect(usageLevel(5, 0)).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('pokes', () => {
|
||||
it('needs both people opted in, then delivers, rate-limits and acks', async () => {
|
||||
const t = await team()
|
||||
expect(await t.req(t.alice, 'POST', '/v1/team/members/bob/poke')).toMatchObject({ status: 409, body: { reason: 'pokes_off' } })
|
||||
expect((await t.req(t.alice, 'PUT', '/v1/team/pokes/settings', { enabled: true })).body).toEqual({ enabled: true })
|
||||
expect(await t.req(t.alice, 'POST', '/v1/team/members/bob/poke')).toMatchObject({ status: 409, body: { reason: 'teammate_pokes_off' } })
|
||||
const before = (await t.req(t.alice, 'GET', '/v1/team/members/bob/profile')).body.profile.pokes
|
||||
expect(before).toEqual({ enabled: true, teammateEnabled: false })
|
||||
await t.req(t.bob, 'PUT', '/v1/team/pokes/settings', { enabled: true })
|
||||
expect((await t.req(t.alice, 'GET', '/v1/team/members/bob/profile')).body.profile.pokes.teammateEnabled).toBe(true)
|
||||
|
||||
const sent = await t.req(t.alice, 'POST', '/v1/team/members/bob/poke')
|
||||
expect(sent.status).toBe(200)
|
||||
const again = await t.req(t.alice, 'POST', '/v1/team/members/bob/poke')
|
||||
expect(again).toMatchObject({ status: 429, body: { reason: 'poke_cooldown' } })
|
||||
expect(again.body.retryAfterMs).toBeGreaterThan(0)
|
||||
expect(await t.req(t.alice, 'POST', '/v1/team/members/alice/poke')).toMatchObject({ status: 400, body: { reason: 'self' } })
|
||||
|
||||
const inbox = await t.req(t.bob, 'GET', '/v1/team/pokes')
|
||||
expect(inbox.body.enabled).toBe(true)
|
||||
expect(inbox.body.pokes).toEqual([{ id: sent.body.poke.id, fromUserId: 'alice', fromName: 'Alice Doe', at: t.h.now() }])
|
||||
// Alice sees nothing addressed to her; another org sees nothing at all.
|
||||
expect((await t.req(t.alice, 'GET', '/v1/team/pokes')).body.pokes).toEqual([])
|
||||
expect((await t.req({ sub: 'bob', orgRole: 'member', org: 'other' }, 'GET', '/v1/team/pokes')).body.pokes).toEqual([])
|
||||
|
||||
expect((await t.req(t.bob, 'POST', '/v1/team/pokes/seen', { ids: [sent.body.poke.id] })).status).toBe(200)
|
||||
expect((await t.req(t.bob, 'GET', '/v1/team/pokes')).body.pokes).toEqual([])
|
||||
|
||||
// Poke back works, and after the cooldown Alice may poke again.
|
||||
expect((await t.req(t.bob, 'POST', '/v1/team/members/alice/poke')).status).toBe(200)
|
||||
t.h.advance(61_000)
|
||||
expect((await t.req(t.alice, 'POST', '/v1/team/members/bob/poke')).status).toBe(200)
|
||||
})
|
||||
|
||||
it('caps pokes per sender per hour and drops stale or opted-out ones', async () => {
|
||||
const t = await team()
|
||||
await t.req(t.alice, 'PUT', '/v1/team/pokes/settings', { enabled: true })
|
||||
const teammates = Array.from({ length: 21 }, (_, i) => ({ sub: `m${i}`, orgRole: 'member' as const }))
|
||||
for (const m of teammates) {
|
||||
await t.req(m, 'PUT', '/v1/team/pokes/settings', { enabled: true })
|
||||
}
|
||||
for (const m of teammates.slice(0, 20)) {
|
||||
expect((await t.req(t.alice, 'POST', `/v1/team/members/${m.sub}/poke`)).status).toBe(200)
|
||||
}
|
||||
expect(await t.req(t.alice, 'POST', '/v1/team/members/m20/poke')).toMatchObject({ status: 429, body: { reason: 'poke_rate' } })
|
||||
// Turning Pokes off clears what was waiting; a day-old poke is never shown.
|
||||
expect((await t.req(teammates[0]!, 'GET', '/v1/team/pokes')).body.pokes).toHaveLength(1)
|
||||
await t.req(teammates[0]!, 'PUT', '/v1/team/pokes/settings', { enabled: false })
|
||||
await t.req(teammates[0]!, 'PUT', '/v1/team/pokes/settings', { enabled: true })
|
||||
expect((await t.req(teammates[0]!, 'GET', '/v1/team/pokes')).body.pokes).toEqual([])
|
||||
t.h.advance(DAY + MIN)
|
||||
expect((await t.req(teammates[1]!, 'GET', '/v1/team/pokes')).body.pokes).toEqual([])
|
||||
})
|
||||
|
||||
it('forgets a removed member so nobody can poke them', async () => {
|
||||
const t = await team()
|
||||
await t.req(t.alice, 'PUT', '/v1/team/pokes/settings', { enabled: true })
|
||||
await t.req(t.bob, 'PUT', '/v1/team/pokes/settings', { enabled: true })
|
||||
const removed = await t.h.call('POST', '/v1/internal/org-members/removed', { bearer: 'o'.repeat(40), body: { accountId: 'org:acme', userId: 'bob' } })
|
||||
expect(removed.status).toBe(200)
|
||||
expect(await t.req(t.alice, 'POST', '/v1/team/members/bob/poke')).toMatchObject({ status: 409, body: { reason: 'teammate_pokes_off' } })
|
||||
})
|
||||
|
||||
it('refuses Pokes on a personal account', async () => {
|
||||
const t = await team()
|
||||
const solo = { sub: 'solo', orgRole: 'owner' as const, org: '' }
|
||||
expect(await t.req(solo, 'PUT', '/v1/team/pokes/settings', { enabled: true })).toMatchObject({ status: 400, body: { reason: 'personal_account' } })
|
||||
expect((await t.req(solo, 'GET', '/v1/team/pokes')).body).toEqual({ enabled: false, pokes: [] })
|
||||
})
|
||||
})
|
||||
|
||||
describe('member-removed token', () => {
|
||||
it('authorizes only POST /v1/internal/org-members/removed, never other operator routes', async () => {
|
||||
const MR = 'm'.repeat(40)
|
||||
const body = { accountId: 'org:acme', userId: 'bob' }
|
||||
const h = await createHarness({ OPERATOR_TOKEN: 'o'.repeat(40), MEMBER_REMOVED_TOKEN: MR })
|
||||
expect((await h.call('POST', '/v1/internal/org-members/removed', { bearer: MR, body })).status).toBe(200)
|
||||
expect((await h.call('GET', '/v1/internal/status', { bearer: MR })).status).toBe(404)
|
||||
expect((await h.call('POST', '/v1/internal/members/removed', { bearer: MR, body })).status).toBe(404)
|
||||
// The operator token still works on the route; a short token is never accepted.
|
||||
expect((await h.call('POST', '/v1/internal/org-members/removed', { bearer: 'o'.repeat(40), body })).status).toBe(200)
|
||||
const weak = await createHarness({ OPERATOR_TOKEN: 'o'.repeat(40), MEMBER_REMOVED_TOKEN: 'short' })
|
||||
expect((await weak.call('POST', '/v1/internal/org-members/removed', { bearer: 'short', body })).status).toBe(404)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,175 @@
|
||||
import { readFileSync, readdirSync } from 'node:fs'
|
||||
import { DatabaseSync } from 'node:sqlite'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { isValidSlug, slugify } from '../src/org-slugs'
|
||||
import { createHarness } from './harness'
|
||||
|
||||
type Role = 'owner' | 'admin' | 'member'
|
||||
type Who = { sub: string; org?: string; role: Role }
|
||||
|
||||
async function setup() {
|
||||
const h = await createHarness()
|
||||
const req = async (who: Who, method: string, path: string, body?: unknown) =>
|
||||
h.call(method, path, { bearer: await h.token(who.sub, who.org, 'sandbox', who.org ? { org_role: who.role } : {}), body })
|
||||
let n = 0
|
||||
const create = async (who: Who, extra: Record<string, unknown> = {}) => {
|
||||
n += 1
|
||||
const res = await req(who, 'POST', '/v1/sandboxes', { workspaceId: `ws-${n}`, machineSize: 'standard', ...extra })
|
||||
expect(res.status).toBe(200)
|
||||
return res.body.sandbox.id as string
|
||||
}
|
||||
const alice: Who = { sub: 'alice', org: 'acme', role: 'member' }
|
||||
const bob: Who = { sub: 'bob', org: 'acme', role: 'member' }
|
||||
const admin: Who = { sub: 'carol', org: 'acme', role: 'admin' }
|
||||
const eve: Who = { sub: 'eve', org: 'other', role: 'owner' }
|
||||
const solo: Who = { sub: 'sam', role: 'member' }
|
||||
return { h, req, create, alice, bob, admin, eve, solo }
|
||||
}
|
||||
|
||||
describe('workspace numbers (W-123)', () => {
|
||||
it('numbers workspaces per account and never reuses a number', async () => {
|
||||
const t = await setup()
|
||||
const a1 = await t.create(t.alice)
|
||||
const a2 = await t.create(t.bob, { visibility: 'team' })
|
||||
const e1 = await t.create(t.eve)
|
||||
const view = async (who: Who, id: string) => (await t.req(who, 'GET', `/v1/team/workspaces/${id}`)).body.workspace
|
||||
expect((await view(t.alice, a1)).number).toBe(1)
|
||||
expect((await view(t.bob, a2)).number).toBe(2)
|
||||
expect((await view(t.eve, e1)).number).toBe(1)
|
||||
expect((await t.req(t.alice, 'DELETE', `/v1/sandboxes/${a1}`)).status).toBe(200)
|
||||
const a3 = await t.create(t.alice)
|
||||
expect((await view(t.alice, a3)).number).toBe(3)
|
||||
})
|
||||
|
||||
it('backfills existing rows by creation order and seeds the counter', () => {
|
||||
const raw = new DatabaseSync(':memory:')
|
||||
const dir = fileURLToPath(new URL('../migrations/', import.meta.url).href)
|
||||
const files = readdirSync(dir).filter((f) => f.endsWith('.sql')).sort()
|
||||
const at = files.indexOf('0051_workspace_numbers_prefs.sql')
|
||||
for (const file of files.slice(0, at)) {
|
||||
raw.exec(readFileSync(`${dir}${file}`, 'utf8'))
|
||||
}
|
||||
const insert = raw.prepare(
|
||||
`INSERT INTO sandboxes (id, account_id, user_id, workspace_id, provider, provider_name, status, machine_size, region,
|
||||
generation, created_at, updated_at) VALUES (?, ?, 'u', ?, 'vercel', ?, 'destroyed', 'standard', 'iad1', 0, ?, ?)`
|
||||
)
|
||||
insert.run('sbx_b', 'org:a', 'w2', 'p2', 20, 20)
|
||||
insert.run('sbx_a', 'org:a', 'w1', 'p1', 10, 10)
|
||||
insert.run('sbx_c', 'org:a', 'w3', 'p3', 20, 20)
|
||||
insert.run('sbx_z', 'org:b', 'w1', 'pz', 5, 5)
|
||||
for (const file of files.slice(at)) {
|
||||
raw.exec(readFileSync(`${dir}${file}`, 'utf8'))
|
||||
}
|
||||
expect(raw.prepare('SELECT id, number FROM sandboxes ORDER BY id').all()).toEqual([
|
||||
{ id: 'sbx_a', number: 1 },
|
||||
{ id: 'sbx_b', number: 2 },
|
||||
{ id: 'sbx_c', number: 3 },
|
||||
{ id: 'sbx_z', number: 1 }
|
||||
])
|
||||
expect(raw.prepare('SELECT * FROM org_workspace_counters ORDER BY account_id').all()).toEqual([
|
||||
{ account_id: 'org:a', last_number: 3 },
|
||||
{ account_id: 'org:b', last_number: 1 }
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('org slugs', () => {
|
||||
it('slugifies names and refuses reserved or malformed slugs', () => {
|
||||
expect(slugify('Acme Labs, Inc.')).toBe('acme-labs-inc')
|
||||
expect(slugify('Ünïcode Crew')).toBe('unicode-crew')
|
||||
expect(slugify('!!!')).toBe('team')
|
||||
expect(slugify('w')).toBe('w-team')
|
||||
expect(isValidSlug('acme')).toBe(true)
|
||||
expect(isValidSlug('w')).toBe(false)
|
||||
expect(isValidSlug('-acme')).toBe(false)
|
||||
expect(isValidSlug('a--b')).toBe(false)
|
||||
expect(isValidSlug('Acme')).toBe(false)
|
||||
})
|
||||
|
||||
it('names an org once from the first name it hears, uniquely across orgs', async () => {
|
||||
const t = await setup()
|
||||
expect((await t.req(t.alice, 'GET', '/v1/team/org')).body).toEqual({ slug: null, orgId: 'acme' })
|
||||
expect((await t.req(t.alice, 'GET', '/v1/team/org?name=Acme%20Labs')).body).toEqual({ slug: 'acme-labs', orgId: 'acme' })
|
||||
// A teammate whose client shows another name still gets the org's slug.
|
||||
expect((await t.req(t.bob, 'GET', '/v1/team/org?name=Whatever')).body.slug).toBe('acme-labs')
|
||||
expect((await t.req(t.eve, 'GET', '/v1/team/org?name=Acme%20Labs')).body.slug).toBe('acme-labs-2')
|
||||
expect((await t.req(t.solo, 'GET', '/v1/team/org?name=Sam')).body).toEqual({ slug: null, orgId: null })
|
||||
})
|
||||
|
||||
it('lets only admins rename, and not onto another org', async () => {
|
||||
const t = await setup()
|
||||
await t.req(t.alice, 'GET', '/v1/team/org?name=Acme')
|
||||
await t.req(t.eve, 'GET', '/v1/team/org?name=Other')
|
||||
expect((await t.req(t.alice, 'PUT', '/v1/team/org', { slug: 'acme-co' })).status).toBe(403)
|
||||
expect((await t.req(t.admin, 'PUT', '/v1/team/org', { slug: 'other' })).status).toBe(409)
|
||||
expect((await t.req(t.admin, 'PUT', '/v1/team/org', { slug: 'w' })).status).toBe(400)
|
||||
expect((await t.req(t.admin, 'PUT', '/v1/team/org', { slug: 'acme-co' })).body).toEqual({ slug: 'acme-co', orgId: 'acme' })
|
||||
expect((await t.req(t.bob, 'GET', '/v1/team/org')).body.slug).toBe('acme-co')
|
||||
})
|
||||
})
|
||||
|
||||
describe('slug links', () => {
|
||||
it('copies org slug links and resolves them only for those who can see the workspace', async () => {
|
||||
const t = await setup()
|
||||
const id = await t.create(t.alice)
|
||||
const before = (await t.req(t.alice, 'GET', `/v1/team/workspaces/${id}`)).body.workspace
|
||||
// No slug yet: the id form still works.
|
||||
expect(before.link).toBe(`orca://cloud/w/${id}`)
|
||||
await t.req(t.alice, 'GET', '/v1/team/org?name=Acme')
|
||||
const after = (await t.req(t.alice, 'GET', '/v1/team/workspaces?scope=mine')).body.workspaces[0]
|
||||
expect(after.link).toBe('orca://cloud/acme/W-1')
|
||||
|
||||
const resolved = await t.req(t.alice, 'GET', '/v1/team/links/resolve?org=acme&n=1&c=s:abc')
|
||||
expect(resolved.status).toBe(200)
|
||||
expect(resolved.body).toMatchObject({ workspace: { id, number: 1 }, chatId: 's:abc' })
|
||||
// Private to Alice: Bob sees nothing until she shares it.
|
||||
expect((await t.req(t.bob, 'GET', '/v1/team/links/resolve?org=acme&n=1')).status).toBe(404)
|
||||
await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${id}`, { visibility: 'team' })
|
||||
expect((await t.req(t.bob, 'GET', '/v1/team/links/resolve?org=acme&n=1')).body.workspace.id).toBe(id)
|
||||
expect((await t.req(t.bob, 'GET', '/v1/team/links/resolve?org=acme&n=2')).status).toBe(404)
|
||||
// Another org: not found, but says which org so a member of both can switch.
|
||||
const other = await t.req(t.eve, 'GET', '/v1/team/links/resolve?org=acme&n=1')
|
||||
expect(other.status).toBe(404)
|
||||
expect(other.body).toEqual({ error: 'not_found', reason: 'other_org', orgId: 'acme' })
|
||||
expect((await t.req(t.eve, 'GET', '/v1/team/links/resolve?org=nope&n=1')).body).toEqual({ error: 'not_found' })
|
||||
expect((await t.req(t.alice, 'GET', '/v1/team/links/resolve?org=acme&n=0')).status).toBe(400)
|
||||
})
|
||||
})
|
||||
|
||||
describe('workspace prefs (synced pins and order)', () => {
|
||||
const A = `sbx_${'a'.repeat(24)}`
|
||||
const B = `sbx_${'b'.repeat(24)}`
|
||||
|
||||
it('stores one document per member and account with compare-and-set', async () => {
|
||||
const t = await setup()
|
||||
expect((await t.req(t.alice, 'GET', '/v1/team/prefs')).body).toEqual({
|
||||
document: { pinned: [], order: [], sections: [], collapsed: [] },
|
||||
revision: 0,
|
||||
updatedAt: null
|
||||
})
|
||||
const doc = { pinned: [A], order: [B], sections: ['Auth', 'Billing'], collapsed: ['Billing'] }
|
||||
const first = await t.req(t.alice, 'PUT', '/v1/team/prefs', { document: doc, revision: 0, deviceId: 'desk-1' })
|
||||
expect(first.status).toBe(200)
|
||||
expect(first.body).toMatchObject({ document: doc, revision: 1 })
|
||||
// A second device that still holds revision 0 must re-read before writing.
|
||||
const stale = await t.req(t.alice, 'PUT', '/v1/team/prefs', { document: { ...doc, pinned: [] }, revision: 0 })
|
||||
expect(stale.status).toBe(409)
|
||||
const second = await t.req(t.alice, 'PUT', '/v1/team/prefs', { document: { ...doc, pinned: [B, A], order: [] }, revision: 1 })
|
||||
expect(second.body.revision).toBe(2)
|
||||
expect((await t.req(t.alice, 'GET', '/v1/team/prefs')).body.document.pinned).toEqual([B, A])
|
||||
// Teammates and other accounts have their own.
|
||||
expect((await t.req(t.bob, 'GET', '/v1/team/prefs')).body.revision).toBe(0)
|
||||
expect((await t.req({ ...t.alice, org: 'other' }, 'GET', '/v1/team/prefs')).body.revision).toBe(0)
|
||||
expect((await t.req(t.solo, 'PUT', '/v1/team/prefs', { document: doc, revision: 0 })).status).toBe(200)
|
||||
})
|
||||
|
||||
it('rejects malformed documents', async () => {
|
||||
const t = await setup()
|
||||
const put = (document: unknown) => t.req(t.alice, 'PUT', '/v1/team/prefs', { document, revision: 0 })
|
||||
expect((await put({ pinned: [A], order: [A], sections: [], collapsed: [] })).status).toBe(400)
|
||||
expect((await put({ pinned: [A, A], order: [], sections: [], collapsed: [] })).status).toBe(400)
|
||||
expect((await put({ pinned: ['nope'], order: [], sections: [], collapsed: [] })).status).toBe(400)
|
||||
expect((await put({ pinned: [], order: [], sections: ['x'], collapsed: [], extra: 1 })).status).toBe(400)
|
||||
})
|
||||
})
|
||||
@@ -66,6 +66,35 @@ describe('workspace registry', () => {
|
||||
expect((await t.req(stranger, 'GET', `/v1/team/links/resolve?w=${t.id}`)).status).toBe(404)
|
||||
})
|
||||
|
||||
it('keeps routine runs off Home unless the Routine runs filter asks for them', async () => {
|
||||
const t = await team()
|
||||
// A routine run's VM: hidden and tagged with its routine (what routines/runs.ts creates).
|
||||
expect((await t.req(t.alice, 'GET', '/v1/team/workspaces?scope=mine')).body.routineRuns).toEqual({ routines: 0, hidden: 0, hiddenRunning: 0, hiddenComputeMs: 0 })
|
||||
t.h.raw
|
||||
.prepare(
|
||||
`INSERT INTO routines (id, account_id, created_by, name, project_id, trigger_kind, trigger_config, agent, prompt, max_runtime_ms, created_at, updated_at)
|
||||
VALUES ('rtn_1', 'org:acme', 'alice', 'nightly-deps', 'prj_1', 'webhook', '{}', 'claude', 'x', 60000, 0, 0)`
|
||||
)
|
||||
.run()
|
||||
t.h.raw.prepare(`UPDATE sandboxes SET hidden = 1, origin = 'routine', origin_ref = 'rtn_1' WHERE id = ?`).run(t.id)
|
||||
const off = await t.req(t.alice, 'GET', '/v1/team/workspaces?scope=mine')
|
||||
expect(off.body.workspaces).toEqual([])
|
||||
// What the switch hides is still counted for Home: the switch label and the team's hours.
|
||||
expect(off.body.routineRuns).toMatchObject({ routines: 1, hidden: 1, hiddenRunning: 1 })
|
||||
const shown = await t.req(t.alice, 'GET', '/v1/team/workspaces?scope=mine&routines=include')
|
||||
expect(shown.body.workspaces.map((w: { id: string; fromRoutine: boolean; routineName: string }) => [w.id, w.fromRoutine, w.routineName])).toEqual([
|
||||
[t.id, true, 'nightly-deps']
|
||||
])
|
||||
expect(shown.body.routineRuns).toMatchObject({ routines: 1, hidden: 0, hiddenRunning: 0 })
|
||||
// Other machine-made rows stay hidden even then.
|
||||
t.h.raw.prepare(`UPDATE sandboxes SET origin = 'vm' WHERE id = ?`).run(t.id)
|
||||
expect((await t.req(t.alice, 'GET', '/v1/team/workspaces?scope=mine&routines=include')).body.workspaces).toEqual([])
|
||||
// A plain workspace says so.
|
||||
t.h.raw.prepare(`UPDATE sandboxes SET hidden = 0, origin = 'desktop' WHERE id = ?`).run(t.id)
|
||||
expect((await t.req(t.alice, 'GET', '/v1/team/workspaces?scope=mine')).body.workspaces[0].fromRoutine).toBe(false)
|
||||
expect((await t.req(t.alice, 'GET', '/v1/team/workspaces?routines=bogus')).status).toBe(400)
|
||||
})
|
||||
|
||||
it('lets admins see private rows for management (scope=all) without access', async () => {
|
||||
const t = await team()
|
||||
expect((await t.req(t.bob, 'GET', '/v1/team/workspaces?scope=all')).status).toBe(403)
|
||||
@@ -414,7 +443,7 @@ describe('desktop wire contract', () => {
|
||||
).body
|
||||
)
|
||||
wire.CloudWorkspaceGrantListSchema.parse((await t.req(t.bob, 'GET', `/v1/team/workspaces/${t.id}/grants`)).body)
|
||||
expect(wire.parseCloudWorkspaceLink(wire.cloudWorkspaceLink(t.id, 'chat 1'))).toEqual({ workspaceId: t.id, chatId: 'chat 1' })
|
||||
expect(wire.parseCloudWorkspaceLink(wire.cloudWorkspaceLink(t.id, 'chat 1'))).toEqual({ target: { kind: 'id', workspaceId: t.id }, chatId: 'chat 1' })
|
||||
expect(issued.grant.status).toBe('active')
|
||||
})
|
||||
|
||||
|
||||
@@ -188,6 +188,13 @@
|
||||
"dynamic": false,
|
||||
"count": 1
|
||||
},
|
||||
{
|
||||
"filePath": "src/renderer/src/lib/workspace/search/worktrees/worktree-palette-evidence.ts",
|
||||
"kind": "object-property:accessibilityLabel",
|
||||
"text": "Cloud workspace number",
|
||||
"dynamic": false,
|
||||
"count": 1
|
||||
},
|
||||
{
|
||||
"filePath": "src/renderer/src/components/agent/launch-settings/AgentDefaultSurfacePreviews.tsx",
|
||||
"kind": "jsx-attribute:title",
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
14 src/main/agent-launch/trust/agent-trust-presets.ts
|
||||
2 src/main/agent-launch/trust/antigravity-workspace-trust-ownership.ts
|
||||
1 src/main/agent-launch/trust/execution-host-workspace-trust.ts
|
||||
2 src/main/agent-mcp-sync/desktop/cloud-mcp-sync.ts
|
||||
1 src/main/agent-mcp-sync/desktop/cloud-mcp-sync.ts
|
||||
1 src/main/ai-vault-search/session-search-worker-client.ts
|
||||
4 src/main/ai-vault/parse-cache/session-parse-cache-legacy-json.ts
|
||||
2 src/main/ai-vault/scan-service/session-scanner-service-entry-path.ts
|
||||
@@ -54,6 +54,7 @@
|
||||
5 src/main/browser/cookies/sources/browser-cookie-source-profiles.ts
|
||||
11 src/main/browser/cookies/staging/browser-session-cookie-staging.ts
|
||||
1 src/main/browser/downloads/browser-download-destination.ts
|
||||
2 src/main/browser/electron-fixtures/popup-identity-electron-probe.ts
|
||||
2 src/main/browser/extensions/api-runtime/browser-extension-worker-shim-source.ts
|
||||
8 src/main/browser/extensions/installation/browser-extension-install-store.ts
|
||||
1 src/main/browser/extensions/installation/browser-extension-load-directory.ts
|
||||
@@ -63,7 +64,6 @@
|
||||
4 src/main/browser/extensions/profile-storage/browser-extension-profile-state-store.ts
|
||||
3 src/main/browser/extensions/profile-storage/browser-extension-retired-profile-storage.ts
|
||||
1 src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-background-cdp-probe.ts
|
||||
2 src/main/browser/electron-fixtures/popup-identity-electron-probe.ts
|
||||
1 src/main/browser/identity/mode/browser-identity-mode-record.ts
|
||||
2 src/main/browser/identity/mode/browser-identity-mode-store.ts
|
||||
2 src/main/browser/network/egress/browser-route-egress-electron-launch.ts
|
||||
@@ -117,7 +117,6 @@
|
||||
1 src/main/codex-accounts/codex-login-auth-snapshot.ts
|
||||
5 src/main/codex-accounts/codex-managed-home-lifecycle.ts
|
||||
6 src/main/codex-accounts/codex-managed-home-path.ts
|
||||
17 src/main/filesystem/atomic-file-publication.ts
|
||||
1 src/main/codex-accounts/guest-codex-account-homes.ts
|
||||
6 src/main/codex-accounts/host-codex-managed-home-ownership.ts
|
||||
2 src/main/codex-accounts/legacy-shared-auth-migration.ts
|
||||
@@ -247,6 +246,7 @@
|
||||
7 src/main/emulator/serve-sim-execution.ts
|
||||
17 src/main/emulator/serve-sim-runtime-materializer.ts
|
||||
12 src/main/external-editors/external-editor-launch.ts
|
||||
17 src/main/filesystem/atomic-file-publication.ts
|
||||
9 src/main/filesystem/durable-file-write.ts
|
||||
2 src/main/filesystem/rolling-file-backup.ts
|
||||
2 src/main/foreign-sqlite-readers/foreign-sqlite-reader-entry-path.ts
|
||||
@@ -297,6 +297,7 @@
|
||||
13 src/main/kimi/hook-service.ts
|
||||
3 src/main/kiro/hook-service.ts
|
||||
1 src/main/kiro/standalone-hooks.ts
|
||||
3 src/main/lib/hidden-probe-cwd.ts
|
||||
4 src/main/linear/linear-credential-paths.ts
|
||||
3 src/main/linear/linear-legacy-viewer-store.ts
|
||||
1 src/main/linear/linear-token-store.ts
|
||||
@@ -465,7 +466,6 @@
|
||||
1 src/main/qoder/workspace-trust.ts
|
||||
4 src/main/rate-limits/providers/cursor/cursor-auth.ts
|
||||
2 src/main/rate-limits/providers/grok/grok-auth.ts
|
||||
3 src/main/lib/hidden-probe-cwd.ts
|
||||
2 src/main/rate-limits/providers/opencode-go/opencode-go-api-key-source.ts
|
||||
1 src/main/rate-limits/providers/zcode/zcode-usage-credentials.ts
|
||||
3 src/main/ripgrep/bundled-ripgrep-path.ts
|
||||
|
||||
@@ -230,6 +230,7 @@ export default function RootLayout() {
|
||||
<Stack.Screen name="cloud/new" options={{ headerShown: false }} />
|
||||
<Stack.Screen name="cloud/access" options={{ headerShown: false }} />
|
||||
<Stack.Screen name="cloud/w/[sandboxId]" options={{ headerShown: false }} />
|
||||
<Stack.Screen name="cloud/[org]/[number]" options={{ headerShown: false }} />
|
||||
<Stack.Screen
|
||||
name="new-workspace"
|
||||
options={{
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { useLocalSearchParams, useRouter } from 'expo-router'
|
||||
import { Cloud } from 'lucide-react-native'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { SafeAreaView } from 'react-native-safe-area-context'
|
||||
import { MobileStateView } from '../../../src/components/MobileStateView'
|
||||
import { CloudWorkspaceScreen } from '../../../src/cloud/CloudWorkspaceScreen'
|
||||
import { resolveCloudWorkspaceLink } from '../../../src/cloud/cloud-workspace-prefs'
|
||||
import { loadCloudControlPlane } from '../../../src/cloud/cloud-session'
|
||||
import { useMobileTranslation } from '../../../src/i18n/use-mobile-translation'
|
||||
import { colors } from '../../../src/theme/mobile-theme'
|
||||
import { parseCloudWorkspaceLink } from '../../../../src/shared/cloud-workspaces/cloud-workspaces-wire'
|
||||
|
||||
type Resolved = { kind: 'loading' } | { kind: 'found'; sandboxId: string } | { kind: 'missing' }
|
||||
|
||||
/** Team links with a number (orca://cloud/<org>/W-123, the desktop's "Copy link") open here. */
|
||||
export default function CloudWorkspaceNumberLinkRoute() {
|
||||
const t = useMobileTranslation()
|
||||
const router = useRouter()
|
||||
const params = useLocalSearchParams<{ org?: string; number?: string }>()
|
||||
const link = `orca://cloud/${params.org ?? ''}/${params.number ?? ''}`
|
||||
const [resolved, setResolved] = useState<Resolved>({ kind: 'loading' })
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
const parsed = parseCloudWorkspaceLink(link)
|
||||
void (async () => {
|
||||
const plane = parsed ? await loadCloudControlPlane() : null
|
||||
const sandboxId =
|
||||
plane && parsed ? await resolveCloudWorkspaceLink(plane, parsed.target) : null
|
||||
if (live) {
|
||||
setResolved(sandboxId ? { kind: 'found', sandboxId } : { kind: 'missing' })
|
||||
}
|
||||
})().catch(() => live && setResolved({ kind: 'missing' }))
|
||||
return () => {
|
||||
live = false
|
||||
}
|
||||
}, [link])
|
||||
if (resolved.kind === 'found') {
|
||||
return <CloudWorkspaceScreen key={resolved.sandboxId} sandboxId={resolved.sandboxId} />
|
||||
}
|
||||
return (
|
||||
<SafeAreaView style={{ flex: 1, backgroundColor: colors.bgBase }}>
|
||||
{resolved.kind === 'loading' ? (
|
||||
<MobileStateView loading title={t('cloud.link.opening', 'Opening workspace…')} />
|
||||
) : (
|
||||
<MobileStateView
|
||||
icon={Cloud}
|
||||
title={t('cloud.link.missingTitle', 'Can’t open this workspace')}
|
||||
message={t(
|
||||
'cloud.link.missing',
|
||||
'It’s private, in another team, or deleted. If it’s in another team, switch to it on your computer first.'
|
||||
)}
|
||||
action={{ label: t('cloud.link.home', 'Go to Home'), onPress: () => router.replace('/') }}
|
||||
/>
|
||||
)}
|
||||
</SafeAreaView>
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Archive, Moon } from 'lucide-react-native'
|
||||
import { Archive, Moon, Pin, PinOff } from 'lucide-react-native'
|
||||
import { useState } from 'react'
|
||||
import { View } from 'react-native'
|
||||
import { ConfirmModal } from '../components/ConfirmModal'
|
||||
@@ -8,6 +8,41 @@ import { colors } from '../theme/mobile-theme'
|
||||
import { useMobileColorScheme } from '../theme/use-mobile-color-scheme'
|
||||
import type { CloudWorkspace } from './cloud-control-plane-client'
|
||||
import { cloudWorkspaceScreenStyles as styles } from './cloud-workspace-screen-styles'
|
||||
import { useCloudWorkspacePrefs } from './cloud-workspace-prefs'
|
||||
import { useCloudEnrollment } from './use-cloud-workspaces'
|
||||
import { setPinned } from '../../../src/shared/cloud-workspaces/cloud-workspace-arrangement'
|
||||
|
||||
/** Pin to the top of the Cloud list on every device of yours (your own pins, not the team's). */
|
||||
function CloudWorkspacePinRow(props: { workspace: CloudWorkspace }) {
|
||||
const t = useMobileTranslation()
|
||||
const enrollment = useCloudEnrollment()
|
||||
const prefs = useCloudWorkspacePrefs(enrollment?.deviceSessionId ?? null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
if (!enrollment || props.workspace.status === 'archived') {
|
||||
return null
|
||||
}
|
||||
const pinned = prefs.document.pinned.includes(props.workspace.id)
|
||||
const Icon = pinned ? PinOff : Pin
|
||||
return (
|
||||
<View style={styles.section}>
|
||||
<View style={styles.card}>
|
||||
<ListRow
|
||||
key="pin"
|
||||
leading={<Icon size={18} color={colors.textSecondary} />}
|
||||
title={pinned ? t('cloud.home.unpin', 'Unpin') : t('cloud.home.pin', 'Pin to top')}
|
||||
subtitle={t('cloud.actions.pinCaption', 'On all your devices. Only you see your pins.')}
|
||||
busy={busy}
|
||||
onPress={() => {
|
||||
setBusy(true)
|
||||
void prefs
|
||||
.edit((doc) => setPinned(doc, props.workspace.id, !pinned))
|
||||
.finally(() => setBusy(false))
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
/** Sleep (no sandbox hours, files kept) and Archive, each behind a confirm because both stop agents. */
|
||||
export function CloudWorkspaceActions(props: {
|
||||
@@ -29,6 +64,7 @@ export function CloudWorkspaceActions(props: {
|
||||
const running = props.workspace.status === 'running'
|
||||
return (
|
||||
<>
|
||||
<CloudWorkspacePinRow workspace={props.workspace} />
|
||||
{running ? (
|
||||
<View style={styles.section}>
|
||||
<View style={styles.card}>
|
||||
|
||||
@@ -47,6 +47,9 @@ export type CloudWorkspace = {
|
||||
createdByUserId: string | null
|
||||
/** When the last sleeping read snapshot was stored (ms); null when none or unknown. */
|
||||
readSnapshotAt: number | null
|
||||
/** Its number in the account (W-123); absent on older control planes and the owner-only list. */
|
||||
number?: number | null
|
||||
section?: string | null
|
||||
}
|
||||
const SANDBOX_STATUS: Record<string, CloudWorkspaceStatus> = {
|
||||
creating: 'creating',
|
||||
@@ -99,7 +102,9 @@ function fromRegistry(row: TeamWorkspace): CloudWorkspace {
|
||||
lastActivityAt: row.lastActivityAt,
|
||||
sandboxMs: row.cost.computeMs,
|
||||
createdByUserId: row.createdBy,
|
||||
readSnapshotAt: row.readSnapshotAt ?? null
|
||||
readSnapshotAt: row.readSnapshotAt ?? null,
|
||||
number: row.number ?? null,
|
||||
section: row.section
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { z } from 'zod'
|
||||
|
||||
vi.mock('./cloud-session', () => ({ loadCloudControlPlane: vi.fn() }))
|
||||
|
||||
import { setPinned } from '../../../src/shared/cloud-workspaces/cloud-workspace-arrangement'
|
||||
import { editCloudWorkspacePrefsOn, resolveCloudWorkspaceLink } from './cloud-workspace-prefs'
|
||||
import type { CloudControlPlane } from './cloud-control-plane-request'
|
||||
|
||||
const PutBody = z.object({
|
||||
document: z.object({
|
||||
pinned: z.array(z.string()),
|
||||
order: z.array(z.string()),
|
||||
sections: z.array(z.string()),
|
||||
collapsed: z.array(z.string())
|
||||
}),
|
||||
revision: z.number()
|
||||
})
|
||||
|
||||
const A = `sbx_${'a'.repeat(24)}`
|
||||
const B = `sbx_${'b'.repeat(24)}`
|
||||
|
||||
function plane(handler: (method: string, url: URL, body: unknown) => [number, unknown]) {
|
||||
const calls: string[] = []
|
||||
const fetchFn: typeof fetch = async (input, init = {}) => {
|
||||
const url = new URL(String(input))
|
||||
calls.push(`${init.method} ${url.pathname}${url.search}`)
|
||||
const [status, body] = handler(
|
||||
init.method ?? 'GET',
|
||||
url,
|
||||
init.body ? JSON.parse(String(init.body)) : undefined
|
||||
)
|
||||
return new Response(JSON.stringify(body), { status })
|
||||
}
|
||||
const p: CloudControlPlane = { baseUrl: 'https://cp.example', token: () => 't', fetch: fetchFn }
|
||||
return { plane: p, calls }
|
||||
}
|
||||
|
||||
describe('phone prefs sync', () => {
|
||||
it('re-applies a pin on top of a desktop that wrote first', async () => {
|
||||
let server: z.infer<typeof PutBody> = {
|
||||
document: { pinned: [B], order: [], sections: [], collapsed: [] },
|
||||
revision: 3
|
||||
}
|
||||
let firstPut = true
|
||||
const { plane: p, calls } = plane((method, _url, body) => {
|
||||
if (method === 'GET') {
|
||||
return [200, { ...server, updatedAt: 1 }]
|
||||
}
|
||||
const put = PutBody.parse(body)
|
||||
if (firstPut) {
|
||||
// A desktop wrote between our read and our write.
|
||||
firstPut = false
|
||||
server = { ...server, revision: 4 }
|
||||
return [409, { error: 'conflict', reason: 'stale_revision' }]
|
||||
}
|
||||
expect(put.revision).toBe(4)
|
||||
server = { document: put.document, revision: 5 }
|
||||
return [200, { ...server, updatedAt: 2 }]
|
||||
})
|
||||
const saved = await editCloudWorkspacePrefsOn(p, (doc) => setPinned(doc, A, true))
|
||||
expect(saved.document.pinned).toEqual([B, A])
|
||||
expect(calls).toEqual([
|
||||
'GET /v1/team/prefs',
|
||||
'PUT /v1/team/prefs',
|
||||
'GET /v1/team/prefs',
|
||||
'PUT /v1/team/prefs'
|
||||
])
|
||||
})
|
||||
|
||||
it('resolves number links and treats not found as null', async () => {
|
||||
const { plane: p, calls } = plane((_method, url) =>
|
||||
url.searchParams.get('n') === '7'
|
||||
? [200, { workspace: { id: A }, chatId: null }]
|
||||
: [404, { error: 'not_found' }]
|
||||
)
|
||||
await expect(
|
||||
resolveCloudWorkspaceLink(p, { kind: 'number', org: 'acme', number: 8 })
|
||||
).resolves.toBeNull()
|
||||
expect(calls).toEqual(['GET /v1/team/links/resolve?org=acme&n=8'])
|
||||
await expect(resolveCloudWorkspaceLink(p, { kind: 'id', workspaceId: B })).resolves.toBe(B)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,125 @@
|
||||
// The phone's side of synced cloud workspace prefs (/v1/team/prefs): the same pins and order as
|
||||
// the member's desktops, read and written with the phone's own device-signed token, and W-number
|
||||
// links (orca://cloud/<org>/W-123) resolved to a workspace.
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useCallback } from 'react'
|
||||
import {
|
||||
CloudWorkspaceLinkResponseSchema,
|
||||
CloudWorkspacePrefsSchema,
|
||||
EMPTY_CLOUD_WORKSPACE_PREFS,
|
||||
type CloudWorkspaceLinkTarget,
|
||||
type CloudWorkspacePrefs,
|
||||
type CloudWorkspacePrefsDocument
|
||||
} from '../../../src/shared/cloud-workspaces/cloud-workspaces-wire'
|
||||
import {
|
||||
CloudRequestError,
|
||||
cloudRequest as request,
|
||||
type CloudControlPlane
|
||||
} from './cloud-control-plane-request'
|
||||
import { loadCloudControlPlane } from './cloud-session'
|
||||
|
||||
const MAX_ATTEMPTS = 4
|
||||
|
||||
export function getCloudWorkspacePrefs(
|
||||
plane: CloudControlPlane,
|
||||
signal?: AbortSignal
|
||||
): Promise<CloudWorkspacePrefs> {
|
||||
return request(plane, 'GET', '/v1/team/prefs', CloudWorkspacePrefsSchema, { signal })
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies `edit` to the newest server copy and writes it with compare-and-set; when a desktop wrote
|
||||
* first it re-reads and applies the same edit again.
|
||||
*/
|
||||
export async function editCloudWorkspacePrefsOn(
|
||||
plane: CloudControlPlane,
|
||||
edit: (doc: CloudWorkspacePrefsDocument) => CloudWorkspacePrefsDocument
|
||||
): Promise<CloudWorkspacePrefs> {
|
||||
let current = await getCloudWorkspacePrefs(plane)
|
||||
for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt += 1) {
|
||||
const next = edit(current.document)
|
||||
if (next === current.document) {
|
||||
return current
|
||||
}
|
||||
try {
|
||||
return await request(plane, 'PUT', '/v1/team/prefs', CloudWorkspacePrefsSchema, {
|
||||
body: { document: next, revision: current.revision }
|
||||
})
|
||||
} catch (error) {
|
||||
if (!(error instanceof CloudRequestError) || error.code !== 'conflict') {
|
||||
throw error
|
||||
}
|
||||
current = await getCloudWorkspacePrefs(plane)
|
||||
}
|
||||
}
|
||||
throw new CloudRequestError('conflict', 409, 'stale_revision')
|
||||
}
|
||||
|
||||
/** Either link form → the workspace's sandbox id (null when this account can't see it). */
|
||||
export async function resolveCloudWorkspaceLink(
|
||||
plane: CloudControlPlane,
|
||||
target: CloudWorkspaceLinkTarget
|
||||
): Promise<string | null> {
|
||||
if (target.kind === 'id') {
|
||||
return target.workspaceId
|
||||
}
|
||||
const params = new URLSearchParams({ org: target.org, n: String(target.number) })
|
||||
try {
|
||||
const body = await request(
|
||||
plane,
|
||||
'GET',
|
||||
`/v1/team/links/resolve?${params}`,
|
||||
CloudWorkspaceLinkResponseSchema
|
||||
)
|
||||
return body.workspace.id
|
||||
} catch (error) {
|
||||
if (error instanceof CloudRequestError && error.status === 404) {
|
||||
return null
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export const cloudWorkspacePrefsQueryKey = (sessionId: string | null) =>
|
||||
['orca-cloud', 'prefs', sessionId] as const
|
||||
|
||||
/** This member's synced prefs and an edit that saves them (shown at once, rolled back on failure). */
|
||||
export function useCloudWorkspacePrefs(sessionId: string | null) {
|
||||
const client = useQueryClient()
|
||||
const query = useQuery({
|
||||
queryKey: cloudWorkspacePrefsQueryKey(sessionId),
|
||||
enabled: sessionId !== null,
|
||||
queryFn: async ({ signal }) => {
|
||||
const plane = await loadCloudControlPlane()
|
||||
return plane
|
||||
? (await getCloudWorkspacePrefs(plane, signal)).document
|
||||
: EMPTY_CLOUD_WORKSPACE_PREFS
|
||||
},
|
||||
// Desktops edit it too; pick their edits up whenever Home is in front.
|
||||
refetchInterval: 15_000,
|
||||
staleTime: 5_000
|
||||
})
|
||||
const edit = useCallback(
|
||||
async (change: (doc: CloudWorkspacePrefsDocument) => CloudWorkspacePrefsDocument) => {
|
||||
const key = cloudWorkspacePrefsQueryKey(sessionId)
|
||||
const previous = client.getQueryData<CloudWorkspacePrefsDocument>(key)
|
||||
client.setQueryData<CloudWorkspacePrefsDocument>(key, (doc) =>
|
||||
change(doc ?? EMPTY_CLOUD_WORKSPACE_PREFS)
|
||||
)
|
||||
try {
|
||||
const plane = await loadCloudControlPlane()
|
||||
if (!plane) {
|
||||
throw new CloudRequestError('not_enrolled', 0)
|
||||
}
|
||||
const saved = await editCloudWorkspacePrefsOn(plane, change)
|
||||
client.setQueryData(key, saved.document)
|
||||
return true
|
||||
} catch {
|
||||
client.setQueryData(key, previous)
|
||||
return false
|
||||
}
|
||||
},
|
||||
[client, sessionId]
|
||||
)
|
||||
return { document: query.data ?? EMPTY_CLOUD_WORKSPACE_PREFS, edit }
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useRouter } from 'expo-router'
|
||||
import { ChevronRight, Cloud, Plus, RotateCw } from 'lucide-react-native'
|
||||
import { Fragment, useState } from 'react'
|
||||
import { ActivityIndicator, Pressable, Text, View } from 'react-native'
|
||||
import { ChevronRight, Cloud, Pin, Plus, RotateCw } from 'lucide-react-native'
|
||||
import { Fragment, useMemo, useState } from 'react'
|
||||
import { ActivityIndicator, Alert, Pressable, Text, View } from 'react-native'
|
||||
import { CloudStatusDot } from '../cloud/CloudStatusDot'
|
||||
import { formatReadSnapshotAsOf } from '../cloud/CloudReadSnapshotSection'
|
||||
import type { CloudWorkspace } from '../cloud/cloud-control-plane-client'
|
||||
@@ -10,6 +10,12 @@ import { takeCloudReturnTo } from '../cloud/cloud-return-to'
|
||||
import type { CloudEnrollment } from '../cloud/cloud-device-identity'
|
||||
import { cloudRepoLine, cloudStatusLabel } from '../cloud/cloud-workspace-display'
|
||||
import { useCloudWorkspaces } from '../cloud/use-cloud-workspaces'
|
||||
import { useCloudWorkspacePrefs } from '../cloud/cloud-workspace-prefs'
|
||||
import {
|
||||
arrangeCloudWorkspaces,
|
||||
setPinned
|
||||
} from '../../../src/shared/cloud-workspaces/cloud-workspace-arrangement'
|
||||
import { formatWorkspaceNumber } from '../../../src/shared/cloud-workspaces/cloud-workspaces-wire'
|
||||
import { formatTimeAgo } from '../worktree/agent-row-display'
|
||||
import { useMobileTranslation } from '../i18n/use-mobile-translation'
|
||||
import { colors } from '../theme/mobile-theme'
|
||||
@@ -35,13 +41,43 @@ export function MobileHomeCloudSection(props: {
|
||||
const t = useMobileTranslation()
|
||||
useMobileColorScheme()
|
||||
const query = useCloudWorkspaces(props.enrollment)
|
||||
// Pins and order are the member's own and sync with their desktops.
|
||||
const prefs = useCloudWorkspacePrefs(props.enrollment?.deviceSessionId ?? null)
|
||||
const workspaces = useMemo(
|
||||
() =>
|
||||
arrangeCloudWorkspaces(
|
||||
(query.data ?? []).filter((workspace) => workspace.status !== 'archived'),
|
||||
prefs.document
|
||||
).flatMap((group) =>
|
||||
group.rows.map((workspace) => ({ workspace, pinned: group.kind === 'pinned' }))
|
||||
),
|
||||
[query.data, prefs.document]
|
||||
)
|
||||
if (props.enrollment === undefined) {
|
||||
return null
|
||||
}
|
||||
if (props.enrollment === null) {
|
||||
return <CloudConnectRow desktop={props.enrollDesktop} deviceLabel={props.deviceLabel} />
|
||||
}
|
||||
const workspaces = (query.data ?? []).filter((workspace) => workspace.status !== 'archived')
|
||||
const togglePin = (workspace: CloudWorkspace, pinned: boolean) => {
|
||||
Alert.alert(workspace.title, undefined, [
|
||||
{
|
||||
text: pinned ? t('cloud.home.unpin', 'Unpin') : t('cloud.home.pin', 'Pin to top'),
|
||||
onPress: () =>
|
||||
void prefs
|
||||
.edit((doc) => setPinned(doc, workspace.id, !pinned))
|
||||
.then((saved) => {
|
||||
if (!saved) {
|
||||
Alert.alert(
|
||||
t('cloud.home.pinFailed', 'Couldn’t save that change'),
|
||||
t('cloud.home.pinFailedDetail', 'Check your connection and try again.')
|
||||
)
|
||||
}
|
||||
})
|
||||
},
|
||||
{ text: t('common.cancel', 'Cancel'), style: 'cancel' }
|
||||
])
|
||||
}
|
||||
const now = query.dataUpdatedAt || 0
|
||||
return (
|
||||
<>
|
||||
@@ -94,12 +130,14 @@ export function MobileHomeCloudSection(props: {
|
||||
</View>
|
||||
</View>
|
||||
) : (
|
||||
workspaces.map((workspace) => (
|
||||
workspaces.map(({ workspace, pinned }) => (
|
||||
<Fragment key={workspace.id}>
|
||||
<CloudWorkspaceRow
|
||||
workspace={workspace}
|
||||
pinned={pinned}
|
||||
now={now}
|
||||
onPress={() => props.onOpenWorkspace(workspace)}
|
||||
onLongPress={() => togglePin(workspace, pinned)}
|
||||
/>
|
||||
<View style={[styles.separator, styles.tileSeparator]} />
|
||||
</Fragment>
|
||||
@@ -135,12 +173,16 @@ function SkeletonRow() {
|
||||
|
||||
function CloudWorkspaceRow({
|
||||
workspace,
|
||||
pinned,
|
||||
now,
|
||||
onPress
|
||||
onPress,
|
||||
onLongPress
|
||||
}: {
|
||||
workspace: CloudWorkspace
|
||||
pinned: boolean
|
||||
now: number
|
||||
onPress: () => void
|
||||
onLongPress: () => void
|
||||
}) {
|
||||
const t = useMobileTranslation()
|
||||
const status = cloudStatusLabel(workspace.status, t)
|
||||
@@ -175,7 +217,9 @@ function CloudWorkspaceRow({
|
||||
: createdLine && lastActive - workspace.createdAt < 60_000
|
||||
? null
|
||||
: formatTimeAgo(lastActive, reference)
|
||||
const line = [status, detail, when].filter(Boolean).join(' · ')
|
||||
const number = workspace.number ? formatWorkspaceNumber(workspace.number) : null
|
||||
const line = [status, number, detail, when].filter(Boolean).join(' · ')
|
||||
const optionsLabel = pinned ? t('cloud.home.unpin', 'Unpin') : t('cloud.home.pin', 'Pin to top')
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
@@ -187,8 +231,17 @@ function CloudWorkspaceRow({
|
||||
detail: line
|
||||
}
|
||||
)}
|
||||
accessibilityHint={pinned ? t('cloud.home.pinnedHint', 'Pinned') : undefined}
|
||||
accessibilityActions={[{ name: 'longpress', label: optionsLabel }]}
|
||||
onAccessibilityAction={(event) => {
|
||||
if (event.nativeEvent.actionName === 'longpress') {
|
||||
onLongPress()
|
||||
}
|
||||
}}
|
||||
style={({ pressed }) => [styles.row, pressed && styles.rowPressed]}
|
||||
onPress={onPress}
|
||||
onLongPress={onLongPress}
|
||||
delayLongPress={400}
|
||||
>
|
||||
<View style={styles.tile}>
|
||||
<Cloud size={17} strokeWidth={1.8} color={colors.textPrimary} />
|
||||
@@ -204,13 +257,14 @@ function CloudWorkspaceRow({
|
||||
<Text style={workspace.status === 'failed' ? { color: colors.statusRed } : undefined}>
|
||||
{status}
|
||||
</Text>
|
||||
{[detail, when]
|
||||
{[number, detail, when]
|
||||
.filter(Boolean)
|
||||
.map((part) => ` · ${part}`)
|
||||
.join('')}
|
||||
</Text>
|
||||
</View>
|
||||
<View style={styles.trailing}>
|
||||
{pinned ? <Pin size={14} color={colors.textMuted} /> : null}
|
||||
<ChevronRight size={18} color={colors.textMuted} />
|
||||
</View>
|
||||
</Pressable>
|
||||
|
||||
@@ -5020,7 +5020,8 @@
|
||||
"actions": {
|
||||
"sleep": "Sleep",
|
||||
"sleepCaption": "Sandbox hours stop. Files are kept; agents restart when it wakes.",
|
||||
"archive": "Archive"
|
||||
"archive": "Archive",
|
||||
"pinCaption": "On all your devices. Only you see your pins."
|
||||
},
|
||||
"sleep": {
|
||||
"title": "Sleep {{title}}?",
|
||||
@@ -5122,7 +5123,12 @@
|
||||
"new": "New cloud workspace",
|
||||
"createdAgo": "Created {{ago}} ago",
|
||||
"createdJustNow": "Created just now",
|
||||
"workspaceRowLabel": "Cloud workspace, {{title}}, {{detail}}"
|
||||
"workspaceRowLabel": "Cloud workspace, {{title}}, {{detail}}",
|
||||
"unpin": "Unpin",
|
||||
"pin": "Pin to top",
|
||||
"pinFailed": "Couldn’t save that change",
|
||||
"pinFailedDetail": "Check your connection and try again.",
|
||||
"pinnedHint": "Pinned"
|
||||
},
|
||||
"connect": {
|
||||
"signedOut": "Sign in to Orca on {{desktop}}, then try again.",
|
||||
@@ -5231,6 +5237,12 @@
|
||||
"idle": {
|
||||
"sleeps_one": "Sleeps after {{count}} minute idle.",
|
||||
"sleeps_other": "Sleeps after {{count}} minutes idle."
|
||||
},
|
||||
"link": {
|
||||
"opening": "Opening workspace…",
|
||||
"missingTitle": "Can’t open this workspace",
|
||||
"missing": "It’s private, in another team, or deleted. If it’s in another team, switch to it on your computer first.",
|
||||
"home": "Go to Home"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
|
||||
export type AgentConfigDigestEntry = {
|
||||
/** Relative path inside a skill folder, or `.` for a command file. */
|
||||
path: string
|
||||
executable: boolean
|
||||
bytes: Buffer
|
||||
}
|
||||
|
||||
/** Content identity of one item. Desktop and host compute it the same way, so either side can tell
|
||||
* whether a sandbox copy is exactly what this computer sent. */
|
||||
export function agentConfigDigest(entries: readonly AgentConfigDigestEntry[]): string {
|
||||
const hash = createHash('sha256')
|
||||
for (const entry of [...entries].sort((a, b) =>
|
||||
a.path < b.path ? -1 : a.path > b.path ? 1 : 0
|
||||
)) {
|
||||
const body = createHash('sha256').update(entry.bytes).digest('hex')
|
||||
hash.update(`${entry.path}\0${entry.executable ? 1 : 0}\0${body}\n`)
|
||||
}
|
||||
return hash.digest('hex')
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import type {
|
||||
AgentConfigItemKind,
|
||||
AgentConfigItemScope
|
||||
} from '../../shared/agent-config-sync/agent-config-sync-contract'
|
||||
import { AGENT_CONFIG_FILE_KINDS } from '../../shared/agent-config-sync/agent-config-sync-contract'
|
||||
|
||||
export type AgentConfigHomes = {
|
||||
/** Claude Code's config dir: $CLAUDE_CONFIG_DIR or ~/.claude. */
|
||||
claudeDir: string
|
||||
/** $CODEX_HOME or ~/.codex. */
|
||||
codexDir: string
|
||||
home: string
|
||||
}
|
||||
|
||||
export function defaultAgentConfigHomes(env: NodeJS.ProcessEnv = process.env): AgentConfigHomes {
|
||||
const home = homedir()
|
||||
return {
|
||||
claudeDir: env.CLAUDE_CONFIG_DIR?.trim() || join(home, '.claude'),
|
||||
codexDir: env.CODEX_HOME?.trim() || join(home, '.codex'),
|
||||
home
|
||||
}
|
||||
}
|
||||
|
||||
/** The folder that holds every item of a kind; null when the kind has no such scope. */
|
||||
export function agentConfigRoot(
|
||||
kind: AgentConfigItemKind,
|
||||
scope: AgentConfigItemScope,
|
||||
homes: AgentConfigHomes,
|
||||
projectPath: string | null
|
||||
): string | null {
|
||||
if (scope === 'project') {
|
||||
if (!projectPath) {
|
||||
return null
|
||||
}
|
||||
switch (kind) {
|
||||
case 'claude-skill':
|
||||
return join(projectPath, '.claude', 'skills')
|
||||
case 'claude-command':
|
||||
return join(projectPath, '.claude', 'commands')
|
||||
case 'agents-skill':
|
||||
return join(projectPath, '.agents', 'skills')
|
||||
// Codex reads prompts and its older skills folder from home only.
|
||||
case 'codex-skill':
|
||||
case 'codex-prompt':
|
||||
return null
|
||||
}
|
||||
}
|
||||
switch (kind) {
|
||||
case 'claude-skill':
|
||||
return join(homes.claudeDir, 'skills')
|
||||
case 'claude-command':
|
||||
return join(homes.claudeDir, 'commands')
|
||||
case 'agents-skill':
|
||||
return join(homes.home, '.agents', 'skills')
|
||||
case 'codex-skill':
|
||||
return join(homes.codexDir, 'skills')
|
||||
case 'codex-prompt':
|
||||
return join(homes.codexDir, 'prompts')
|
||||
}
|
||||
}
|
||||
|
||||
/** Where one item lives under its root: a folder for skills, `<name>.md` for commands. */
|
||||
export function agentConfigItemPath(root: string, kind: AgentConfigItemKind, name: string): string {
|
||||
return AGENT_CONFIG_FILE_KINDS.has(kind)
|
||||
? join(root, ...`${name}.md`.split('/'))
|
||||
: join(root, name)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Skills sometimes sit next to keys a script reads. Those files stay on this computer: names that
|
||||
* hold credentials by convention, and text with a well-known key or token shape.
|
||||
*/
|
||||
|
||||
const SECRET_FILE_NAMES = [
|
||||
/^\.?env(\..*)?$/i,
|
||||
/\.(pem|key|p12|pfx|jks|keystore|ppk|asc|gpg|kdbx|der|crt)$/i,
|
||||
/^id_(rsa|dsa|ecdsa|ed25519)(\.pub)?$/i,
|
||||
/^(credentials?|secrets?|tokens?|auth|service[-_]?account)([-_.].*)?\.(json|ya?ml|toml|txt|ini|env)$/i,
|
||||
/^\.?(npmrc|netrc|pypirc|htpasswd|git-credentials)$/i,
|
||||
/^client_secret.*\.json$/i
|
||||
]
|
||||
|
||||
const SECRET_CONTENT = [
|
||||
/-----BEGIN (?:[A-Z0-9]+ )?PRIVATE KEY-----/,
|
||||
/\bAKIA[0-9A-Z]{16}\b/,
|
||||
/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,}\b/,
|
||||
/\bgithub_pat_[A-Za-z0-9_]{60,}\b/,
|
||||
/\bglpat-[A-Za-z0-9_-]{20,}\b/,
|
||||
/\bsk-ant-[A-Za-z0-9_-]{20,}\b/,
|
||||
/\bsk-(?:proj-|live_|test_)?[A-Za-z0-9_-]{32,}\b/,
|
||||
/\bxox[abposr]-[A-Za-z0-9-]{10,}\b/,
|
||||
/\bAIza[0-9A-Za-z_-]{35}\b/,
|
||||
/\bnpm_[A-Za-z0-9]{36}\b/,
|
||||
/\b(?:rk|sk)_live_[A-Za-z0-9]{20,}\b/,
|
||||
/\bvck_[A-Za-z0-9]{20,}\b/
|
||||
]
|
||||
|
||||
export function isSecretFileName(name: string): boolean {
|
||||
return SECRET_FILE_NAMES.some((pattern) => pattern.test(name))
|
||||
}
|
||||
|
||||
/** Binary files are not scanned: the patterns are text shapes. */
|
||||
export function hasSecretContent(bytes: Buffer): boolean {
|
||||
if (bytes.subarray(0, 8000).includes(0)) {
|
||||
return false
|
||||
}
|
||||
const text = bytes.toString('utf8')
|
||||
return SECRET_CONTENT.some((pattern) => pattern.test(text))
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import {
|
||||
AGENT_CONFIG_LIMITS,
|
||||
agentConfigItemKey,
|
||||
type AgentConfigItemKind,
|
||||
type AgentConfigItemPayload,
|
||||
type AgentConfigItemRef,
|
||||
type AgentConfigSyncPlanResult,
|
||||
type AgentConfigSyncPutResult,
|
||||
type AgentConfigSyncRow
|
||||
} from '../../../shared/agent-config-sync/agent-config-sync-contract'
|
||||
import type { AgentConfigDigestEntry } from '../agent-config-digest'
|
||||
import type { LocalAgentConfigItem } from './local-agent-config-read'
|
||||
|
||||
export type DesiredAgentConfigItem = AgentConfigItemRef & {
|
||||
key: string
|
||||
files: AgentConfigDigestEntry[]
|
||||
}
|
||||
|
||||
export type AgentConfigSyncPlan = {
|
||||
rows: AgentConfigSyncRow[]
|
||||
desired: DesiredAgentConfigItem[]
|
||||
}
|
||||
|
||||
/** The other agent's kind an item converts to; the formats match (SKILL.md folders, Markdown prompts). */
|
||||
function counterpartKind(item: LocalAgentConfigItem): AgentConfigItemKind | null {
|
||||
switch (item.kind) {
|
||||
case 'claude-skill':
|
||||
return 'agents-skill'
|
||||
case 'agents-skill':
|
||||
case 'codex-skill':
|
||||
return 'claude-skill'
|
||||
case 'claude-command':
|
||||
// Codex prompts are flat: a namespaced command has no Codex name.
|
||||
return item.name.includes('/') ? null : 'codex-prompt'
|
||||
case 'codex-prompt':
|
||||
return 'claude-command'
|
||||
}
|
||||
}
|
||||
|
||||
/** Kinds that already give the other agent an item of that name. */
|
||||
const NATIVE_FOR: Record<AgentConfigItemKind, AgentConfigItemKind[]> = {
|
||||
'agents-skill': ['agents-skill', 'codex-skill'],
|
||||
'codex-skill': ['agents-skill', 'codex-skill'],
|
||||
'claude-skill': ['claude-skill'],
|
||||
'claude-command': ['claude-command'],
|
||||
'codex-prompt': ['codex-prompt']
|
||||
}
|
||||
|
||||
function rowOf(item: LocalAgentConfigItem, key: string, included: boolean): AgentConfigSyncRow {
|
||||
return {
|
||||
key,
|
||||
scope: item.scope,
|
||||
kind: item.kind,
|
||||
name: item.name,
|
||||
bytes: item.bytes,
|
||||
fileCount: item.fileCount,
|
||||
withheldFiles: item.withheldFiles,
|
||||
included,
|
||||
state: 'pending'
|
||||
}
|
||||
}
|
||||
|
||||
/** What to send and how each local item shows, before the host answers. */
|
||||
export function planAgentConfigSync(args: {
|
||||
items: readonly LocalAgentConfigItem[]
|
||||
excluded: ReadonlySet<string>
|
||||
shareAcrossAgents: boolean
|
||||
}): AgentConfigSyncPlan {
|
||||
const rows: AgentConfigSyncRow[] = []
|
||||
const candidates: { row: AgentConfigSyncRow; item: LocalAgentConfigItem }[] = []
|
||||
const names = new Set(
|
||||
args.items.filter((item) => item.scope === 'user').map((item) => `${item.kind}:${item.name}`)
|
||||
)
|
||||
const converted = new Set<string>()
|
||||
for (const item of args.items) {
|
||||
const key = agentConfigItemKey(item.scope, item.kind, item.name)
|
||||
const included = !args.excluded.has(key)
|
||||
const row = rowOf(item, key, included)
|
||||
if (item.skipReason) {
|
||||
rows.push({ ...row, state: 'skipped', skipReason: item.skipReason })
|
||||
continue
|
||||
}
|
||||
if (!included) {
|
||||
rows.push({ ...row, state: 'skipped', skipReason: 'turned-off' })
|
||||
continue
|
||||
}
|
||||
rows.push(row)
|
||||
candidates.push({ row, item })
|
||||
const target = args.shareAcrossAgents && item.scope === 'user' ? counterpartKind(item) : null
|
||||
if (
|
||||
!target ||
|
||||
NATIVE_FOR[target].some((kind) => names.has(`${kind}:${item.name}`)) ||
|
||||
converted.has(`${target}:${item.name}`)
|
||||
) {
|
||||
continue
|
||||
}
|
||||
// One copy per name: .agents and the older .codex skills folder can both hold it.
|
||||
converted.add(`${target}:${item.name}`)
|
||||
const copy = { ...item, kind: target }
|
||||
const copyRow: AgentConfigSyncRow = {
|
||||
...rowOf(copy, agentConfigItemKey('user', target, item.name), true),
|
||||
convertedFrom: key
|
||||
}
|
||||
rows.push(copyRow)
|
||||
candidates.push({ row: copyRow, item: copy })
|
||||
}
|
||||
// Natives first, so a copy is what falls past the limit.
|
||||
candidates.sort((a, b) => Number(!!a.row.convertedFrom) - Number(!!b.row.convertedFrom))
|
||||
const desired: DesiredAgentConfigItem[] = []
|
||||
let total = 0
|
||||
for (const { row, item } of candidates) {
|
||||
if (
|
||||
desired.length >= AGENT_CONFIG_LIMITS.items ||
|
||||
total + item.bytes > AGENT_CONFIG_LIMITS.totalBytes ||
|
||||
!item.digest
|
||||
) {
|
||||
row.state = 'skipped'
|
||||
row.skipReason = 'over-limit'
|
||||
continue
|
||||
}
|
||||
total += item.bytes
|
||||
desired.push({
|
||||
key: row.key,
|
||||
scope: item.scope,
|
||||
kind: item.kind,
|
||||
name: item.name,
|
||||
digest: item.digest,
|
||||
files: item.files
|
||||
})
|
||||
}
|
||||
return { rows, desired }
|
||||
}
|
||||
|
||||
/** Put calls that each stay under one item's byte budget (and so under the RPC frame). */
|
||||
export function agentConfigPutBatches(
|
||||
items: readonly DesiredAgentConfigItem[]
|
||||
): AgentConfigItemPayload[][] {
|
||||
const batches: AgentConfigItemPayload[][] = []
|
||||
let current: AgentConfigItemPayload[] = []
|
||||
let bytes = 0
|
||||
for (const item of items) {
|
||||
const size = item.files.reduce((sum, file) => sum + file.bytes.length, 0)
|
||||
if (
|
||||
current.length > 0 &&
|
||||
(bytes + size > AGENT_CONFIG_LIMITS.itemBytes ||
|
||||
current.length >= AGENT_CONFIG_LIMITS.putItems)
|
||||
) {
|
||||
batches.push(current)
|
||||
current = []
|
||||
bytes = 0
|
||||
}
|
||||
current.push({
|
||||
scope: item.scope,
|
||||
kind: item.kind,
|
||||
name: item.name,
|
||||
digest: item.digest,
|
||||
files: item.files.map((file) => ({
|
||||
path: file.path,
|
||||
executable: file.executable,
|
||||
base64: file.bytes.toString('base64')
|
||||
}))
|
||||
})
|
||||
bytes += size
|
||||
}
|
||||
if (current.length > 0) {
|
||||
batches.push(current)
|
||||
}
|
||||
return batches
|
||||
}
|
||||
|
||||
const SYNCED_OUTCOMES: ReadonlySet<string> = new Set(['added', 'updated', 'unchanged'])
|
||||
|
||||
/** Rows after the host's plan and puts answered. */
|
||||
export function applyAgentConfigSyncResults(
|
||||
rows: readonly AgentConfigSyncRow[],
|
||||
plan: AgentConfigSyncPlanResult,
|
||||
put: AgentConfigSyncPutResult['items']
|
||||
): AgentConfigSyncRow[] {
|
||||
return rows.map((row) => {
|
||||
if (row.state === 'skipped') {
|
||||
return row
|
||||
}
|
||||
const outcome = put[row.key] ?? plan.items[row.key]
|
||||
if (!outcome) {
|
||||
return row
|
||||
}
|
||||
const synced = SYNCED_OUTCOMES.has(outcome)
|
||||
return { ...row, state: synced ? 'synced' : 'skipped', outcome }
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { BrowserWindow, ipcMain } from 'electron'
|
||||
import {
|
||||
CLOUD_AGENT_CONFIG_SYNC_CHANGED_CHANNEL,
|
||||
CLOUD_AGENT_CONFIG_SYNC_PREFERENCES_CHANNEL,
|
||||
type CloudAgentConfigSyncPreferences
|
||||
} from '../../../shared/agent-config-sync/agent-config-sync-contract'
|
||||
import { createCloudAgentConfigSync, type CloudAgentConfigSync } from './cloud-agent-config-sync'
|
||||
|
||||
let instance: CloudAgentConfigSync | null = null
|
||||
|
||||
function send(channel: string, payload: unknown): void {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (!window.isDestroyed()) {
|
||||
window.webContents.send(channel, payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function environmentIdOf(value: unknown): string | null {
|
||||
return typeof value === 'string' && value.length > 0 && value.length <= 256 ? value : null
|
||||
}
|
||||
|
||||
function preferencesOf(value: unknown): Partial<CloudAgentConfigSyncPreferences> {
|
||||
if (!value || typeof value !== 'object') {
|
||||
return {}
|
||||
}
|
||||
const raw = value as Record<string, unknown>
|
||||
return {
|
||||
...(typeof raw.autoSync === 'boolean' ? { autoSync: raw.autoSync } : {}),
|
||||
...(typeof raw.shareAcrossAgents === 'boolean'
|
||||
? { shareAcrossAgents: raw.shareAcrossAgents }
|
||||
: {})
|
||||
}
|
||||
}
|
||||
|
||||
/** Orca Cloud builds only; other builds answer null so the renderer hides the pane. */
|
||||
export function installCloudAgentConfigSync(userDataPath: string): CloudAgentConfigSync {
|
||||
instance ??= createCloudAgentConfigSync({
|
||||
userDataPath,
|
||||
broadcast: (status) => send(CLOUD_AGENT_CONFIG_SYNC_CHANGED_CHANNEL, status),
|
||||
broadcastPreferences: (preferences) =>
|
||||
send(CLOUD_AGENT_CONFIG_SYNC_PREFERENCES_CHANNEL, preferences)
|
||||
})
|
||||
return instance
|
||||
}
|
||||
|
||||
const CHANNELS = [
|
||||
'cloudAgentConfigSync:getStatus',
|
||||
'cloudAgentConfigSync:syncNow',
|
||||
'cloudAgentConfigSync:getPreferences',
|
||||
'cloudAgentConfigSync:setPreferences',
|
||||
'cloudAgentConfigSync:setItemIncluded'
|
||||
] as const
|
||||
|
||||
export function registerCloudAgentConfigSyncHandlers(): void {
|
||||
for (const channel of CHANNELS) {
|
||||
ipcMain.removeHandler(channel)
|
||||
}
|
||||
ipcMain.handle('cloudAgentConfigSync:getStatus', (_event, value: unknown) => {
|
||||
const environmentId = environmentIdOf(value)
|
||||
return environmentId && instance ? instance.getStatus(environmentId) : null
|
||||
})
|
||||
ipcMain.handle('cloudAgentConfigSync:syncNow', (_event, value: unknown) => {
|
||||
const environmentId = environmentIdOf(value)
|
||||
return environmentId && instance ? instance.sync(environmentId, 'manual') : null
|
||||
})
|
||||
ipcMain.handle('cloudAgentConfigSync:getPreferences', async () => {
|
||||
if (!instance) {
|
||||
return null
|
||||
}
|
||||
await instance.ready
|
||||
return instance.getPreferences()
|
||||
})
|
||||
ipcMain.handle('cloudAgentConfigSync:setPreferences', (_event, value: unknown) =>
|
||||
instance ? instance.setPreferences(preferencesOf(value)) : null
|
||||
)
|
||||
ipcMain.handle(
|
||||
'cloudAgentConfigSync:setItemIncluded',
|
||||
(_event, key: unknown, included: unknown) =>
|
||||
instance && typeof key === 'string' && key.length <= 300 && typeof included === 'boolean'
|
||||
? instance.setItemIncluded(key, included)
|
||||
: null
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import type {
|
||||
AgentConfigSyncStatus,
|
||||
CloudAgentConfigSyncPreferences
|
||||
} from '../../../shared/agent-config-sync/agent-config-sync-contract'
|
||||
import { gitExecFileAsync } from '../../git/command-runner/git-exec-file'
|
||||
|
||||
export const MAX_EXCLUDED = 1024
|
||||
|
||||
// Off until the user turns it on: a cloud workspace can be shared with a team, and skills are
|
||||
// the user's own prompts. One switch in Settings is the consent.
|
||||
export const DEFAULT_PREFERENCES: CloudAgentConfigSyncPreferences = {
|
||||
autoSync: false,
|
||||
shareAcrossAgents: false,
|
||||
excluded: []
|
||||
}
|
||||
|
||||
export class RuntimeCallError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly code: string | undefined
|
||||
) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
export function errorCode(error: unknown): AgentConfigSyncStatus['error'] {
|
||||
const code =
|
||||
typeof error === 'object' && error !== null && 'code' in error ? String(error.code) : ''
|
||||
if (code === 'method_not_found') {
|
||||
return 'host-outdated'
|
||||
}
|
||||
return /unavailable|timeout|unreachable/.test(code) ? 'host-unreachable' : 'failed'
|
||||
}
|
||||
|
||||
/** Repo-relative files git tracks under the project agent folders. */
|
||||
export async function trackedAgentConfigPaths(repoPath: string): Promise<ReadonlySet<string>> {
|
||||
const { stdout } = await gitExecFileAsync(
|
||||
['ls-files', '-z', '--', '.claude/skills', '.claude/commands', '.agents/skills'],
|
||||
{ cwd: repoPath, timeout: 10_000 }
|
||||
)
|
||||
return new Set(stdout.split('\0').filter(Boolean))
|
||||
}
|
||||
|
||||
export function parsePreferences(text: string): CloudAgentConfigSyncPreferences {
|
||||
const raw: unknown = JSON.parse(text)
|
||||
if (!raw || typeof raw !== 'object') {
|
||||
return { ...DEFAULT_PREFERENCES, excluded: [] }
|
||||
}
|
||||
return {
|
||||
autoSync: 'autoSync' in raw && raw.autoSync === true,
|
||||
shareAcrossAgents: 'shareAcrossAgents' in raw && raw.shareAcrossAgents === true,
|
||||
excluded:
|
||||
'excluded' in raw && Array.isArray(raw.excluded)
|
||||
? raw.excluded
|
||||
.filter((key): key is string => typeof key === 'string' && key.length <= 300)
|
||||
.slice(0, MAX_EXCLUDED)
|
||||
: []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import {
|
||||
chmodSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync
|
||||
} from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
AGENT_CONFIG_SYNC_PLAN_METHOD,
|
||||
AGENT_CONFIG_SYNC_PUT_METHOD,
|
||||
AgentConfigSyncPlanParams,
|
||||
AgentConfigSyncPutParams,
|
||||
type AgentConfigSyncStatus
|
||||
} from '../../../shared/agent-config-sync/agent-config-sync-contract'
|
||||
import type { AgentConfigHomes } from '../agent-config-roots'
|
||||
import { planHostAgentConfigSync, putHostAgentConfig } from '../host/host-agent-config-sync'
|
||||
import { createCloudAgentConfigSync } from './cloud-agent-config-sync'
|
||||
import { readLocalAgentConfig } from './local-agent-config-read'
|
||||
|
||||
type FakeRuntime = {
|
||||
runtimeEnvironmentId: string
|
||||
recipe: { provider: string }
|
||||
repoPath: string
|
||||
status: string
|
||||
}
|
||||
const runtimes = vi.hoisted((): { list: FakeRuntime[] } => ({ list: [] }))
|
||||
vi.mock('../../../shared/ephemeral-vm-runtime-store', () => ({
|
||||
listEphemeralVmRuntimes: () => runtimes.list
|
||||
}))
|
||||
|
||||
let dir: string
|
||||
let local: AgentConfigHomes
|
||||
let host: AgentConfigHomes
|
||||
let hostProject: string
|
||||
let localRepo: string
|
||||
let calls: { method: string; params: unknown }[]
|
||||
|
||||
function put(path: string, text: string, mode?: number): void {
|
||||
mkdirSync(dirname(path), { recursive: true })
|
||||
writeFileSync(path, text)
|
||||
if (mode) {
|
||||
chmodSync(path, mode)
|
||||
}
|
||||
}
|
||||
|
||||
function homesUnder(root: string): AgentConfigHomes {
|
||||
return { home: root, claudeDir: join(root, '.claude'), codexDir: join(root, '.codex') }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), 'cloud-agent-config-'))
|
||||
local = homesUnder(join(dir, 'mac'))
|
||||
host = homesUnder(join(dir, 'vm'))
|
||||
localRepo = join(dir, 'mac-repo')
|
||||
hostProject = join(dir, 'vm-project')
|
||||
mkdirSync(localRepo, { recursive: true })
|
||||
mkdirSync(hostProject, { recursive: true })
|
||||
execFileSync('git', ['init', '-q', hostProject])
|
||||
calls = []
|
||||
runtimes.list = [
|
||||
{
|
||||
runtimeEnvironmentId: 'env-1',
|
||||
recipe: { provider: 'orca-cloud' },
|
||||
repoPath: localRepo,
|
||||
// Not running, so turning sync on doesn't start its own sync under each test.
|
||||
status: 'stopped'
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function create(patch: { outdated?: boolean } = {}) {
|
||||
const statuses: AgentConfigSyncStatus[] = []
|
||||
const hostDeps = { homes: host, projectPath: hostProject, ledgerDir: join(dir, 'vm-userdata') }
|
||||
const sync = createCloudAgentConfigSync({
|
||||
userDataPath: join(dir, 'mac-userdata'),
|
||||
broadcast: (status) => statuses.push(status),
|
||||
readLocal: (repoPath) =>
|
||||
readLocalAgentConfig({ homes: local, repoPath, trackedPaths: async () => new Set() }),
|
||||
// The wire schemas run here as they do in orcad, so the test also checks what crosses.
|
||||
call: async (_environmentId, method, params) => {
|
||||
calls.push({ method, params })
|
||||
if (patch.outdated) {
|
||||
throw Object.assign(new Error('nope'), { code: 'method_not_found' })
|
||||
}
|
||||
if (method === AGENT_CONFIG_SYNC_PLAN_METHOD) {
|
||||
return planHostAgentConfigSync(AgentConfigSyncPlanParams.parse(params), hostDeps)
|
||||
}
|
||||
if (method === AGENT_CONFIG_SYNC_PUT_METHOD) {
|
||||
return putHostAgentConfig(AgentConfigSyncPutParams.parse(params), hostDeps)
|
||||
}
|
||||
throw new Error(`unexpected ${method}`)
|
||||
},
|
||||
now: () => 1_000
|
||||
})
|
||||
mkdirSync(join(dir, 'mac-userdata'), { recursive: true })
|
||||
return { sync, statuses }
|
||||
}
|
||||
|
||||
const outcomes = (status: AgentConfigSyncStatus | null) =>
|
||||
Object.fromEntries((status?.rows ?? []).map((row) => [row.key, row.outcome ?? row.skipReason]))
|
||||
|
||||
describe('cloud agent config sync, desktop to host', () => {
|
||||
it('stays off on connect until the user turns it on, then copies skills and commands', async () => {
|
||||
put(join(local.claudeDir, 'skills', 'deploy', 'SKILL.md'), '---\nname: deploy\n---\nShip.')
|
||||
put(join(local.claudeDir, 'skills', 'deploy', 'run.sh'), '#!/bin/sh\n', 0o755)
|
||||
put(join(local.claudeDir, 'commands', 'review.md'), 'Review $ARGUMENTS')
|
||||
const { sync } = create()
|
||||
expect(await sync.sync('env-1', 'connect')).toBeNull()
|
||||
expect(calls).toEqual([])
|
||||
|
||||
sync.setPreferences({ autoSync: true })
|
||||
const status = await sync.sync('env-1', 'connect')
|
||||
expect(status?.error).toBeNull()
|
||||
expect(outcomes(status)).toEqual({
|
||||
'user:claude-skill:deploy': 'added',
|
||||
'user:claude-command:review': 'added'
|
||||
})
|
||||
expect(readFileSync(join(host.claudeDir, 'skills', 'deploy', 'SKILL.md'), 'utf8')).toContain(
|
||||
'Ship.'
|
||||
)
|
||||
expect(statSync(join(host.claudeDir, 'skills', 'deploy', 'run.sh')).mode & 0o111).not.toBe(0)
|
||||
expect(readFileSync(join(host.claudeDir, 'commands', 'review.md'), 'utf8')).toBe(
|
||||
'Review $ARGUMENTS'
|
||||
)
|
||||
})
|
||||
|
||||
it('sends nothing the host already has, updates its own copies and removes what was dropped', async () => {
|
||||
put(join(local.claudeDir, 'skills', 'a', 'SKILL.md'), 'one')
|
||||
put(join(local.claudeDir, 'skills', 'b', 'SKILL.md'), 'bee')
|
||||
const { sync } = create()
|
||||
sync.setPreferences({ autoSync: true })
|
||||
await sync.sync('env-1', 'manual')
|
||||
|
||||
calls = []
|
||||
expect(outcomes(await sync.sync('env-1', 'manual'))).toEqual({
|
||||
'user:claude-skill:a': 'unchanged',
|
||||
'user:claude-skill:b': 'unchanged'
|
||||
})
|
||||
expect(calls.map((call) => call.method)).toEqual([AGENT_CONFIG_SYNC_PLAN_METHOD])
|
||||
|
||||
put(join(local.claudeDir, 'skills', 'a', 'SKILL.md'), 'two')
|
||||
rmSync(join(local.claudeDir, 'skills', 'b'), { recursive: true })
|
||||
expect(outcomes(await sync.sync('env-1', 'manual'))).toEqual({
|
||||
'user:claude-skill:a': 'updated'
|
||||
})
|
||||
expect(readFileSync(join(host.claudeDir, 'skills', 'a', 'SKILL.md'), 'utf8')).toBe('two')
|
||||
expect(existsSync(join(host.claudeDir, 'skills', 'b'))).toBe(false)
|
||||
})
|
||||
|
||||
it('never touches items made or edited in the sandbox', async () => {
|
||||
put(join(local.claudeDir, 'skills', 'mine', 'SKILL.md'), 'from the mac')
|
||||
put(join(local.claudeDir, 'skills', 'edited', 'SKILL.md'), 'from the mac')
|
||||
put(join(host.claudeDir, 'skills', 'mine', 'SKILL.md'), 'made in the sandbox')
|
||||
const { sync } = create()
|
||||
sync.setPreferences({ autoSync: true })
|
||||
expect(outcomes(await sync.sync('env-1', 'manual'))).toEqual({
|
||||
'user:claude-skill:mine': 'kept-host',
|
||||
'user:claude-skill:edited': 'added'
|
||||
})
|
||||
put(join(host.claudeDir, 'skills', 'edited', 'SKILL.md'), 'changed in the sandbox')
|
||||
rmSync(join(local.claudeDir, 'skills', 'edited'), { recursive: true })
|
||||
await sync.sync('env-1', 'manual')
|
||||
expect(readFileSync(join(host.claudeDir, 'skills', 'mine', 'SKILL.md'), 'utf8')).toBe(
|
||||
'made in the sandbox'
|
||||
)
|
||||
expect(readFileSync(join(host.claudeDir, 'skills', 'edited', 'SKILL.md'), 'utf8')).toBe(
|
||||
'changed in the sandbox'
|
||||
)
|
||||
})
|
||||
|
||||
it('shares skills and commands across agents only when asked, keeping each agent’s own', async () => {
|
||||
put(join(local.claudeDir, 'skills', 'deploy', 'SKILL.md'), 'claude deploy')
|
||||
put(join(local.claudeDir, 'skills', 'both', 'SKILL.md'), 'claude both')
|
||||
put(join(local.home, '.agents', 'skills', 'both', 'SKILL.md'), 'codex both')
|
||||
put(join(local.home, '.agents', 'skills', 'lint', 'SKILL.md'), 'codex lint')
|
||||
put(join(local.claudeDir, 'commands', 'review.md'), 'review')
|
||||
put(join(local.claudeDir, 'commands', 'ns', 'deep.md'), 'namespaced')
|
||||
put(join(local.codexDir, 'prompts', 'fix.md'), 'fix')
|
||||
const { sync } = create()
|
||||
sync.setPreferences({ autoSync: true })
|
||||
await sync.sync('env-1', 'manual')
|
||||
expect(existsSync(join(host.home, '.agents', 'skills', 'deploy'))).toBe(false)
|
||||
|
||||
sync.setPreferences({ shareAcrossAgents: true })
|
||||
const status = await sync.sync('env-1', 'manual')
|
||||
const copies = status?.rows.filter((row) => row.convertedFrom).map((row) => row.key)
|
||||
expect(copies?.sort()).toEqual([
|
||||
'user:agents-skill:deploy',
|
||||
'user:claude-command:fix',
|
||||
'user:claude-skill:lint',
|
||||
'user:codex-prompt:review'
|
||||
])
|
||||
expect(readFileSync(join(host.home, '.agents', 'skills', 'deploy', 'SKILL.md'), 'utf8')).toBe(
|
||||
'claude deploy'
|
||||
)
|
||||
expect(readFileSync(join(host.home, '.agents', 'skills', 'both', 'SKILL.md'), 'utf8')).toBe(
|
||||
'codex both'
|
||||
)
|
||||
expect(readFileSync(join(host.codexDir, 'prompts', 'review.md'), 'utf8')).toBe('review')
|
||||
expect(readFileSync(join(host.claudeDir, 'commands', 'fix.md'), 'utf8')).toBe('fix')
|
||||
expect(existsSync(join(host.codexDir, 'prompts', 'deep.md'))).toBe(false)
|
||||
|
||||
// Turning an original off takes its copy with it.
|
||||
sync.setItemIncluded('user:claude-skill:deploy', false)
|
||||
await sync.sync('env-1', 'manual')
|
||||
expect(existsSync(join(host.claudeDir, 'skills', 'deploy'))).toBe(false)
|
||||
expect(existsSync(join(host.home, '.agents', 'skills', 'deploy'))).toBe(false)
|
||||
})
|
||||
|
||||
it('puts untracked project items in the workspace and keeps them out of its git status', async () => {
|
||||
put(join(localRepo, '.claude', 'skills', 'proj', 'SKILL.md'), 'project skill')
|
||||
const { sync } = create()
|
||||
sync.setPreferences({ autoSync: true })
|
||||
expect(outcomes(await sync.sync('env-1', 'manual'))).toEqual({
|
||||
'project:claude-skill:proj': 'added'
|
||||
})
|
||||
expect(readFileSync(join(hostProject, '.claude', 'skills', 'proj', 'SKILL.md'), 'utf8')).toBe(
|
||||
'project skill'
|
||||
)
|
||||
const exclude = readFileSync(join(hostProject, '.git', 'info', 'exclude'), 'utf8')
|
||||
expect(exclude.split('\n')).toContain('/.claude/skills/proj/')
|
||||
const porcelain = execFileSync('git', ['-C', hostProject, 'status', '--porcelain'], {
|
||||
encoding: 'utf8'
|
||||
})
|
||||
expect(porcelain).toBe('')
|
||||
})
|
||||
|
||||
it('says the sandbox is outdated when its Orca has no skill sync', async () => {
|
||||
put(join(local.claudeDir, 'skills', 'a', 'SKILL.md'), 'x')
|
||||
const { sync } = create({ outdated: true })
|
||||
const status = await sync.sync('env-1', 'manual')
|
||||
expect(status?.error).toBe('host-outdated')
|
||||
expect(status?.rows.map((row) => row.state)).toEqual(['pending'])
|
||||
})
|
||||
|
||||
it('syncs running workspaces as soon as sync is turned on', async () => {
|
||||
put(join(local.claudeDir, 'skills', 'a', 'SKILL.md'), 'x')
|
||||
runtimes.list[0].status = 'running'
|
||||
const { sync, statuses } = create()
|
||||
sync.setPreferences({ autoSync: true })
|
||||
await vi.waitFor(() =>
|
||||
expect(statuses.some((status) => status.lastSyncedAt !== null)).toBe(true)
|
||||
)
|
||||
expect(existsSync(join(host.claudeDir, 'skills', 'a', 'SKILL.md'))).toBe(true)
|
||||
})
|
||||
|
||||
it('answers null for workspaces that are not Orca Cloud', async () => {
|
||||
const { sync } = create()
|
||||
expect(await sync.getStatus('env-other')).toBeNull()
|
||||
expect(await sync.sync('env-other', 'manual')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,295 @@
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import {
|
||||
AGENT_CONFIG_SYNC_PLAN_METHOD,
|
||||
AGENT_CONFIG_SYNC_PUT_METHOD,
|
||||
AgentConfigSyncPlanResult,
|
||||
AgentConfigSyncPutResult,
|
||||
type AgentConfigSyncStatus,
|
||||
type CloudAgentConfigSyncPreferences
|
||||
} from '../../../shared/agent-config-sync/agent-config-sync-contract'
|
||||
import { listEphemeralVmRuntimes } from '../../../shared/ephemeral-vm-runtime-store'
|
||||
import { writeFileAtomically } from '../../filesystem/atomic-file-publication'
|
||||
import { callRuntimeEnvironment } from '../../ipc/runtime-environments/runtime-environment-transport-routing'
|
||||
import { defaultAgentConfigHomes } from '../agent-config-roots'
|
||||
import {
|
||||
agentConfigPutBatches,
|
||||
applyAgentConfigSyncResults,
|
||||
planAgentConfigSync
|
||||
} from './agent-config-sync-plan'
|
||||
import { readLocalAgentConfig, type LocalAgentConfigItem } from './local-agent-config-read'
|
||||
import { readOrCreateSyncerId } from './syncer-id'
|
||||
import {
|
||||
DEFAULT_PREFERENCES,
|
||||
MAX_EXCLUDED,
|
||||
RuntimeCallError,
|
||||
errorCode,
|
||||
parsePreferences,
|
||||
trackedAgentConfigPaths
|
||||
} from './cloud-agent-config-sync-support'
|
||||
|
||||
const PLAN_TIMEOUT_MS = 30_000
|
||||
const PUT_TIMEOUT_MS = 60_000
|
||||
|
||||
export type CloudAgentConfigSyncDeps = {
|
||||
userDataPath: string
|
||||
broadcast: (status: AgentConfigSyncStatus) => void
|
||||
broadcastPreferences?: (preferences: CloudAgentConfigSyncPreferences) => void
|
||||
readLocal?: (repoPath: string | null) => Promise<LocalAgentConfigItem[]>
|
||||
call?: (
|
||||
environmentId: string,
|
||||
method: string,
|
||||
params: unknown,
|
||||
timeoutMs: number
|
||||
) => Promise<unknown>
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
export type CloudAgentConfigSync = {
|
||||
isCloudEnvironment(environmentId: string): boolean
|
||||
getStatus(environmentId: string): Promise<AgentConfigSyncStatus | null>
|
||||
sync(environmentId: string, trigger: 'connect' | 'manual'): Promise<AgentConfigSyncStatus | null>
|
||||
/** Settles once saved preferences are read; getPreferences answers defaults until then. */
|
||||
ready: Promise<void>
|
||||
getPreferences(): CloudAgentConfigSyncPreferences
|
||||
setPreferences(next: Partial<CloudAgentConfigSyncPreferences>): CloudAgentConfigSyncPreferences
|
||||
setItemIncluded(key: string, included: boolean): CloudAgentConfigSyncPreferences
|
||||
}
|
||||
|
||||
/** Mirrors this computer's skills and slash commands into each Orca Cloud workspace. */
|
||||
export function createCloudAgentConfigSync(deps: CloudAgentConfigSyncDeps): CloudAgentConfigSync {
|
||||
const preferencesPath = join(deps.userDataPath, 'cloud-agent-config-sync.json')
|
||||
const statuses = new Map<string, AgentConfigSyncStatus>()
|
||||
const queues = new Map<string, Promise<unknown>>()
|
||||
const now = deps.now ?? Date.now
|
||||
const readLocal =
|
||||
deps.readLocal ??
|
||||
((repoPath) =>
|
||||
readLocalAgentConfig({
|
||||
homes: defaultAgentConfigHomes(),
|
||||
repoPath,
|
||||
trackedPaths: trackedAgentConfigPaths
|
||||
}))
|
||||
const call =
|
||||
deps.call ??
|
||||
(async (environmentId: string, method: string, params: unknown, timeoutMs: number) => {
|
||||
const response = await callRuntimeEnvironment(
|
||||
deps.userDataPath,
|
||||
environmentId,
|
||||
method,
|
||||
params,
|
||||
timeoutMs
|
||||
)
|
||||
if (response.ok) {
|
||||
return response.result
|
||||
}
|
||||
throw new RuntimeCallError(response.error.message, response.error.code)
|
||||
})
|
||||
|
||||
let preferences: CloudAgentConfigSyncPreferences | null = null
|
||||
const ready = readFile(preferencesPath, 'utf8')
|
||||
.then(parsePreferences)
|
||||
.catch(() => null)
|
||||
.then((loaded) => {
|
||||
// A change saved while this read ran wins.
|
||||
preferences ??= loaded ?? { ...DEFAULT_PREFERENCES, excluded: [] }
|
||||
})
|
||||
function getPreferences(): CloudAgentConfigSyncPreferences {
|
||||
return preferences ?? { ...DEFAULT_PREFERENCES, excluded: [] }
|
||||
}
|
||||
|
||||
function cloudRuntime(environmentId: string) {
|
||||
return listEphemeralVmRuntimes(deps.userDataPath).find(
|
||||
(runtime) =>
|
||||
runtime.runtimeEnvironmentId === environmentId && runtime.recipe?.provider === 'orca-cloud'
|
||||
)
|
||||
}
|
||||
|
||||
async function plan(environmentId: string) {
|
||||
const local = await readLocal(cloudRuntime(environmentId)?.repoPath ?? null)
|
||||
const prefs = getPreferences()
|
||||
return planAgentConfigSync({
|
||||
items: local,
|
||||
excluded: new Set(prefs.excluded),
|
||||
shareAcrossAgents: prefs.shareAcrossAgents
|
||||
})
|
||||
}
|
||||
|
||||
function publish(status: AgentConfigSyncStatus): AgentConfigSyncStatus {
|
||||
statuses.set(status.environmentId, status)
|
||||
deps.broadcast(status)
|
||||
return status
|
||||
}
|
||||
|
||||
async function run(environmentId: string): Promise<AgentConfigSyncStatus> {
|
||||
const previous = statuses.get(environmentId)
|
||||
const planned = await plan(environmentId).catch(() => null)
|
||||
if (!planned) {
|
||||
return publish({
|
||||
environmentId,
|
||||
running: false,
|
||||
lastSyncedAt: previous?.lastSyncedAt ?? null,
|
||||
error: 'failed',
|
||||
rows: previous?.rows ?? []
|
||||
})
|
||||
}
|
||||
publish({
|
||||
environmentId,
|
||||
running: true,
|
||||
lastSyncedAt: previous?.lastSyncedAt ?? null,
|
||||
error: previous?.error ?? null,
|
||||
rows: previous?.rows.length ? previous.rows : planned.rows
|
||||
})
|
||||
const syncer = await readOrCreateSyncerId(deps.userDataPath)
|
||||
try {
|
||||
const hostPlan = AgentConfigSyncPlanResult.parse(
|
||||
await call(
|
||||
environmentId,
|
||||
AGENT_CONFIG_SYNC_PLAN_METHOD,
|
||||
{
|
||||
syncer,
|
||||
items: planned.desired.map(({ scope, kind, name, digest }) => ({
|
||||
scope,
|
||||
kind,
|
||||
name,
|
||||
digest
|
||||
}))
|
||||
},
|
||||
PLAN_TIMEOUT_MS
|
||||
)
|
||||
)
|
||||
const needed = planned.desired.filter((item) => hostPlan.items[item.key] === 'needed')
|
||||
const put: AgentConfigSyncPutResult['items'] = {}
|
||||
for (const batch of agentConfigPutBatches(needed)) {
|
||||
const answer = AgentConfigSyncPutResult.parse(
|
||||
await call(
|
||||
environmentId,
|
||||
AGENT_CONFIG_SYNC_PUT_METHOD,
|
||||
{ syncer, items: batch },
|
||||
PUT_TIMEOUT_MS
|
||||
)
|
||||
)
|
||||
Object.assign(put, answer.items)
|
||||
}
|
||||
const rows = applyAgentConfigSyncResults(planned.rows, hostPlan, put)
|
||||
const synced = rows.filter((row) => row.state === 'synced').length
|
||||
console.info(
|
||||
`[cloud-agent-config-sync] ${environmentId}: ${synced} synced, ${needed.length} sent, ${hostPlan.removed} removed, ${rows.length - synced} not synced`
|
||||
)
|
||||
return publish({ environmentId, running: false, lastSyncedAt: now(), error: null, rows })
|
||||
} catch (error) {
|
||||
const code = errorCode(error)
|
||||
console.warn(`[cloud-agent-config-sync] ${environmentId}: sync failed (${code})`)
|
||||
return publish({
|
||||
environmentId,
|
||||
running: false,
|
||||
lastSyncedAt: previous?.lastSyncedAt ?? null,
|
||||
error: code,
|
||||
rows: planned.rows
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function enqueue(environmentId: string): Promise<AgentConfigSyncStatus> {
|
||||
// One sync per workspace at a time; a click during an auto-sync runs after it.
|
||||
const next = (queues.get(environmentId) ?? Promise.resolve())
|
||||
.catch(() => {})
|
||||
.then(() => run(environmentId))
|
||||
queues.set(environmentId, next)
|
||||
void next.finally(() => {
|
||||
if (queues.get(environmentId) === next) {
|
||||
queues.delete(environmentId)
|
||||
}
|
||||
})
|
||||
return next
|
||||
}
|
||||
|
||||
/** After a settings change, bring every workspace that already synced in line with it. */
|
||||
function resyncSynced(): void {
|
||||
for (const status of statuses.values()) {
|
||||
if (status.lastSyncedAt !== null && cloudRuntime(status.environmentId)) {
|
||||
void enqueue(status.environmentId).catch(() => {})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function setPreferences(
|
||||
next: Partial<CloudAgentConfigSyncPreferences>
|
||||
): CloudAgentConfigSyncPreferences {
|
||||
const current = getPreferences()
|
||||
const merged: CloudAgentConfigSyncPreferences = {
|
||||
autoSync: next.autoSync ?? current.autoSync,
|
||||
shareAcrossAgents: next.shareAcrossAgents ?? current.shareAcrossAgents,
|
||||
excluded: [...new Set(next.excluded ?? current.excluded)].sort().slice(0, MAX_EXCLUDED)
|
||||
}
|
||||
writeFileAtomically(preferencesPath, `${JSON.stringify(merged, null, 2)}\n`)
|
||||
preferences = merged
|
||||
deps.broadcastPreferences?.(merged)
|
||||
return merged
|
||||
}
|
||||
|
||||
return {
|
||||
ready,
|
||||
isCloudEnvironment: (environmentId) => cloudRuntime(environmentId) !== undefined,
|
||||
async getStatus(environmentId) {
|
||||
await ready
|
||||
if (!cloudRuntime(environmentId)) {
|
||||
return null
|
||||
}
|
||||
const known = statuses.get(environmentId)
|
||||
if (known) {
|
||||
return known
|
||||
}
|
||||
// Before any sync: what would go, read from this computer only.
|
||||
const planned = await plan(environmentId).catch(() => null)
|
||||
return {
|
||||
environmentId,
|
||||
running: false,
|
||||
lastSyncedAt: null,
|
||||
error: planned ? null : 'failed',
|
||||
rows: planned?.rows ?? []
|
||||
}
|
||||
},
|
||||
async sync(environmentId, trigger) {
|
||||
await ready
|
||||
if (!cloudRuntime(environmentId)) {
|
||||
return null
|
||||
}
|
||||
if (trigger === 'connect' && !getPreferences().autoSync) {
|
||||
return statuses.get(environmentId) ?? null
|
||||
}
|
||||
return enqueue(environmentId)
|
||||
},
|
||||
getPreferences,
|
||||
setPreferences(next) {
|
||||
const before = getPreferences()
|
||||
const merged = setPreferences(next)
|
||||
// Turning sync on reaches the running workspaces now, not at their next wake.
|
||||
if (merged.autoSync && !before.autoSync) {
|
||||
for (const runtime of listEphemeralVmRuntimes(deps.userDataPath)) {
|
||||
if (
|
||||
runtime.recipe?.provider === 'orca-cloud' &&
|
||||
runtime.status === 'running' &&
|
||||
runtime.runtimeEnvironmentId
|
||||
) {
|
||||
void enqueue(runtime.runtimeEnvironmentId).catch(() => {})
|
||||
}
|
||||
}
|
||||
} else if (merged.shareAcrossAgents !== before.shareAcrossAgents) {
|
||||
resyncSynced()
|
||||
}
|
||||
return merged
|
||||
},
|
||||
setItemIncluded(key, included) {
|
||||
const excluded = new Set(getPreferences().excluded)
|
||||
if (included) {
|
||||
excluded.delete(key)
|
||||
} else {
|
||||
excluded.add(key)
|
||||
}
|
||||
const merged = setPreferences({ excluded: [...excluded] })
|
||||
resyncSynced()
|
||||
return merged
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import type { AgentConfigHomes } from '../agent-config-roots'
|
||||
import { readLocalAgentConfig } from './local-agent-config-read'
|
||||
|
||||
let dir: string
|
||||
let homes: AgentConfigHomes
|
||||
|
||||
function put(path: string, text: string | Buffer, mode?: number): void {
|
||||
mkdirSync(dirname(path), { recursive: true })
|
||||
writeFileSync(path, text)
|
||||
if (mode) {
|
||||
chmodSync(path, mode)
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), 'agent-config-read-'))
|
||||
homes = {
|
||||
home: join(dir, 'home'),
|
||||
claudeDir: join(dir, 'home', '.claude'),
|
||||
codexDir: join(dir, 'home', '.codex')
|
||||
}
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
const read = (repoPath: string | null = null, tracked: string[] | null = []) =>
|
||||
readLocalAgentConfig({
|
||||
homes,
|
||||
repoPath,
|
||||
trackedPaths: async () => (tracked ? new Set(tracked) : null)
|
||||
})
|
||||
|
||||
describe('readLocalAgentConfig', () => {
|
||||
it('reads skills with their files and keeps likely secrets on this computer', async () => {
|
||||
const skill = join(homes.claudeDir, 'skills', 'deploy')
|
||||
put(join(skill, 'SKILL.md'), '---\nname: deploy\n---\nShip it.')
|
||||
put(join(skill, 'scripts', 'run.sh'), '#!/bin/sh\necho hi\n', 0o755)
|
||||
put(join(skill, 'service-account.json'), '{}')
|
||||
put(join(skill, 'notes.txt'), 'token: ghp_0123456789abcdefghijABCDEFGHIJ0123456789')
|
||||
put(join(skill, '.env'), 'X=1')
|
||||
put(join(skill, 'node_modules', 'x', 'index.js'), 'x')
|
||||
// Not a skill: no SKILL.md.
|
||||
put(join(homes.claudeDir, 'skills', 'synced', 'blob.bin'), 'x')
|
||||
// A link out of the skill folder is not followed.
|
||||
put(join(dir, 'outside.txt'), 'outside')
|
||||
symlinkSync(join(dir, 'outside.txt'), join(skill, 'link.txt'))
|
||||
|
||||
const items = await read()
|
||||
expect(items).toHaveLength(1)
|
||||
const [item] = items
|
||||
expect(item).toMatchObject({
|
||||
scope: 'user',
|
||||
kind: 'claude-skill',
|
||||
name: 'deploy',
|
||||
withheldFiles: 2
|
||||
})
|
||||
expect(item.skipReason).toBeUndefined()
|
||||
expect(item.files.map((file) => [file.path, file.executable])).toEqual([
|
||||
['SKILL.md', false],
|
||||
['scripts/run.sh', true]
|
||||
])
|
||||
expect(item.digest).toMatch(/^[a-f0-9]{64}$/)
|
||||
})
|
||||
|
||||
it('skips a skill whose SKILL.md holds a key, and one that is too large', async () => {
|
||||
put(
|
||||
join(homes.claudeDir, 'skills', 'leaky', 'SKILL.md'),
|
||||
'Use sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789'
|
||||
)
|
||||
put(join(homes.claudeDir, 'skills', 'huge', 'SKILL.md'), 'x')
|
||||
put(join(homes.claudeDir, 'skills', 'huge', 'data.bin'), Buffer.alloc(300 * 1024))
|
||||
const items = await read()
|
||||
expect(Object.fromEntries(items.map((item) => [item.name, item.skipReason]))).toEqual({
|
||||
leaky: 'secret',
|
||||
huge: 'too-large'
|
||||
})
|
||||
expect(items.every((item) => item.files.length === 0)).toBe(true)
|
||||
})
|
||||
|
||||
it('reads namespaced Claude commands, flat Codex prompts, and both Codex skill folders', async () => {
|
||||
put(join(homes.claudeDir, 'commands', 'review.md'), 'Review $ARGUMENTS')
|
||||
put(join(homes.claudeDir, 'commands', 'frontend', 'component.md'), 'Make a component')
|
||||
put(join(homes.claudeDir, 'commands', 'README.txt'), 'not a command')
|
||||
put(join(homes.codexDir, 'prompts', 'fix.md'), 'Fix it')
|
||||
put(join(homes.codexDir, 'prompts', 'nested', 'ignored.md'), 'Codex prompts are flat')
|
||||
put(join(homes.home, '.agents', 'skills', 'lint', 'SKILL.md'), 'Lint')
|
||||
put(join(homes.codexDir, 'skills', '.system', 'builtin', 'SKILL.md'), 'Codex own')
|
||||
put(join(homes.codexDir, 'skills', 'legacy', 'SKILL.md'), 'Old home')
|
||||
const items = await read()
|
||||
expect(items.map((item) => `${item.kind}:${item.name}`).sort()).toEqual([
|
||||
'agents-skill:lint',
|
||||
'claude-command:frontend/component',
|
||||
'claude-command:review',
|
||||
'codex-prompt:fix',
|
||||
'codex-skill:legacy'
|
||||
])
|
||||
const review = items.find((item) => item.name === 'review')
|
||||
expect(review?.files).toEqual([
|
||||
{ path: '.', executable: false, bytes: Buffer.from('Review $ARGUMENTS') }
|
||||
])
|
||||
})
|
||||
|
||||
it('sends project items git does not track, and marks committed ones as already in the repo', async () => {
|
||||
const repo = join(dir, 'repo')
|
||||
put(join(repo, '.claude', 'skills', 'committed', 'SKILL.md'), 'in git')
|
||||
put(join(repo, '.claude', 'skills', 'local-only', 'SKILL.md'), 'not in git')
|
||||
put(join(repo, '.claude', 'commands', 'ship.md'), 'in git')
|
||||
put(join(repo, '.claude', 'commands', 'mine.md'), 'not in git')
|
||||
const items = await read(repo, [
|
||||
'.claude/skills/committed/SKILL.md',
|
||||
'.claude/commands/ship.md'
|
||||
])
|
||||
expect(
|
||||
Object.fromEntries(
|
||||
items.map((item) => [`${item.scope}:${item.name}`, item.skipReason ?? 'send'])
|
||||
)
|
||||
).toEqual({
|
||||
'project:committed': 'in-repo',
|
||||
'project:local-only': 'send',
|
||||
'project:ship': 'in-repo',
|
||||
'project:mine': 'send'
|
||||
})
|
||||
})
|
||||
|
||||
it('treats project items as committed when git cannot answer', async () => {
|
||||
const repo = join(dir, 'repo')
|
||||
put(join(repo, '.claude', 'skills', 'a', 'SKILL.md'), 'x')
|
||||
const items = await read(repo, null)
|
||||
expect(items.map((item) => item.skipReason)).toEqual(['in-repo'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,314 @@
|
||||
import { lstat, readFile, readdir, realpath, stat } from 'node:fs/promises'
|
||||
import { join, relative, sep } from 'node:path'
|
||||
import {
|
||||
AGENT_CONFIG_COMMAND_NAME,
|
||||
AGENT_CONFIG_FILE_PATH,
|
||||
AGENT_CONFIG_LIMITS,
|
||||
AGENT_CONFIG_PROJECT_KINDS,
|
||||
AGENT_CONFIG_SELF_PATH,
|
||||
AGENT_CONFIG_SKILL_NAME,
|
||||
AgentConfigItemKind,
|
||||
isSkillKind,
|
||||
type AgentConfigItemScope,
|
||||
type AgentConfigSkipReason
|
||||
} from '../../../shared/agent-config-sync/agent-config-sync-contract'
|
||||
import { agentConfigDigest, type AgentConfigDigestEntry } from '../agent-config-digest'
|
||||
import { agentConfigRoot, type AgentConfigHomes } from '../agent-config-roots'
|
||||
import { hasSecretContent, isSecretFileName } from './agent-config-secret-scan'
|
||||
|
||||
export type LocalAgentConfigItem = {
|
||||
scope: AgentConfigItemScope
|
||||
kind: AgentConfigItemKind
|
||||
name: string
|
||||
/** Empty when skipped. */
|
||||
files: AgentConfigDigestEntry[]
|
||||
fileCount: number
|
||||
bytes: number
|
||||
withheldFiles: number
|
||||
digest: string | null
|
||||
skipReason?: Extract<AgentConfigSkipReason, 'in-repo' | 'too-large' | 'secret' | 'invalid'>
|
||||
}
|
||||
|
||||
export type LocalAgentConfigReadDeps = {
|
||||
homes: AgentConfigHomes
|
||||
/** The workspace's checkout on this computer, for project items. */
|
||||
repoPath: string | null
|
||||
/** Repo-relative paths git tracks under the project agent folders; null when git can't say. */
|
||||
trackedPaths: (repoPath: string) => Promise<ReadonlySet<string> | null>
|
||||
}
|
||||
|
||||
/** Folders a skill never needs in the sandbox. */
|
||||
const SKIPPED_DIRS = new Set(['node_modules', '__pycache__', 'venv'])
|
||||
const MAX_DEPTH = 8
|
||||
const SKILL_FILE = 'SKILL.md'
|
||||
|
||||
type Walked =
|
||||
| { ok: true; files: AgentConfigDigestEntry[]; withheld: number; bytes: number }
|
||||
| { ok: false; reason: 'too-large' | 'secret' | 'invalid' }
|
||||
|
||||
async function isExecutable(path: string): Promise<boolean> {
|
||||
try {
|
||||
return ((await stat(path)).mode & 0o111) !== 0
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** One file's verdict: kept, kept back as a likely secret, or too big for any skill. */
|
||||
async function readItemFile(
|
||||
path: string,
|
||||
name: string
|
||||
): Promise<'too-large' | 'withheld' | { bytes: Buffer; executable: boolean }> {
|
||||
const info = await stat(path)
|
||||
if (info.size > AGENT_CONFIG_LIMITS.fileBytes) {
|
||||
return 'too-large'
|
||||
}
|
||||
if (isSecretFileName(name)) {
|
||||
return 'withheld'
|
||||
}
|
||||
const bytes = await readFile(path)
|
||||
if (hasSecretContent(bytes)) {
|
||||
return 'withheld'
|
||||
}
|
||||
return { bytes, executable: await isExecutable(path) }
|
||||
}
|
||||
|
||||
/** Every regular file in a skill folder; symlinks only when they stay inside it. */
|
||||
async function walkSkill(dir: string): Promise<Walked> {
|
||||
const root = await realpath(dir)
|
||||
const files: AgentConfigDigestEntry[] = []
|
||||
let withheld = 0
|
||||
let bytes = 0
|
||||
const visit = async (current: string, depth: number): Promise<Walked | null> => {
|
||||
const entries = await readdir(current, { withFileTypes: true })
|
||||
entries.sort((a, b) => (a.name < b.name ? -1 : 1))
|
||||
for (const entry of entries) {
|
||||
if (entry.name.startsWith('.') || SKIPPED_DIRS.has(entry.name)) {
|
||||
continue
|
||||
}
|
||||
const path = join(current, entry.name)
|
||||
let resolved = path
|
||||
if (entry.isSymbolicLink()) {
|
||||
try {
|
||||
resolved = await realpath(path)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
if (resolved !== root && !resolved.startsWith(root + sep)) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
const info = await stat(resolved).catch(() => null)
|
||||
if (!info) {
|
||||
continue
|
||||
}
|
||||
const rel = relative(dir, path).split(sep).join('/')
|
||||
if (info.isDirectory()) {
|
||||
if (depth >= MAX_DEPTH) {
|
||||
continue
|
||||
}
|
||||
const nested = await visit(path, depth + 1)
|
||||
if (nested) {
|
||||
return nested
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (!info.isFile()) {
|
||||
continue
|
||||
}
|
||||
if (!AGENT_CONFIG_FILE_PATH.test(rel)) {
|
||||
return { ok: false, reason: 'invalid' }
|
||||
}
|
||||
const read = await readItemFile(resolved, entry.name)
|
||||
if (read === 'too-large') {
|
||||
return { ok: false, reason: 'too-large' }
|
||||
}
|
||||
if (read === 'withheld') {
|
||||
if (rel === SKILL_FILE) {
|
||||
return { ok: false, reason: 'secret' }
|
||||
}
|
||||
withheld += 1
|
||||
continue
|
||||
}
|
||||
bytes += read.bytes.length
|
||||
files.push({ path: rel, executable: read.executable, bytes: read.bytes })
|
||||
if (
|
||||
files.length > AGENT_CONFIG_LIMITS.filesPerItem ||
|
||||
bytes > AGENT_CONFIG_LIMITS.itemBytes
|
||||
) {
|
||||
return { ok: false, reason: 'too-large' }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
const failed = await visit(dir, 0)
|
||||
return failed ?? { ok: true, files, withheld, bytes }
|
||||
}
|
||||
|
||||
async function isDirectory(path: string): Promise<boolean> {
|
||||
return (await stat(path).catch(() => null))?.isDirectory() === true
|
||||
}
|
||||
|
||||
async function isFile(path: string): Promise<boolean> {
|
||||
return (await stat(path).catch(() => null))?.isFile() === true
|
||||
}
|
||||
|
||||
async function readSkills(
|
||||
root: string,
|
||||
kind: AgentConfigItemKind,
|
||||
scope: AgentConfigItemScope
|
||||
): Promise<LocalAgentConfigItem[]> {
|
||||
const entries = await readdir(root, { withFileTypes: true }).catch(() => [])
|
||||
const items: LocalAgentConfigItem[] = []
|
||||
for (const entry of entries) {
|
||||
const dir = join(root, entry.name)
|
||||
// Hidden folders hold tool state (Codex's .system skills, trash), not the user's skills.
|
||||
if (entry.name.startsWith('.') || !(await isDirectory(dir))) {
|
||||
continue
|
||||
}
|
||||
if (!(await isFile(join(dir, SKILL_FILE)))) {
|
||||
continue
|
||||
}
|
||||
const base = { scope, kind, name: entry.name, withheldFiles: 0 }
|
||||
if (!AGENT_CONFIG_SKILL_NAME.test(entry.name)) {
|
||||
items.push({
|
||||
...base,
|
||||
files: [],
|
||||
fileCount: 0,
|
||||
bytes: 0,
|
||||
digest: null,
|
||||
skipReason: 'invalid'
|
||||
})
|
||||
continue
|
||||
}
|
||||
const walked = await walkSkill(dir).catch((): Walked => ({ ok: false, reason: 'invalid' }))
|
||||
if (!walked.ok) {
|
||||
items.push({
|
||||
...base,
|
||||
files: [],
|
||||
fileCount: 0,
|
||||
bytes: 0,
|
||||
digest: null,
|
||||
skipReason: walked.reason
|
||||
})
|
||||
continue
|
||||
}
|
||||
items.push({
|
||||
...base,
|
||||
files: walked.files,
|
||||
fileCount: walked.files.length,
|
||||
bytes: walked.bytes,
|
||||
withheldFiles: walked.withheld,
|
||||
digest: agentConfigDigest(walked.files)
|
||||
})
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
/** Markdown commands, namespaced by folder (Claude) or flat (Codex prompts). */
|
||||
async function readCommands(
|
||||
root: string,
|
||||
kind: AgentConfigItemKind,
|
||||
scope: AgentConfigItemScope
|
||||
): Promise<LocalAgentConfigItem[]> {
|
||||
const maxDepth = kind === 'codex-prompt' ? 0 : 2
|
||||
const items: LocalAgentConfigItem[] = []
|
||||
const visit = async (dir: string, depth: number): Promise<void> => {
|
||||
const entries = await readdir(dir, { withFileTypes: true }).catch(() => [])
|
||||
for (const entry of entries) {
|
||||
if (entry.name.startsWith('.')) {
|
||||
continue
|
||||
}
|
||||
const path = join(dir, entry.name)
|
||||
const info = await stat(path).catch(() => null)
|
||||
if (info?.isDirectory()) {
|
||||
if (depth < maxDepth) {
|
||||
await visit(path, depth + 1)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (!info?.isFile() || !entry.name.endsWith('.md')) {
|
||||
continue
|
||||
}
|
||||
const name = relative(root, path).split(sep).join('/').slice(0, -'.md'.length)
|
||||
const base = { scope, kind, name, withheldFiles: 0, fileCount: 1 }
|
||||
const skipped = (
|
||||
skipReason: NonNullable<LocalAgentConfigItem['skipReason']>
|
||||
): LocalAgentConfigItem => ({
|
||||
...base,
|
||||
files: [],
|
||||
bytes: info.size,
|
||||
digest: null,
|
||||
skipReason
|
||||
})
|
||||
if (!AGENT_CONFIG_COMMAND_NAME.test(name)) {
|
||||
items.push(skipped('invalid'))
|
||||
continue
|
||||
}
|
||||
const read = await readItemFile(path, entry.name).catch(() => 'invalid' as const)
|
||||
if (read === 'too-large' || read === 'invalid') {
|
||||
items.push(skipped(read))
|
||||
continue
|
||||
}
|
||||
if (read === 'withheld') {
|
||||
items.push(skipped('secret'))
|
||||
continue
|
||||
}
|
||||
const files = [
|
||||
{ path: AGENT_CONFIG_SELF_PATH, executable: false, bytes: read.bytes } // commands are never run
|
||||
]
|
||||
items.push({ ...base, files, bytes: read.bytes.length, digest: agentConfigDigest(files) })
|
||||
}
|
||||
}
|
||||
await visit(root, 0)
|
||||
return items
|
||||
}
|
||||
|
||||
/** Repo-relative path of an item, as `git ls-files` prints it. */
|
||||
function repoRelative(repoPath: string, root: string, kind: AgentConfigItemKind, name: string) {
|
||||
const rel = relative(repoPath, root).split(sep).join('/')
|
||||
return isSkillKind(kind) ? `${rel}/${name}/` : `${rel}/${name}.md`
|
||||
}
|
||||
|
||||
/** This computer's Claude Code and Codex skills and commands, user scope and the workspace's project. */
|
||||
export async function readLocalAgentConfig(
|
||||
deps: LocalAgentConfigReadDeps
|
||||
): Promise<LocalAgentConfigItem[]> {
|
||||
const items: LocalAgentConfigItem[] = []
|
||||
for (const kind of AgentConfigItemKind.options) {
|
||||
const root = agentConfigRoot(kind, 'user', deps.homes, null)
|
||||
if (root) {
|
||||
items.push(...(await (isSkillKind(kind) ? readSkills : readCommands)(root, kind, 'user')))
|
||||
}
|
||||
}
|
||||
const repoPath = deps.repoPath
|
||||
if (repoPath) {
|
||||
const tracked = await deps.trackedPaths(repoPath).catch(() => null)
|
||||
for (const kind of AgentConfigItemKind.options) {
|
||||
const root = AGENT_CONFIG_PROJECT_KINDS.has(kind)
|
||||
? agentConfigRoot(kind, 'project', deps.homes, repoPath)
|
||||
: null
|
||||
// A project folder that is a link elsewhere is not the repo's; leave it alone.
|
||||
if (!root || (await lstat(root).catch(() => null))?.isSymbolicLink()) {
|
||||
continue
|
||||
}
|
||||
for (const item of await (isSkillKind(kind) ? readSkills : readCommands)(
|
||||
root,
|
||||
kind,
|
||||
'project'
|
||||
)) {
|
||||
const path = repoRelative(repoPath, root, kind, item.name)
|
||||
// Committed items reach the sandbox with the clone; unknown means assume committed.
|
||||
const inRepo =
|
||||
tracked === null ||
|
||||
[...tracked].some((file) => (isSkillKind(kind) ? file.startsWith(path) : file === path))
|
||||
items.push(
|
||||
inRepo && !item.skipReason
|
||||
? { ...item, files: [], digest: null, skipReason: 'in-repo' }
|
||||
: item
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { writeFileAtomically } from '../../filesystem/atomic-file-publication'
|
||||
|
||||
// One read per profile; concurrent first syncs share it, so they can't mint two ids.
|
||||
const cache = new Map<string, Promise<string>>()
|
||||
|
||||
async function load(userDataPath: string): Promise<string> {
|
||||
const path = join(userDataPath, 'mcp-sync-syncer-id')
|
||||
try {
|
||||
const stored = (await readFile(path, 'utf8')).trim()
|
||||
if (/^[a-f0-9]{16}$/.test(stored)) {
|
||||
return stored
|
||||
}
|
||||
} catch {
|
||||
// First sync from this computer.
|
||||
}
|
||||
const id = randomBytes(8).toString('hex')
|
||||
try {
|
||||
writeFileAtomically(path, `${id}\n`)
|
||||
} catch {
|
||||
// Unwritable profile: this run still syncs as itself; the next launch gets a new id.
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
/** This computer's stable sync identity (random, not a device fingerprint). The host keeps one
|
||||
* ledger per syncer, so two computers syncing one sandbox never remove each other's items. */
|
||||
export function readOrCreateSyncerId(userDataPath: string): Promise<string> {
|
||||
let id = cache.get(userDataPath)
|
||||
if (!id) {
|
||||
id = load(userDataPath)
|
||||
cache.set(userDataPath, id)
|
||||
}
|
||||
return id
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { runProcess } from '@orca/process-host'
|
||||
import { appendFile, mkdir, readFile } from 'node:fs/promises'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { writeFileAtomically } from '../../filesystem/atomic-file-publication'
|
||||
|
||||
/** What this host last wrote for one syncing computer: item key -> digest. Never contents. */
|
||||
export type Ledger = { version: 1; items: Record<string, string> }
|
||||
|
||||
export function ledgerPath(ledgerDir: string, syncer: string): string {
|
||||
return join(ledgerDir, `agent-config-sync-ledger-${syncer}.json`)
|
||||
}
|
||||
|
||||
export async function readLedger(path: string): Promise<Ledger> {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(await readFile(path, 'utf8'))
|
||||
const items =
|
||||
parsed && typeof parsed === 'object' && 'items' in parsed ? parsed.items : undefined
|
||||
const clean: Record<string, string> = {}
|
||||
if (items && typeof items === 'object') {
|
||||
for (const [key, value] of Object.entries(items)) {
|
||||
if (typeof value === 'string' && /^[a-f0-9]{64}$/.test(value)) {
|
||||
clean[key] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
return { version: 1, items: clean }
|
||||
} catch {
|
||||
return { version: 1, items: {} }
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeLedger(path: string, ledger: Ledger): Promise<void> {
|
||||
await mkdir(dirname(path), { recursive: true })
|
||||
writeFileAtomically(path, `${JSON.stringify(ledger, null, 2)}\n`, { mode: 0o600 })
|
||||
}
|
||||
|
||||
/** Keeps a synced project item out of the sandbox's git status (local exclude, never committed). */
|
||||
export async function excludeFromGit(
|
||||
projectPath: string,
|
||||
dest: string,
|
||||
isDir: boolean
|
||||
): Promise<void> {
|
||||
try {
|
||||
const { code, stdout } = await runProcess({
|
||||
program: 'git',
|
||||
args: [
|
||||
'-C',
|
||||
projectPath,
|
||||
'rev-parse',
|
||||
'--path-format=absolute',
|
||||
'--git-path',
|
||||
'info/exclude'
|
||||
],
|
||||
timeoutMs: 5_000
|
||||
})
|
||||
if (code !== 0) {
|
||||
return
|
||||
}
|
||||
const excludePath = stdout.trim()
|
||||
if (!excludePath) {
|
||||
return
|
||||
}
|
||||
const rel = dest.slice(projectPath.length).split('\\').join('/')
|
||||
const line = `${rel.startsWith('/') ? rel : `/${rel}`}${isDir ? '/' : ''}`
|
||||
const current = await readFile(excludePath, 'utf8').catch(() => '')
|
||||
if (current.split('\n').includes(line)) {
|
||||
return
|
||||
}
|
||||
await mkdir(dirname(excludePath), { recursive: true })
|
||||
await appendFile(excludePath, `${current && !current.endsWith('\n') ? '\n' : ''}${line}\n`)
|
||||
} catch {
|
||||
// Not a git checkout here; the item still works, it just shows as untracked.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
AgentConfigSyncPlanParams,
|
||||
AgentConfigSyncPutParams
|
||||
} from '../../../shared/agent-config-sync/agent-config-sync-contract'
|
||||
import { agentConfigDigest } from '../agent-config-digest'
|
||||
import {
|
||||
planHostAgentConfigSync,
|
||||
putHostAgentConfig,
|
||||
type HostAgentConfigSyncDeps
|
||||
} from './host-agent-config-sync'
|
||||
|
||||
let dir: string
|
||||
let deps: HostAgentConfigSyncDeps
|
||||
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), 'host-agent-config-'))
|
||||
deps = {
|
||||
homes: { home: dir, claudeDir: join(dir, '.claude'), codexDir: join(dir, '.codex') },
|
||||
projectPath: null,
|
||||
ledgerDir: join(dir, 'userData')
|
||||
}
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
const skillFiles = [{ path: 'SKILL.md', executable: false, bytes: Buffer.from('hello') }]
|
||||
const digest = agentConfigDigest(skillFiles)
|
||||
const payload = (patch: Record<string, unknown> = {}) => ({
|
||||
scope: 'user' as const,
|
||||
kind: 'claude-skill' as const,
|
||||
name: 'hello',
|
||||
digest,
|
||||
files: [{ path: 'SKILL.md', executable: false, base64: Buffer.from('hello').toString('base64') }],
|
||||
...patch
|
||||
})
|
||||
|
||||
describe('host agent config sync', () => {
|
||||
it('rejects names and paths that could leave the agent folders', () => {
|
||||
for (const name of ['../x', '.hidden', 'a/b', '']) {
|
||||
expect(
|
||||
AgentConfigSyncPlanParams.safeParse({
|
||||
syncer: 's',
|
||||
items: [{ scope: 'user', kind: 'claude-skill', name, digest }]
|
||||
}).success
|
||||
).toBe(false)
|
||||
}
|
||||
for (const path of ['../SKILL.md', '/etc/passwd', 'a/../../b', '.git/config']) {
|
||||
expect(
|
||||
AgentConfigSyncPutParams.safeParse({
|
||||
syncer: 's',
|
||||
items: [payload({ files: [{ path, executable: false, base64: '' }] })]
|
||||
}).success
|
||||
).toBe(false)
|
||||
}
|
||||
// Codex prompts and old Codex skills have no project scope.
|
||||
expect(
|
||||
AgentConfigSyncPlanParams.safeParse({
|
||||
syncer: 's',
|
||||
items: [{ scope: 'project', kind: 'codex-prompt', name: 'x', digest }]
|
||||
}).success
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('refuses a payload that does not match its digest or lacks SKILL.md', async () => {
|
||||
const result = await putHostAgentConfig(
|
||||
{
|
||||
syncer: 's',
|
||||
items: [
|
||||
payload({ digest: '0'.repeat(64) }),
|
||||
payload({
|
||||
name: 'nomain',
|
||||
digest: agentConfigDigest([
|
||||
{ path: 'other.md', executable: false, bytes: Buffer.from('x') }
|
||||
]),
|
||||
files: [
|
||||
{ path: 'other.md', executable: false, base64: Buffer.from('x').toString('base64') }
|
||||
]
|
||||
})
|
||||
]
|
||||
},
|
||||
deps
|
||||
)
|
||||
expect(result.items).toEqual({
|
||||
'user:claude-skill:hello': 'invalid',
|
||||
'user:claude-skill:nomain': 'invalid'
|
||||
})
|
||||
expect(existsSync(join(dir, '.claude', 'skills'))).toBe(false)
|
||||
})
|
||||
|
||||
it('leaves a symlinked skill alone and keeps project items out without a workspace', async () => {
|
||||
mkdirSync(join(dir, '.claude', 'skills'), { recursive: true })
|
||||
mkdirSync(join(dir, 'elsewhere'))
|
||||
symlinkSync(join(dir, 'elsewhere'), join(dir, '.claude', 'skills', 'hello'))
|
||||
const plan = await planHostAgentConfigSync(
|
||||
{
|
||||
syncer: 's',
|
||||
items: [
|
||||
{ scope: 'user', kind: 'claude-skill', name: 'hello', digest },
|
||||
{ scope: 'project', kind: 'claude-skill', name: 'proj', digest }
|
||||
]
|
||||
},
|
||||
deps
|
||||
)
|
||||
expect(plan.items).toEqual({
|
||||
'user:claude-skill:hello': 'kept-host',
|
||||
'project:claude-skill:proj': 'no-project'
|
||||
})
|
||||
})
|
||||
|
||||
it('ignores ledger entries that do not name a valid item', async () => {
|
||||
mkdirSync(deps.ledgerDir, { recursive: true })
|
||||
writeFileSync(
|
||||
join(deps.ledgerDir, 'agent-config-sync-ledger-s.json'),
|
||||
JSON.stringify({ version: 1, items: { 'user:claude-skill:../../victim': digest } })
|
||||
)
|
||||
mkdirSync(join(dir, 'victim'))
|
||||
writeFileSync(join(dir, 'victim', 'SKILL.md'), 'hello')
|
||||
const plan = await planHostAgentConfigSync({ syncer: 's', items: [] }, deps)
|
||||
expect(plan.removed).toBe(0)
|
||||
expect(existsSync(join(dir, 'victim', 'SKILL.md'))).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps each computer’s items separate', async () => {
|
||||
await planHostAgentConfigSync(
|
||||
{ syncer: 'mac-a', items: [{ scope: 'user', kind: 'claude-skill', name: 'hello', digest }] },
|
||||
deps
|
||||
)
|
||||
await putHostAgentConfig({ syncer: 'mac-a', items: [payload()] }, deps)
|
||||
// Another computer that never sent it doesn't remove it.
|
||||
const other = await planHostAgentConfigSync({ syncer: 'mac-b', items: [] }, deps)
|
||||
expect(other.removed).toBe(0)
|
||||
expect(existsSync(join(dir, '.claude', 'skills', 'hello', 'SKILL.md'))).toBe(true)
|
||||
const own = await planHostAgentConfigSync({ syncer: 'mac-a', items: [] }, deps)
|
||||
expect(own.removed).toBe(1)
|
||||
expect(existsSync(join(dir, '.claude', 'skills', 'hello'))).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,273 @@
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import { lstat, mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises'
|
||||
import { dirname, isAbsolute, join, resolve } from 'node:path'
|
||||
import {
|
||||
AGENT_CONFIG_FILE_KINDS,
|
||||
AGENT_CONFIG_LIMITS,
|
||||
AGENT_CONFIG_SELF_PATH,
|
||||
AgentConfigItemKind,
|
||||
AgentConfigItemScope,
|
||||
AgentConfigSyncPlanParams,
|
||||
agentConfigItemKey,
|
||||
isSkillKind,
|
||||
type AgentConfigItemPayload,
|
||||
type AgentConfigPlanOutcome,
|
||||
type AgentConfigPutOutcome,
|
||||
type AgentConfigSyncPlanResult,
|
||||
type AgentConfigSyncPutParams,
|
||||
type AgentConfigSyncPutResult
|
||||
} from '../../../shared/agent-config-sync/agent-config-sync-contract'
|
||||
import { writeFileAtomically } from '../../filesystem/atomic-file-publication'
|
||||
import { excludeFromGit, ledgerPath, readLedger, writeLedger } from './host-agent-config-ledger'
|
||||
import { agentConfigDigest, type AgentConfigDigestEntry } from '../agent-config-digest'
|
||||
import { agentConfigItemPath, agentConfigRoot, type AgentConfigHomes } from '../agent-config-roots'
|
||||
|
||||
export type HostAgentConfigSyncDeps = {
|
||||
homes: AgentConfigHomes
|
||||
/** The host workspace's checkout (ORCA_WORKSPACE_PATH); project items go there. */
|
||||
projectPath: string | null
|
||||
/** Folder for this host's per-computer ledgers. */
|
||||
ledgerDir: string
|
||||
}
|
||||
|
||||
type ItemId = { scope: AgentConfigItemScope; kind: AgentConfigItemKind; name: string }
|
||||
|
||||
function parseKey(key: string): ItemId | null {
|
||||
const [scope, kind, ...rest] = key.split(':')
|
||||
const parsedScope = AgentConfigItemScope.safeParse(scope)
|
||||
const parsedKind = AgentConfigItemKind.safeParse(kind)
|
||||
const name = rest.join(':')
|
||||
if (!parsedScope.success || !parsedKind.success || !name) {
|
||||
return null
|
||||
}
|
||||
// Same checks as a fresh request, so a tampered ledger can't name a path outside the roots.
|
||||
const checked = AgentConfigSyncPlanParams.safeParse({
|
||||
syncer: 'ledger',
|
||||
items: [{ scope, kind, name, digest: '0'.repeat(64) }]
|
||||
})
|
||||
return checked.success ? { scope: parsedScope.data, kind: parsedKind.data, name } : null
|
||||
}
|
||||
|
||||
function destinationOf(item: ItemId, deps: HostAgentConfigSyncDeps): string | null {
|
||||
const root = agentConfigRoot(item.kind, item.scope, deps.homes, deps.projectPath)
|
||||
return root ? agentConfigItemPath(root, item.kind, item.name) : null
|
||||
}
|
||||
|
||||
/** Digest of what is on disk now: null when absent, 'foreign' for anything not a plain copy. */
|
||||
async function digestOnDisk(path: string, kind: AgentConfigItemKind): Promise<string | null> {
|
||||
const info = await lstat(path).catch(() => null)
|
||||
if (!info) {
|
||||
return null
|
||||
}
|
||||
if (info.isSymbolicLink()) {
|
||||
return 'foreign'
|
||||
}
|
||||
if (AGENT_CONFIG_FILE_KINDS.has(kind)) {
|
||||
if (!info.isFile()) {
|
||||
return 'foreign'
|
||||
}
|
||||
return agentConfigDigest([
|
||||
{ path: AGENT_CONFIG_SELF_PATH, executable: false, bytes: await readFile(path) }
|
||||
])
|
||||
}
|
||||
if (!info.isDirectory()) {
|
||||
return 'foreign'
|
||||
}
|
||||
const entries: AgentConfigDigestEntry[] = []
|
||||
const visit = async (dir: string, prefix: string): Promise<boolean> => {
|
||||
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
||||
const rel = prefix ? `${prefix}/${entry.name}` : entry.name
|
||||
const full = join(dir, entry.name)
|
||||
if (entry.isDirectory()) {
|
||||
if (!(await visit(full, rel))) {
|
||||
return false
|
||||
}
|
||||
} else if (entry.isFile()) {
|
||||
const stat = await lstat(full)
|
||||
entries.push({
|
||||
path: rel,
|
||||
executable: (stat.mode & 0o111) !== 0,
|
||||
bytes: await readFile(full)
|
||||
})
|
||||
if (entries.length > AGENT_CONFIG_LIMITS.filesPerItem * 2) {
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
try {
|
||||
return (await visit(path, '')) ? agentConfigDigest(entries) : 'foreign'
|
||||
} catch {
|
||||
return 'foreign'
|
||||
}
|
||||
}
|
||||
|
||||
/** Decides each item before any bytes move, and removes what this computer stopped sending. */
|
||||
export async function planHostAgentConfigSync(
|
||||
params: AgentConfigSyncPlanParams,
|
||||
deps: HostAgentConfigSyncDeps
|
||||
): Promise<AgentConfigSyncPlanResult> {
|
||||
const path = ledgerPath(deps.ledgerDir, params.syncer)
|
||||
const ledger = await readLedger(path)
|
||||
const items: Record<string, AgentConfigPlanOutcome> = {}
|
||||
const wanted = new Set<string>()
|
||||
for (const item of params.items) {
|
||||
const key = agentConfigItemKey(item.scope, item.kind, item.name)
|
||||
wanted.add(key)
|
||||
const dest = destinationOf(item, deps)
|
||||
if (!dest) {
|
||||
items[key] = 'no-project'
|
||||
continue
|
||||
}
|
||||
const onDisk = await digestOnDisk(dest, item.kind)
|
||||
if (onDisk === null) {
|
||||
items[key] = 'needed'
|
||||
} else if (onDisk === item.digest) {
|
||||
items[key] = 'unchanged'
|
||||
ledger.items[key] = item.digest
|
||||
} else if (ledger.items[key] === onDisk) {
|
||||
items[key] = 'needed'
|
||||
} else {
|
||||
// Made or edited in the sandbox: it's the user's now.
|
||||
items[key] = 'kept-host'
|
||||
delete ledger.items[key]
|
||||
}
|
||||
}
|
||||
let removed = 0
|
||||
for (const [key, digest] of Object.entries(ledger.items)) {
|
||||
if (wanted.has(key)) {
|
||||
continue
|
||||
}
|
||||
delete ledger.items[key]
|
||||
const id = parseKey(key)
|
||||
const dest = id ? destinationOf(id, deps) : null
|
||||
// Only an untouched copy goes; an edited one stays as the user's.
|
||||
if (id && dest && (await digestOnDisk(dest, id.kind)) === digest) {
|
||||
await rm(dest, { recursive: true, force: true })
|
||||
removed += 1
|
||||
}
|
||||
}
|
||||
await writeLedger(path, ledger)
|
||||
return { items, removed }
|
||||
}
|
||||
|
||||
function decodeFiles(item: AgentConfigItemPayload): AgentConfigDigestEntry[] | null {
|
||||
const isFileKind = AGENT_CONFIG_FILE_KINDS.has(item.kind)
|
||||
if (isFileKind && (item.files.length !== 1 || item.files[0].path !== AGENT_CONFIG_SELF_PATH)) {
|
||||
return null
|
||||
}
|
||||
const paths = new Set<string>()
|
||||
const entries: AgentConfigDigestEntry[] = []
|
||||
let total = 0
|
||||
for (const file of item.files) {
|
||||
if ((!isFileKind && file.path === AGENT_CONFIG_SELF_PATH) || paths.has(file.path)) {
|
||||
return null
|
||||
}
|
||||
paths.add(file.path)
|
||||
const bytes = Buffer.from(file.base64, 'base64')
|
||||
total += bytes.length
|
||||
if (bytes.length > AGENT_CONFIG_LIMITS.fileBytes || total > AGENT_CONFIG_LIMITS.itemBytes) {
|
||||
return null
|
||||
}
|
||||
entries.push({ path: file.path, executable: !isFileKind && file.executable, bytes })
|
||||
}
|
||||
if (!isFileKind && !paths.has('SKILL.md')) {
|
||||
return null
|
||||
}
|
||||
return agentConfigDigest(entries) === item.digest ? entries : null
|
||||
}
|
||||
|
||||
async function writeItem(
|
||||
dest: string,
|
||||
kind: AgentConfigItemKind,
|
||||
files: AgentConfigDigestEntry[]
|
||||
): Promise<void> {
|
||||
const parent = dirname(dest)
|
||||
await mkdir(parent, { recursive: true })
|
||||
const tag = randomBytes(6).toString('hex')
|
||||
if (AGENT_CONFIG_FILE_KINDS.has(kind)) {
|
||||
writeFileAtomically(dest, files[0].bytes, { mode: 0o644 })
|
||||
return
|
||||
}
|
||||
// Built beside the target, then swapped in, so an agent never reads half a skill.
|
||||
const staged = join(parent, `.orca-sync-${tag}`)
|
||||
try {
|
||||
for (const file of files) {
|
||||
const target = resolve(staged, file.path)
|
||||
if (isAbsolute(file.path) || !target.startsWith(`${staged}/`)) {
|
||||
throw new Error('Path escapes the skill folder.')
|
||||
}
|
||||
await mkdir(dirname(target), { recursive: true })
|
||||
await writeFile(target, file.bytes, { mode: file.executable ? 0o755 : 0o644 })
|
||||
}
|
||||
const old = join(parent, `.orca-sync-old-${tag}`)
|
||||
const existed = await lstat(dest).then(
|
||||
() => true,
|
||||
() => false
|
||||
)
|
||||
if (existed) {
|
||||
await rename(dest, old)
|
||||
}
|
||||
await rename(staged, dest)
|
||||
if (existed) {
|
||||
await rm(old, { recursive: true, force: true })
|
||||
}
|
||||
} finally {
|
||||
await rm(staged, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes items the plan asked for. Rechecks ownership, so a file edited since the plan stays. */
|
||||
export async function putHostAgentConfig(
|
||||
params: AgentConfigSyncPutParams,
|
||||
deps: HostAgentConfigSyncDeps
|
||||
): Promise<AgentConfigSyncPutResult> {
|
||||
const path = ledgerPath(deps.ledgerDir, params.syncer)
|
||||
const ledger = await readLedger(path)
|
||||
const items: Record<string, AgentConfigPutOutcome> = {}
|
||||
for (const item of params.items) {
|
||||
const key = agentConfigItemKey(item.scope, item.kind, item.name)
|
||||
const id = parseKey(key)
|
||||
const files = id ? decodeFiles(item) : null
|
||||
if (!id || !files) {
|
||||
items[key] = 'invalid'
|
||||
continue
|
||||
}
|
||||
const dest = destinationOf(id, deps)
|
||||
if (!dest) {
|
||||
items[key] = 'no-project'
|
||||
continue
|
||||
}
|
||||
try {
|
||||
const onDisk = await digestOnDisk(dest, id.kind)
|
||||
if (onDisk !== null && onDisk !== item.digest && ledger.items[key] !== onDisk) {
|
||||
items[key] = 'kept-host'
|
||||
continue
|
||||
}
|
||||
if (onDisk !== item.digest) {
|
||||
await writeItem(dest, id.kind, files)
|
||||
}
|
||||
if (id.scope === 'project' && deps.projectPath) {
|
||||
await excludeFromGit(deps.projectPath, dest, isSkillKind(id.kind))
|
||||
}
|
||||
ledger.items[key] = item.digest
|
||||
items[key] = onDisk === null ? 'added' : 'updated'
|
||||
} catch {
|
||||
items[key] = 'failed'
|
||||
}
|
||||
}
|
||||
await writeLedger(path, ledger)
|
||||
const counts = Object.values(items).reduce<Record<string, number>>((acc, outcome) => {
|
||||
acc[outcome] = (acc[outcome] ?? 0) + 1
|
||||
return acc
|
||||
}, {})
|
||||
console.info(
|
||||
`[agent-config-sync] ${Object.entries(counts)
|
||||
.map(([outcome, n]) => `${outcome}=${n}`)
|
||||
.join(',')}`
|
||||
)
|
||||
return { items }
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
@@ -18,6 +17,7 @@ import { environmentHandleFromRecipeResult } from '../../environment-providers/e
|
||||
import { HOSTED_SANDBOX_DRIVER_ID } from '../../hosted-sandbox/hosted-sandbox-driver'
|
||||
import { readLocalMcpConfig, type LocalMcpConfig } from './local-mcp-config-read'
|
||||
import type { CloudMcpEgress } from './cloud-mcp-egress'
|
||||
import { readOrCreateSyncerId } from '../../agent-config-sync/desktop/syncer-id'
|
||||
|
||||
const SYNC_TIMEOUT_MS = 30_000
|
||||
const MAX_EXCLUDED = 512
|
||||
@@ -146,30 +146,7 @@ export function createCloudMcpSync(deps: CloudMcpSyncDeps): CloudMcpSync {
|
||||
}
|
||||
}
|
||||
|
||||
let syncer: string | null = null
|
||||
/** This computer's stable sync identity (random, not a device fingerprint). */
|
||||
function syncerId(): string {
|
||||
if (syncer) {
|
||||
return syncer
|
||||
}
|
||||
const path = join(deps.userDataPath, 'mcp-sync-syncer-id')
|
||||
try {
|
||||
const stored = readFileSync(path, 'utf8').trim()
|
||||
if (/^[a-f0-9]{16}$/.test(stored)) {
|
||||
syncer = stored
|
||||
return stored
|
||||
}
|
||||
} catch {
|
||||
// First sync from this computer.
|
||||
}
|
||||
syncer = randomBytes(8).toString('hex')
|
||||
try {
|
||||
writeFileAtomically(path, `${syncer}\n`)
|
||||
} catch {
|
||||
// Unwritable profile: this run still syncs as itself; the next launch gets a new id.
|
||||
}
|
||||
return syncer
|
||||
}
|
||||
const syncerId = (): Promise<string> => readOrCreateSyncerId(deps.userDataPath)
|
||||
|
||||
async function plan(environmentId: string) {
|
||||
const runtime = cloudRuntime(environmentId)
|
||||
@@ -180,7 +157,7 @@ export function createCloudMcpSync(deps: CloudMcpSyncDeps): CloudMcpSync {
|
||||
repoServerNames: local.repoServerNames,
|
||||
homeDir: homedir()
|
||||
})
|
||||
return { ...planned, params: { ...planned.params, syncer: syncerId() } }
|
||||
return { ...planned, params: { ...planned.params, syncer: await syncerId() } }
|
||||
}
|
||||
|
||||
function publish(status: McpSyncStatus): McpSyncStatus {
|
||||
|
||||
@@ -141,7 +141,10 @@ const EntitlementSchema = z.object({
|
||||
interval: z.enum(ORCA_BILLING_INTERVALS).nullable().catch(null),
|
||||
seats: seconds,
|
||||
seatChange: z
|
||||
.object({ seatsAtRenewal: z.number().int().min(1), effectiveAt: z.number() })
|
||||
.object({
|
||||
seatsAtRenewal: z.number().int().min(1),
|
||||
effectiveAt: z.number()
|
||||
})
|
||||
.nullable()
|
||||
.catch(null),
|
||||
period: window,
|
||||
@@ -172,7 +175,13 @@ const EntitlementSchema = z.object({
|
||||
spentCents: seconds,
|
||||
centsPerHour: seconds
|
||||
})
|
||||
.catch({ optedIn: false, active: false, spendCapCents: 0, spentCents: 0, centsPerHour: 0 }),
|
||||
.catch({
|
||||
optedIn: false,
|
||||
active: false,
|
||||
spendCapCents: 0,
|
||||
spentCents: 0,
|
||||
centsPerHour: 0
|
||||
}),
|
||||
payment: z
|
||||
.object({
|
||||
pastDueSince: z.number().nullable().catch(null),
|
||||
|
||||
@@ -11,7 +11,8 @@ import type {
|
||||
OrcaBillingOverageResult,
|
||||
OrcaBillingStatusResult,
|
||||
OrcaBillingTeamPlansResult,
|
||||
OrcaBillingTrialClaimResult
|
||||
OrcaBillingTrialClaimResult,
|
||||
OrcaBillingUsageHistoryResult
|
||||
} from '../../shared/orca-billing'
|
||||
import { getOrcaCloudAuthConfig } from '../orca-profiles/profile-cloud-auth-config'
|
||||
import { runWithFreshOrcaCloudSession } from '../orca-profiles/profile-cloud-session-refresh'
|
||||
@@ -28,6 +29,7 @@ import {
|
||||
type BillingEndpoints
|
||||
} from './billing-client'
|
||||
import { getBillingEndpoints } from './billing-config'
|
||||
import { fetchUsageHistory } from './billing-usage-client'
|
||||
import { getBillingDevKeyFile, mintDevBillingToken } from './billing-dev-token'
|
||||
import { cleanCloudServiceUrl } from '../../shared/cloud-service-url'
|
||||
import { listOrcaProfileOrgMembers } from '../orca-profiles/profile-cloud-org-members-service'
|
||||
@@ -55,7 +57,10 @@ function prepareDev(userDataPath: string, keyFile: string): Ready {
|
||||
if (!cloud) {
|
||||
return { ok: false, status: 'signed-out' }
|
||||
}
|
||||
const endpoints: BillingEndpoints = { billingApiUrl, billingTokenEndpoint: billingApiUrl }
|
||||
const endpoints: BillingEndpoints = {
|
||||
billingApiUrl,
|
||||
billingTokenEndpoint: billingApiUrl
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
run: async (call) => {
|
||||
@@ -139,6 +144,25 @@ export async function getOrcaBillingStatus(userDataPath: string): Promise<OrcaBi
|
||||
}
|
||||
}
|
||||
|
||||
/** The last 30 days of sandbox hours, with days starting at the viewer's local midnight. */
|
||||
export async function getOrcaBillingUsageHistory(
|
||||
userDataPath: string,
|
||||
utcOffsetMinutes: number
|
||||
): Promise<OrcaBillingUsageHistoryResult> {
|
||||
const ready = prepare(userDataPath)
|
||||
if (!ready.ok) {
|
||||
return { status: ready.status }
|
||||
}
|
||||
try {
|
||||
const history = await ready.run((token, endpoints) =>
|
||||
fetchUsageHistory(endpoints, token, utcOffsetMinutes)
|
||||
)
|
||||
return history === 'signed-out' ? { status: 'signed-out' } : { status: 'ok', history }
|
||||
} catch (error) {
|
||||
return { status: 'failed', error: message(error) }
|
||||
}
|
||||
}
|
||||
|
||||
/** Plan state for other teams the signed-in user is on (cloud start B2); never switches teams. */
|
||||
export async function getOrcaBillingTeamPlans(
|
||||
userDataPath: string,
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { fetchUsageHistory } from './billing-usage-client'
|
||||
|
||||
const endpoints = {
|
||||
billingApiUrl: 'https://billing.example.test',
|
||||
billingTokenEndpoint: 'https://login.example.test/v1/desktop/auth/billing-token'
|
||||
}
|
||||
|
||||
type Seen = { url: string; init: RequestInit | undefined }
|
||||
|
||||
function fakeFetch(responses: Record<string, Response>, seen: Seen[] = []): typeof fetch {
|
||||
return async (input, init) => {
|
||||
const url = String(input)
|
||||
seen.push({ url, init })
|
||||
const response = responses[url]
|
||||
if (!response) {
|
||||
throw new Error(`unexpected ${url}`)
|
||||
}
|
||||
return response
|
||||
}
|
||||
}
|
||||
|
||||
describe('fetchUsageHistory', () => {
|
||||
const url = 'https://billing.example.test/v1/billing/usage?utcOffset=-480'
|
||||
const body = {
|
||||
days: [{ start: 1, seconds: 3600 }],
|
||||
totalSeconds: 3600,
|
||||
yourSeconds: 1800,
|
||||
members: { top: [{ userId: 'u1', seconds: 3600 }], otherCount: 0, otherSeconds: 0 },
|
||||
sandboxes: { top: [{ sandboxId: 'sbx_1', seconds: 3600 }], otherCount: 0, otherSeconds: 0 }
|
||||
}
|
||||
|
||||
it('sends the local offset and maps both breakdowns to one row shape', async () => {
|
||||
const seen: Seen[] = []
|
||||
const history = await fetchUsageHistory(
|
||||
endpoints,
|
||||
'bt',
|
||||
-480,
|
||||
fakeFetch({ [url]: Response.json(body) }, seen)
|
||||
)
|
||||
expect(seen[0]!.init?.method).toBe('GET')
|
||||
expect(history.members).toEqual({
|
||||
top: [{ id: 'u1', seconds: 3600 }],
|
||||
otherCount: 0,
|
||||
otherSeconds: 0
|
||||
})
|
||||
expect(history.sandboxes?.top).toEqual([{ id: 'sbx_1', seconds: 3600 }])
|
||||
})
|
||||
|
||||
it('accepts a member’s view and rejects malformed rows', async () => {
|
||||
const member = await fetchUsageHistory(
|
||||
endpoints,
|
||||
'bt',
|
||||
-480,
|
||||
fakeFetch({ [url]: Response.json({ ...body, members: null, sandboxes: null }) })
|
||||
)
|
||||
expect(member.members).toBeNull()
|
||||
await expect(
|
||||
fetchUsageHistory(
|
||||
endpoints,
|
||||
'bt',
|
||||
-480,
|
||||
fakeFetch({
|
||||
[url]: Response.json({
|
||||
...body,
|
||||
members: { top: [{ userId: '<script>', seconds: 1 }], otherCount: 0, otherSeconds: 0 }
|
||||
})
|
||||
})
|
||||
)
|
||||
).rejects.toThrow('invalid_billing_response')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,67 @@
|
||||
// GET /v1/billing/usage behind Plan & billing's "Last 30 days". Pure (fetch injected).
|
||||
import { z } from 'zod'
|
||||
import type { OrcaBillingUsageHistory } from '../../shared/orca-billing'
|
||||
import { billingRequest, type BillingEndpoints } from './billing-client'
|
||||
|
||||
const UsageId = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(128)
|
||||
.regex(/^[A-Za-z0-9_.:-]+$/)
|
||||
const UsageSeconds = z.number().finite().nonnegative()
|
||||
const usageTop = <K extends 'userId' | 'sandboxId'>(key: K) =>
|
||||
z
|
||||
.object({
|
||||
top: z.array(z.record(z.string(), z.unknown())).max(20),
|
||||
otherCount: z.number().int().nonnegative(),
|
||||
otherSeconds: UsageSeconds
|
||||
})
|
||||
.transform((value, ctx) => {
|
||||
const top = value.top.map((row) => ({
|
||||
id: UsageId.safeParse(row[key]),
|
||||
seconds: UsageSeconds.safeParse(row.seconds)
|
||||
}))
|
||||
if (top.some((row) => !row.id.success || !row.seconds.success)) {
|
||||
ctx.addIssue({ code: 'custom', message: 'invalid_usage_row' })
|
||||
return z.NEVER
|
||||
}
|
||||
return {
|
||||
top: top.map((row) => ({
|
||||
id: row.id.data!,
|
||||
seconds: row.seconds.data!
|
||||
})),
|
||||
otherCount: value.otherCount,
|
||||
otherSeconds: value.otherSeconds
|
||||
}
|
||||
})
|
||||
.nullable()
|
||||
const UsageHistoryBody = z.object({
|
||||
days: z.array(z.object({ start: z.number().int(), seconds: UsageSeconds })).max(31),
|
||||
totalSeconds: UsageSeconds,
|
||||
yourSeconds: UsageSeconds,
|
||||
members: usageTop('userId'),
|
||||
sandboxes: usageTop('sandboxId')
|
||||
})
|
||||
|
||||
/** GET /v1/billing/usage: 30 days of sandbox hours, days starting at the local midnight. */
|
||||
export async function fetchUsageHistory(
|
||||
endpoints: BillingEndpoints,
|
||||
token: string,
|
||||
utcOffsetMinutes: number,
|
||||
fetchImpl: typeof fetch = fetch
|
||||
): Promise<OrcaBillingUsageHistory> {
|
||||
const body = UsageHistoryBody.safeParse(
|
||||
await billingRequest(
|
||||
endpoints,
|
||||
token,
|
||||
'GET',
|
||||
`v1/billing/usage?utcOffset=${Math.round(utcOffsetMinutes)}`,
|
||||
undefined,
|
||||
fetchImpl
|
||||
)
|
||||
)
|
||||
if (!body.success) {
|
||||
throw new Error('invalid_billing_response')
|
||||
}
|
||||
return body.data
|
||||
}
|
||||
@@ -195,6 +195,49 @@ describe('response hardening', () => {
|
||||
expect(parsed.result?.prUrl).toBeUndefined()
|
||||
expect(parsed.status).toBe('succeeded')
|
||||
})
|
||||
|
||||
it('accepts the run the control plane answers Run now with (object trigger detail)', async () => {
|
||||
// Exactly what POST /v1/routines/:id/run returns (routines/store.ts runView, private view).
|
||||
const queued = {
|
||||
id: 'run_9',
|
||||
routineId: 'rt_1',
|
||||
trigger: 'manual',
|
||||
triggerDetail: { requestedBy: 'usr_1' },
|
||||
status: 'queued',
|
||||
workspaceId: null,
|
||||
result: null,
|
||||
error: null,
|
||||
createdAt: 5,
|
||||
startedAt: null,
|
||||
finishedAt: null,
|
||||
durationMs: null
|
||||
}
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () => respond(202, { run: queued }))
|
||||
const { run } = await client(fetchImpl).runRoutine('rt_1')
|
||||
expect(run).toMatchObject({ id: 'run_9', status: 'queued', triggerDetail: null })
|
||||
|
||||
const github = {
|
||||
...queued,
|
||||
trigger: 'github',
|
||||
triggerDetail: {
|
||||
event: 'pull_request.labeled',
|
||||
delivery: 'd1',
|
||||
target: { repo: 'acme/web', number: 482, kind: 'pull_request' },
|
||||
context: { anything: true }
|
||||
}
|
||||
}
|
||||
const page = vi.fn<typeof fetch>(async () =>
|
||||
respond(200, {
|
||||
runs: [github, { ...queued, triggerDetail: 'POST from ci' }],
|
||||
nextBefore: null
|
||||
})
|
||||
)
|
||||
const { runs } = await client(page).listRoutineRuns('rt_1')
|
||||
expect(runs.map((r) => r.triggerDetail)).toEqual([
|
||||
'acme/web#482 pull_request.labeled',
|
||||
'POST from ci'
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('classifyCloudApiResponse', () => {
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
createCloudPairingPrune,
|
||||
type CloudPairingBindings,
|
||||
type CloudSandboxPresence
|
||||
} from './cloud-pairing-prune'
|
||||
|
||||
const A = 'sbx_aaaaaaaaaaaaaaaaaaaaaaaa'
|
||||
const B = 'sbx_bbbbbbbbbbbbbbbbbbbbbbbb'
|
||||
|
||||
function setup(options: {
|
||||
bindings: CloudPairingBindings
|
||||
listed?: string[] | null
|
||||
presence?: Record<string, CloudSandboxPresence>
|
||||
account?: () => string | null
|
||||
}) {
|
||||
let bindings = structuredClone(options.bindings)
|
||||
const removed: string[] = []
|
||||
const presence = vi.fn(async (id: string) => options.presence?.[id] ?? 'unknown')
|
||||
const listVisible = vi.fn(async () =>
|
||||
options.listed === null ? null : new Set(options.listed ?? [])
|
||||
)
|
||||
let clock = 0
|
||||
const prune = createCloudPairingPrune({
|
||||
activeAccountId: options.account ?? (() => 'team-1'),
|
||||
readBindings: async () => structuredClone(bindings),
|
||||
updateBindings: async (change) => {
|
||||
bindings = change(structuredClone(bindings))
|
||||
},
|
||||
listVisible,
|
||||
presence,
|
||||
removeEnvironment: async (id) => {
|
||||
removed.push(id)
|
||||
},
|
||||
now: () => clock
|
||||
})
|
||||
return {
|
||||
prune,
|
||||
removed,
|
||||
presence,
|
||||
listVisible,
|
||||
bindings: () => bindings,
|
||||
advance: (ms: number) => {
|
||||
clock += ms
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe('cloud pairing prune (LC-1)', () => {
|
||||
it('drops a pairing missing from the list once one more fetch confirms the sandbox is gone', async () => {
|
||||
const t = setup({
|
||||
bindings: {
|
||||
[A]: { environmentId: 'env-a', grantId: null, accountId: 'team-1' },
|
||||
[B]: { environmentId: 'env-b', grantId: null, accountId: 'team-1' }
|
||||
},
|
||||
listed: [B],
|
||||
presence: { [A]: 'gone' }
|
||||
})
|
||||
await t.prune.run({ force: true })
|
||||
expect(t.presence).toHaveBeenCalledWith(A)
|
||||
expect(t.presence).not.toHaveBeenCalledWith(B)
|
||||
expect(t.removed).toEqual(['env-a'])
|
||||
expect(Object.keys(t.bindings())).toEqual([B])
|
||||
})
|
||||
|
||||
it('a failed list never drops anything (network blip)', async () => {
|
||||
const t = setup({
|
||||
bindings: { [A]: { environmentId: 'env-a', grantId: null, accountId: 'team-1' } },
|
||||
listed: null,
|
||||
presence: { [A]: 'gone' }
|
||||
})
|
||||
await t.prune.run({ force: true })
|
||||
expect(t.presence).not.toHaveBeenCalled()
|
||||
expect(t.removed).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps a pairing when the confirming fetch fails or finds the sandbox', async () => {
|
||||
for (const answer of ['unknown', 'present'] as const) {
|
||||
const t = setup({
|
||||
bindings: { [A]: { environmentId: 'env-a', grantId: null, accountId: 'team-1' } },
|
||||
listed: [],
|
||||
presence: { [A]: answer }
|
||||
})
|
||||
await t.prune.run({ force: true })
|
||||
expect(t.removed).toEqual([])
|
||||
expect(Object.keys(t.bindings())).toEqual([A])
|
||||
}
|
||||
})
|
||||
|
||||
it("leaves another team's pairings alone", async () => {
|
||||
const t = setup({
|
||||
bindings: { [A]: { environmentId: 'env-a', grantId: null, accountId: 'team-2' } },
|
||||
listed: [],
|
||||
presence: { [A]: 'gone' }
|
||||
})
|
||||
await t.prune.run({ force: true })
|
||||
expect(t.listVisible).not.toHaveBeenCalled()
|
||||
expect(t.removed).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps everything when the team switches mid-check', async () => {
|
||||
let account = 'team-1'
|
||||
const t = setup({
|
||||
bindings: { [A]: { environmentId: 'env-a', grantId: null, accountId: 'team-1' } },
|
||||
listed: [],
|
||||
presence: { [A]: 'gone' },
|
||||
account: () => account
|
||||
})
|
||||
t.presence.mockImplementation(async () => {
|
||||
account = 'team-2'
|
||||
return 'gone'
|
||||
})
|
||||
await t.prune.run({ force: true })
|
||||
expect(t.removed).toEqual([])
|
||||
})
|
||||
|
||||
it('stamps older bindings with the team that lists them', async () => {
|
||||
const t = setup({
|
||||
bindings: { [A]: { environmentId: 'env-a', grantId: null } },
|
||||
listed: [A]
|
||||
})
|
||||
await t.prune.run({ force: true })
|
||||
expect(t.bindings()[A]?.accountId).toBe('team-1')
|
||||
expect(t.removed).toEqual([])
|
||||
})
|
||||
|
||||
it('forget drops the pairing now, keeping a server another binding still uses', async () => {
|
||||
const t = setup({
|
||||
bindings: {
|
||||
[A]: { environmentId: 'env-shared', grantId: null, accountId: 'team-1' },
|
||||
[B]: { environmentId: 'env-shared', grantId: null, accountId: 'team-1' }
|
||||
}
|
||||
})
|
||||
await t.prune.forget(A)
|
||||
expect(t.removed).toEqual([])
|
||||
await t.prune.forget(B)
|
||||
expect(t.removed).toEqual(['env-shared'])
|
||||
expect(t.bindings()).toEqual({})
|
||||
})
|
||||
|
||||
it('throttles list-triggered runs; a forced run always goes', async () => {
|
||||
const t = setup({
|
||||
bindings: { [A]: { environmentId: 'env-a', grantId: null, accountId: 'team-1' } },
|
||||
listed: [A]
|
||||
})
|
||||
await t.prune.run()
|
||||
await t.prune.run()
|
||||
expect(t.listVisible).toHaveBeenCalledTimes(1)
|
||||
await t.prune.run({ force: true })
|
||||
expect(t.listVisible).toHaveBeenCalledTimes(2)
|
||||
t.advance(60_000)
|
||||
await t.prune.run()
|
||||
expect(t.listVisible).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,137 @@
|
||||
// Drops this device's pairing with a cloud workspace whose sandbox no longer exists (LC-1). Opening
|
||||
// a workspace this desktop does not own pairs it as a "<name> (cloud)" server, and that server's
|
||||
// projects mirror into the sidebar. Once the sandbox was deleted (from Home, another desktop, the
|
||||
// control plane), the server, its struck-out host row and its projects stayed forever.
|
||||
//
|
||||
// Only an authoritative answer drops one: missing from the active team's successful list, then
|
||||
// confirmed by one more fetch of that sandbox answering not found or destroyed. A failed list, a
|
||||
// failed or ambiguous confirm, or a team switch mid-check keeps everything, so a network blip never
|
||||
// wipes a pairing. (Owned workspaces are retired by cloud-sandbox-gone-prune; this is the pairing
|
||||
// half.)
|
||||
|
||||
export type CloudPairingBinding = {
|
||||
environmentId: string
|
||||
grantId: string | null
|
||||
/** The team the sandbox belongs to; absent on bindings saved before LC-1. */
|
||||
accountId?: string | null
|
||||
}
|
||||
|
||||
export type CloudPairingBindings = Record<string, CloudPairingBinding>
|
||||
|
||||
/** What one fetch of a sandbox said: only `gone` (not found, or destroyed) lets a pairing go. */
|
||||
export type CloudSandboxPresence = 'gone' | 'present' | 'unknown'
|
||||
|
||||
export type CloudPairingPrune = {
|
||||
/** Startup and each cloud list refresh. Single-flight; list-triggered runs are throttled. */
|
||||
run(options?: { force?: boolean }): Promise<void>
|
||||
/** The sandbox was deleted from here: drop its pairing now, no fetch needed. */
|
||||
forget(sandboxId: string): Promise<void>
|
||||
/** A pairing was just saved: stamp it with the active team. */
|
||||
accountForNewBinding(): string | null
|
||||
}
|
||||
|
||||
export function createCloudPairingPrune(deps: {
|
||||
activeAccountId: () => string | null
|
||||
readBindings: () => Promise<CloudPairingBindings>
|
||||
updateBindings: (change: (current: CloudPairingBindings) => CloudPairingBindings) => Promise<void>
|
||||
/** Ids of every sandbox the active team's list shows this user; null when the list failed. */
|
||||
listVisible: () => Promise<ReadonlySet<string> | null>
|
||||
/** One fetch of a single sandbox. */
|
||||
presence: (sandboxId: string) => Promise<CloudSandboxPresence>
|
||||
/** Remove the paired server; the window's catalog refresh then purges its projects. */
|
||||
removeEnvironment: (environmentId: string) => Promise<void>
|
||||
minIntervalMs?: number
|
||||
now?: () => number
|
||||
log?: (line: string) => void
|
||||
}): CloudPairingPrune {
|
||||
const now = deps.now ?? Date.now
|
||||
const minIntervalMs = deps.minIntervalMs ?? 60_000
|
||||
let lastRunAt = Number.NEGATIVE_INFINITY
|
||||
let running: Promise<void> | null = null
|
||||
|
||||
async function forget(sandboxId: string): Promise<void> {
|
||||
let dropped: CloudPairingBinding | undefined
|
||||
let stillUsed = false
|
||||
await deps.updateBindings((current) => {
|
||||
dropped = current[sandboxId]
|
||||
if (!dropped) {
|
||||
return current
|
||||
}
|
||||
const next = { ...current }
|
||||
delete next[sandboxId]
|
||||
stillUsed = Object.values(next).some((b) => b.environmentId === dropped?.environmentId)
|
||||
return next
|
||||
})
|
||||
if (dropped && !stillUsed) {
|
||||
await deps.removeEnvironment(dropped.environmentId)
|
||||
}
|
||||
}
|
||||
|
||||
async function prune(): Promise<void> {
|
||||
const account = deps.activeAccountId()
|
||||
if (!account) {
|
||||
return
|
||||
}
|
||||
const bindings = await deps.readBindings()
|
||||
// Another team's pairing is not this list's to judge. Unstamped ones are judged by the confirm.
|
||||
const candidates = Object.entries(bindings).filter(
|
||||
([, binding]) => !binding.accountId || binding.accountId === account
|
||||
)
|
||||
if (candidates.length === 0) {
|
||||
return
|
||||
}
|
||||
const listed = await deps.listVisible()
|
||||
if (!listed || deps.activeAccountId() !== account) {
|
||||
return
|
||||
}
|
||||
// Listed means it is this team's: stamp older bindings so later team switches leave them be.
|
||||
const unstampedListed = candidates.filter(([id, b]) => !b.accountId && listed.has(id))
|
||||
if (unstampedListed.length > 0) {
|
||||
await deps.updateBindings((current) => {
|
||||
const next = { ...current }
|
||||
for (const [id] of unstampedListed) {
|
||||
if (next[id] && !next[id].accountId) {
|
||||
next[id] = { ...next[id], accountId: account }
|
||||
}
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
for (const [sandboxId] of candidates) {
|
||||
if (listed.has(sandboxId)) {
|
||||
continue
|
||||
}
|
||||
const presence = await deps.presence(sandboxId)
|
||||
// The confirming answer must still be for the team the list was for.
|
||||
if (presence !== 'gone' || deps.activeAccountId() !== account) {
|
||||
continue
|
||||
}
|
||||
try {
|
||||
await forget(sandboxId)
|
||||
deps.log?.(`[cloud-workspaces] dropped the pairing with ${sandboxId}: sandbox is gone`)
|
||||
} catch (error) {
|
||||
deps.log?.(`[cloud-workspaces] could not drop a gone sandbox's pairing: ${String(error)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
run(options) {
|
||||
if (running) {
|
||||
return running
|
||||
}
|
||||
if (!options?.force && now() - lastRunAt < minIntervalMs) {
|
||||
return Promise.resolve()
|
||||
}
|
||||
lastRunAt = now()
|
||||
running = prune()
|
||||
.catch((error) => deps.log?.(`[cloud-workspaces] pairing prune failed: ${String(error)}`))
|
||||
.finally(() => {
|
||||
running = null
|
||||
})
|
||||
return running
|
||||
},
|
||||
forget,
|
||||
accountForNewBinding: () => deps.activeAccountId()
|
||||
}
|
||||
}
|
||||
@@ -145,3 +145,45 @@ describe('cloud workspaces client: sleep and delete', () => {
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('cloud workspaces client: routine runs on Home', () => {
|
||||
it('asks for routine runs only when the filter is on, and keeps the routine mark', async () => {
|
||||
const row = {
|
||||
id: SBX,
|
||||
workspaceId: 'routine-run_1',
|
||||
status: 'running',
|
||||
machineSize: 'standard',
|
||||
region: 'pdx1',
|
||||
createdAt: 1,
|
||||
title: 'Nightly · run',
|
||||
repo: null,
|
||||
visibility: 'private',
|
||||
section: null,
|
||||
archivedAt: null,
|
||||
createdBy: 'u1',
|
||||
ownerUserId: 'u1',
|
||||
lastActivityAt: 1,
|
||||
lastActivityBy: null,
|
||||
cost: {
|
||||
computeMs: 0,
|
||||
rateUsdMicrosPerHour: 0,
|
||||
computeUsdMicros: 0,
|
||||
tokenUsdMicros: null,
|
||||
totalUsdMicros: 0
|
||||
},
|
||||
access: 'owner',
|
||||
presence: [],
|
||||
fromRoutine: true
|
||||
}
|
||||
const { client, fetch } = clientAnswering(200, { workspaces: [row] })
|
||||
const listed = (await client.list({ scope: 'mine', archived: 'exclude', routines: 'include' }))
|
||||
.workspaces
|
||||
expect(String(fetch.mock.calls[0]![0])).toBe(
|
||||
'https://cp.example.test/v1/team/workspaces?scope=mine&archived=exclude&routines=include'
|
||||
)
|
||||
expect(listed[0]!.fromRoutine).toBe(true)
|
||||
// Older control planes omit the mark; it is never required.
|
||||
const { fromRoutine: _omitted, ...older } = row
|
||||
expect(CloudWorkspaceSchema.parse(older).fromRoutine).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// hosted sandbox driver: a short-lived Orca token (aud=orca-sandbox), never a provider credential.
|
||||
import { z } from 'zod'
|
||||
import { errorMessage } from '../../shared/error-message'
|
||||
import { cloudWorkspacePrefsMethods } from './cloud-workspaces-prefs-client'
|
||||
import { HOSTED_SANDBOX_STATUSES } from '../../shared/hosted-sandbox/hosted-sandbox-wire'
|
||||
import type { SealedReadSnapshot } from '../../shared/cloud-workspaces/read-snapshot'
|
||||
import {
|
||||
@@ -14,10 +15,17 @@ import {
|
||||
CloudWorkspacePresenceResponseSchema,
|
||||
CloudWorkspaceResponseSchema,
|
||||
OrgPromptsSchema,
|
||||
type CloudWorkspaceLinkTarget,
|
||||
type CloudWorkspaceListQuery,
|
||||
type CloudWorkspacePatch,
|
||||
type OrgPrompts
|
||||
} from '../../shared/cloud-workspaces/cloud-workspaces-wire'
|
||||
import {
|
||||
PokeInboxSchema,
|
||||
PokeSentSchema,
|
||||
PokeSettingsSchema,
|
||||
TeammateProfileResponseSchema
|
||||
} from '../../shared/cloud-workspaces/team-presence-wire'
|
||||
|
||||
const NoteSentSchema = z.object({ ok: z.literal(true) })
|
||||
/** DELETE and POST suspend on /v1/sandboxes/:id answer with the sandbox's new state, not `{ok}`. */
|
||||
@@ -29,7 +37,9 @@ export class CloudWorkspacesError extends Error {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
readonly code: string,
|
||||
readonly reason?: string
|
||||
readonly reason?: string,
|
||||
/** A slug link for another org (`reason: other_org`) names that org, so a member can switch. */
|
||||
readonly orgId?: string
|
||||
) {
|
||||
super(reason ? `${code}:${reason}` : code)
|
||||
this.name = 'CloudWorkspacesError'
|
||||
@@ -112,7 +122,8 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption
|
||||
throw new CloudWorkspacesError(
|
||||
response.status,
|
||||
typeof err.error === 'string' ? err.error : 'error',
|
||||
typeof err.reason === 'string' ? err.reason : undefined
|
||||
typeof err.reason === 'string' ? err.reason : undefined,
|
||||
typeof err.orgId === 'string' ? err.orgId.slice(0, 128) : undefined
|
||||
)
|
||||
}
|
||||
const parsed = schema.safeParse(payload)
|
||||
@@ -125,6 +136,7 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption
|
||||
const ws = (id: string) => `/v1/team/workspaces/${encodeURIComponent(id)}`
|
||||
|
||||
return {
|
||||
...cloudWorkspacePrefsMethods(call),
|
||||
async list(query: CloudWorkspaceListQuery = {}) {
|
||||
const params = new URLSearchParams()
|
||||
for (const [key, value] of Object.entries(query)) {
|
||||
@@ -133,13 +145,11 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption
|
||||
}
|
||||
}
|
||||
const qs = params.toString()
|
||||
return (
|
||||
await call(
|
||||
'GET',
|
||||
`/v1/team/workspaces${qs ? `?${qs}` : ''}`,
|
||||
CloudWorkspaceListResponseSchema
|
||||
)
|
||||
).workspaces
|
||||
return call(
|
||||
'GET',
|
||||
`/v1/team/workspaces${qs ? `?${qs}` : ''}`,
|
||||
CloudWorkspaceListResponseSchema
|
||||
)
|
||||
},
|
||||
async get(id: string) {
|
||||
return (await call('GET', ws(id), CloudWorkspaceResponseSchema)).workspace
|
||||
@@ -204,8 +214,12 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption
|
||||
CloudWorkspaceGrantListSchema.partial().passthrough()
|
||||
)
|
||||
},
|
||||
async resolveLink(workspaceId: string, chatId?: string | null) {
|
||||
const params = new URLSearchParams({ w: workspaceId })
|
||||
async resolveLink(target: CloudWorkspaceLinkTarget, chatId?: string | null) {
|
||||
const params = new URLSearchParams(
|
||||
target.kind === 'id'
|
||||
? { w: target.workspaceId }
|
||||
: { org: target.org, n: String(target.number) }
|
||||
)
|
||||
if (chatId) {
|
||||
params.set('c', chatId)
|
||||
}
|
||||
@@ -256,6 +270,35 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption
|
||||
},
|
||||
putOrgPrompts(document: OrgPrompts['document'], revision: number): Promise<OrgPrompts> {
|
||||
return call('PUT', '/v1/team/prompts', OrgPromptsSchema, { document, revision })
|
||||
},
|
||||
async teammateProfile(userId: string, utcOffsetMin: number) {
|
||||
const qs = new URLSearchParams({ utcOffsetMin: String(utcOffsetMin) })
|
||||
return (
|
||||
await call(
|
||||
'GET',
|
||||
`/v1/team/members/${encodeURIComponent(userId)}/profile?${qs}`,
|
||||
TeammateProfileResponseSchema
|
||||
)
|
||||
).profile
|
||||
},
|
||||
async poke(userId: string) {
|
||||
return (
|
||||
await call(
|
||||
'POST',
|
||||
`/v1/team/members/${encodeURIComponent(userId)}/poke`,
|
||||
PokeSentSchema,
|
||||
{}
|
||||
)
|
||||
).poke
|
||||
},
|
||||
pokeInbox() {
|
||||
return call('GET', '/v1/team/pokes', PokeInboxSchema)
|
||||
},
|
||||
async setPokesEnabled(enabled: boolean) {
|
||||
return (await call('PUT', '/v1/team/pokes/settings', PokeSettingsSchema, { enabled })).enabled
|
||||
},
|
||||
async markPokesSeen(ids: string[]) {
|
||||
await call('POST', '/v1/team/pokes/seen', NoteSentSchema, { ids })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
// Synced cloud workspace prefs (pins, order, sections) and the org's link slug, on the same
|
||||
// authenticated call as the rest of the team registry client.
|
||||
import type { z } from 'zod'
|
||||
import {
|
||||
CloudOrgSlugSchema,
|
||||
CloudWorkspacePrefsSchema,
|
||||
type CloudOrgSlug,
|
||||
type CloudWorkspacePrefs,
|
||||
type CloudWorkspacePrefsDocument
|
||||
} from '../../shared/cloud-workspaces/cloud-workspaces-wire'
|
||||
|
||||
type Call = <T>(
|
||||
method: 'GET' | 'PUT',
|
||||
path: string,
|
||||
schema: z.ZodType<T>,
|
||||
body?: unknown
|
||||
) => Promise<T>
|
||||
|
||||
export function cloudWorkspacePrefsMethods(call: Call) {
|
||||
return {
|
||||
/** This member's synced arrangement for the current account. */
|
||||
getPrefs(): Promise<CloudWorkspacePrefs> {
|
||||
return call('GET', '/v1/team/prefs', CloudWorkspacePrefsSchema)
|
||||
},
|
||||
/** Compare-and-set: a stale `revision` answers 409 `conflict`; re-read and re-apply. */
|
||||
putPrefs(
|
||||
document: CloudWorkspacePrefsDocument,
|
||||
revision: number,
|
||||
deviceId?: string
|
||||
): Promise<CloudWorkspacePrefs> {
|
||||
// JSON drops an undefined deviceId.
|
||||
return call('PUT', '/v1/team/prefs', CloudWorkspacePrefsSchema, {
|
||||
document,
|
||||
revision,
|
||||
deviceId
|
||||
})
|
||||
},
|
||||
/** The org's link slug; `name` (the org name this client shows) names it the first time. */
|
||||
getOrgSlug(name?: string | null): Promise<CloudOrgSlug> {
|
||||
const qs = name ? `?${new URLSearchParams({ name: name.slice(0, 120) })}` : ''
|
||||
return call('GET', `/v1/team/org${qs}`, CloudOrgSlugSchema)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,12 @@ import { listEphemeralVmRuntimes } from '../../shared/ephemeral-vm-runtime-store
|
||||
import { openSealedGrant } from '../../shared/cloud-workspaces/sealed-grant'
|
||||
import { errorMessage } from '../../shared/error-message'
|
||||
import type {
|
||||
CloudWorkspaceLinkTarget,
|
||||
CloudWorkspace,
|
||||
CloudWorkspaceListQuery,
|
||||
CloudWorkspacePatch,
|
||||
CloudWorkspacePrefsDocument,
|
||||
CloudWorkspaceRoutineRuns,
|
||||
OrgPrompts
|
||||
} from '../../shared/cloud-workspaces/cloud-workspaces-wire'
|
||||
import { environmentHandleFromRecipeResult } from '../environment-providers/environment-provider-recipe-adapter'
|
||||
@@ -28,6 +32,11 @@ const TYPING_HOLD_MS = 6_000
|
||||
|
||||
export type CloudWorkspacesResult<T> =
|
||||
| { ok: true; value: T }
|
||||
| { ok: false; error: string; reason?: string; status?: number; orgId?: string }
|
||||
|
||||
/** A list read, plus what Home's Routine runs switch hides (absent from older control planes). */
|
||||
export type CloudWorkspaceListResult =
|
||||
| { ok: true; value: CloudWorkspace[]; routineRuns?: CloudWorkspaceRoutineRuns }
|
||||
| { ok: false; error: string; reason?: string; status?: number }
|
||||
|
||||
/** Where this desktop already has a cloud workspace locally (owner: the hosted runtime it created). */
|
||||
@@ -42,7 +51,13 @@ async function wrap<T>(run: () => Promise<T>): Promise<CloudWorkspacesResult<T>>
|
||||
return { ok: true, value: await run() }
|
||||
} catch (error) {
|
||||
if (error instanceof CloudWorkspacesError) {
|
||||
return { ok: false, error: error.code, reason: error.reason, status: error.status }
|
||||
return {
|
||||
ok: false,
|
||||
error: error.code,
|
||||
reason: error.reason,
|
||||
status: error.status,
|
||||
...(error.orgId ? { orgId: error.orgId } : {})
|
||||
}
|
||||
}
|
||||
return { ok: false, error: 'internal_error', reason: errorMessage(error).slice(0, 200) }
|
||||
}
|
||||
@@ -134,13 +149,17 @@ export function createCloudWorkspacesService(deps: {
|
||||
|
||||
return {
|
||||
available: true as const,
|
||||
list: (query: CloudWorkspaceListQuery) =>
|
||||
wrap(async () => {
|
||||
const workspaces = await client.list(query)
|
||||
list: async (query: CloudWorkspaceListQuery): Promise<CloudWorkspaceListResult> => {
|
||||
let routineRuns: CloudWorkspaceRoutineRuns | undefined
|
||||
const result = await wrap(async () => {
|
||||
const page = await client.list(query)
|
||||
routineRuns = page.routineRuns
|
||||
// Cheap when already registered; catches a sign-in or account switch since the last list.
|
||||
void reader?.register()
|
||||
return workspaces
|
||||
}),
|
||||
return page.workspaces
|
||||
})
|
||||
return result.ok && routineRuns ? { ...result, routineRuns } : result
|
||||
},
|
||||
/** Sign-out: revoke this device's reader key server-side (callers bound the wait). */
|
||||
revokeReaderKey: (timeoutMs: number) => reader?.revoke(timeoutMs) ?? Promise.resolve(),
|
||||
/** A sleeping workspace's sealed snapshot, opened on this device; never wakes it. */
|
||||
@@ -154,14 +173,24 @@ export function createCloudWorkspacesService(deps: {
|
||||
get: (id: string) => wrap(() => client.get(id)),
|
||||
patch: (id: string, patch: CloudWorkspacePatch) =>
|
||||
wrap(async () => (await client.patch(id, patch)).workspace),
|
||||
resolveLink: (workspaceId: string, chatId?: string | null) =>
|
||||
wrap(() => client.resolveLink(workspaceId, chatId)),
|
||||
resolveLink: (target: CloudWorkspaceLinkTarget, chatId?: string | null) =>
|
||||
wrap(() => client.resolveLink(target, chatId)),
|
||||
getPrefs: () => wrap(() => client.getPrefs()),
|
||||
putPrefs: (document: CloudWorkspacePrefsDocument, revision: number) =>
|
||||
wrap(() => client.putPrefs(document, revision, deps.clientId)),
|
||||
getOrgSlug: (name?: string | null) => wrap(() => client.getOrgSlug(name)),
|
||||
listGrants: (id: string) => wrap(() => client.listGrants(id)),
|
||||
revokeGrant: (id: string, grantId: string) =>
|
||||
wrap(async () => void (await client.revokeGrant(id, grantId))),
|
||||
getOrgPrompts: () => wrap(() => client.getOrgPrompts()),
|
||||
putOrgPrompts: (document: OrgPrompts['document'], revision: number) =>
|
||||
wrap(() => client.putOrgPrompts(document, revision)),
|
||||
teammateProfile: (userId: string, utcOffsetMin: number) =>
|
||||
wrap(() => client.teammateProfile(userId, utcOffsetMin)),
|
||||
poke: (userId: string) => wrap(() => client.poke(userId)),
|
||||
pokeInbox: () => wrap(() => client.pokeInbox()),
|
||||
setPokesEnabled: (enabled: boolean) => wrap(() => client.setPokesEnabled(enabled)),
|
||||
markPokesSeen: (ids: string[]) => wrap(() => client.markPokesSeen(ids)),
|
||||
localWorkspaces: () => localWorkspaces(),
|
||||
noteSent: (id: string) => wrap(() => client.noteSent(id)),
|
||||
sleep: (id: string) => wrap(() => client.sleep(id)),
|
||||
|
||||
@@ -87,7 +87,9 @@ export async function checkSetup(
|
||||
'Setup script is configured and has run here. Use --run-setup to check its exit code.'
|
||||
)
|
||||
: check('setup', 'setup.run', 'warn', 'Setup script is configured but has not run here.', {
|
||||
remediation: 'Re-run the doctor with --run-setup to run it and check the result.'
|
||||
remediation: 'Re-run the doctor with --run-setup to run it and check the result.',
|
||||
// Desktop clients show their own words (no CLI flags) for this code.
|
||||
code: 'setupNotRun'
|
||||
})
|
||||
]
|
||||
}
|
||||
|
||||
@@ -18,6 +18,11 @@ export type EnvironmentProviderPhase =
|
||||
| 'booting'
|
||||
/** The repo clones in the VM after it is up; `percent` is git's overall progress. */
|
||||
| 'cloning'
|
||||
/** The repo came prebuilt (an environment build): only what changed is fetched. */
|
||||
| 'updating'
|
||||
/** Before the create answers: whether its repository step will clone or update (names the step once). */
|
||||
| 'plan-clone'
|
||||
| 'plan-update'
|
||||
| 'connecting'
|
||||
| 'suspending'
|
||||
| 'resuming'
|
||||
@@ -37,6 +42,8 @@ export type EnvironmentCreateSpec = {
|
||||
/** Orca's workspace id; one environment per workspace. */
|
||||
workspaceId: string
|
||||
workspaceName?: string
|
||||
/** One per user intent; the provider dedupes creates by it (Idempotency-Key). */
|
||||
idempotencyKey?: string
|
||||
projectId?: string
|
||||
machineSize?: string
|
||||
region?: string
|
||||
|
||||
@@ -33,6 +33,8 @@ export type ProvisionEphemeralVmRuntimeArgs = {
|
||||
projectId?: string
|
||||
workspaceId?: string
|
||||
workspaceName?: string
|
||||
/** One per Create press (Orca Cloud): the create's Idempotency-Key. */
|
||||
idempotencyKey?: string
|
||||
repoUrl?: string
|
||||
branch?: string
|
||||
ref?: string
|
||||
@@ -102,6 +104,7 @@ export async function provisionEphemeralVmRuntime(
|
||||
projectId: args.projectId,
|
||||
workspaceId: args.workspaceId,
|
||||
workspaceName: args.workspaceName,
|
||||
...(args.idempotencyKey ? { idempotencyKey: args.idempotencyKey } : {}),
|
||||
repoUrl: args.repoUrl,
|
||||
branch: args.branch,
|
||||
ref: args.ref,
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
type HostedSandboxView
|
||||
} from '../../shared/hosted-sandbox/hosted-sandbox-wire'
|
||||
import {
|
||||
HostedBootPlanResponseSchema,
|
||||
HostedCloneStatusResponseSchema,
|
||||
type HostedCloneStatus
|
||||
} from '../../shared/hosted-sandbox/hosted-clone-wire'
|
||||
@@ -51,9 +52,13 @@ type HostedGithubConnectResponse = z.infer<typeof HostedGithubConnectResponseSch
|
||||
export type HostedSandboxControlPlaneClient = {
|
||||
create(
|
||||
body: HostedSandboxCreateRequest,
|
||||
signal?: AbortSignal
|
||||
signal?: AbortSignal,
|
||||
/** Idempotency-Key: one per user intent; a repeat returns the first create's sandbox (24 h). */
|
||||
idempotencyKey?: string
|
||||
): Promise<HostedSandboxReadyResponse>
|
||||
get(sandboxId: string, signal?: AbortSignal): Promise<HostedSandboxView>
|
||||
/** Whether a create of `repoUrl` would clone it or update a prebuilt copy (environment build). */
|
||||
bootPlan(repoUrl: string, signal?: AbortSignal): Promise<'clone' | 'update'>
|
||||
/** The background clone a create started (create answered with `clone`). */
|
||||
cloneStatus(sandboxId: string, signal?: AbortSignal): Promise<HostedCloneStatus>
|
||||
list(signal?: AbortSignal): Promise<HostedSandboxView[]>
|
||||
@@ -133,14 +138,25 @@ export function createHostedSandboxControlPlaneClient(
|
||||
`v1/sandboxes/${encodeURIComponent(id)}${suffix}`
|
||||
|
||||
return {
|
||||
create: (body, signal) =>
|
||||
create: (body, signal, idempotencyKey) =>
|
||||
call('POST', 'v1/sandboxes', HostedSandboxReadyResponseSchema, {
|
||||
body,
|
||||
kind: 'boot',
|
||||
signal,
|
||||
...(idempotencyKey ? { headers: { 'idempotency-key': idempotencyKey } } : {}),
|
||||
// The repo clones after the sandbox is up; the driver shows it as its own step.
|
||||
features: ['clone-progress']
|
||||
// An environment boot reports its incremental fetch as an update (`clone.mode`).
|
||||
features: ['clone-progress', 'repo-update']
|
||||
}),
|
||||
bootPlan: async (repoUrl, signal) =>
|
||||
(
|
||||
await call(
|
||||
'GET',
|
||||
`v1/sandboxes/boot-plan?repo=${encodeURIComponent(repoUrl)}`,
|
||||
HostedBootPlanResponseSchema,
|
||||
{ kind: 'control', signal }
|
||||
)
|
||||
).repo,
|
||||
cloneStatus: async (id, signal) =>
|
||||
(
|
||||
await call('GET', sandboxPath(id, '/clone'), HostedCloneStatusResponseSchema, {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user