Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

fix(runtime): bind observability writes to run owners (#135)

OKNOTOK81fec44f13c0
diff --git a/server/src/__integration__/runtime-server.test.ts b/server/src/__integration__/runtime-server.test.ts
index 229eaad..06c3724 100644
--- a/server/src/__integration__/runtime-server.test.ts
+++ b/server/src/__integration__/runtime-server.test.ts
@@ -21,17 +21,18 @@
* require the real HTTP/JWT/runCli chain. Lower-level argv normalization
* remains exhaustively covered in agents-runtime-cli-argv.test.ts.
*/
-import { test, before, beforeEach, after } from 'node:test'
+
import assert from 'node:assert/strict'
-import { createServer, type Server } from 'node:http'
import { randomUUID } from 'node:crypto'
import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'
+import { createServer, type Server } from 'node:http'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
-import { ensureSchemaOnce, resetAllTables, teardownAll } from './_helpers.js'
+import { after, before, beforeEach, test } from 'node:test'
import { mintAgentRuntimeToken } from '../agents/computer/registry.js'
import { signAgentToken, verifyAgentToken } from '../agents/runtime/jwt.js'
import { pool } from '../db/pool.js'
+import { ensureSchemaOnce, resetAllTables, teardownAll } from './_helpers.js'
let server: Server
let baseUrl = ''
@@ -94,6 +95,41 @@ async function callRaw(
return { status: res.status, body: await res.text() }
}
+/** The runtime endpoint now awaits one atomic batch. Still drain the pool in
+ * zero-write checks so a future regression to the generic fire-and-forget
+ * recorder cannot pass merely because its INSERT lands after the assertion. */
+async function waitForPoolIdle(timeoutMs = 5_000): Promise<void> {
+ const deadline = Date.now() + timeoutMs
+ let stablePasses = 0
+ while (Date.now() < deadline) {
+ await new Promise((resolve) => setTimeout(resolve, 10))
+ if (pool.waitingCount === 0 && pool.idleCount === pool.totalCount) {
+ stablePasses += 1
+ if (stablePasses >= 3) return
+ } else {
+ stablePasses = 0
+ }
+ }
+ assert.fail('timed out waiting for queued ledger queries to drain')
+}
+
+async function waitForBlockedQuery(pattern: string, minimum = 1): Promise<void> {
+ for (let attempt = 0; attempt < 200; attempt += 1) {
+ const { rows } = await pool.query<{ count: number }>(
+ `SELECT COUNT(*)::int AS count
+ FROM pg_stat_activity
+ WHERE datname = current_database()
+ AND pid <> pg_backend_pid()
+ AND wait_event_type = 'Lock'
+ AND query ILIKE $1`,
+ [pattern],
+ )
+ if ((rows[0]?.count ?? 0) >= minimum) return
+ await new Promise((resolve) => setTimeout(resolve, 10))
+ }
+ throw new Error(`query never reached the expected row lock: ${pattern}`)
+}
+
async function seedAgent(): Promise<{ agentId: string; companyId: string; token: string }> {
const companyId = `c-${randomUUID().slice(0, 8)}`
const agentId = `a-${randomUUID().slice(0, 8)}`
@@ -110,6 +146,87 @@ async function seedAgent(): Promise<{ agentId: string; companyId: string; token:
return { agentId, companyId, token }
}
+async function seedPeerAgent(companyId: string): Promise<{ agentId: string; companyId: string; token: string }> {
+ const agentId = `a-${randomUUID().slice(0, 8)}`
+ await pool.query(
+ `INSERT INTO participants (id, company_id, kind, name, role, initial, avatar_bg, status)
+ VALUES ($1, $2, 'agent', $3, 'tester', $4, '#abcdef', 'avail')`,
+ [agentId, companyId, agentId, agentId.slice(0, 1).toUpperCase()],
+ )
+ return { agentId, companyId, token: signAgentToken({ agentId, companyId }) }
+}
+
+async function assertCannotMutateForeignRun(args: {
+ ownerToken: string
+ attackerToken: string
+}): Promise<string> {
+ const created = await call('/runtime/runs', {
+ token: args.ownerToken,
+ body: { trigger: { kind: 'ownership-test' }, inboxCount: 0 },
+ })
+ assert.equal(created.status, 200)
+ assert.equal(typeof created.body?.runId, 'string')
+ const runId = created.body.runId as string
+ assert.match(runId, /^run-/)
+ await pool.query(
+ `UPDATE agent_runs SET updated_at = '2000-01-01T00:00:00Z'::timestamptz WHERE id = $1`,
+ [runId],
+ )
+
+ const snapshot = async () => {
+ const { rows } = await pool.query(
+ `SELECT status, stage, summary, error, tool_call_count, token_count,
+ updated_at::text, finished_at::text
+ FROM agent_runs WHERE id = $1`,
+ [runId],
+ )
+ return rows[0]
+ }
+ const before = await snapshot()
+ assert.ok(before, 'owner run fixture must exist before the attack')
+
+ const attempts = [
+ await call('/runtime/events', {
+ token: args.attackerToken,
+ body: {
+ runId,
+ kind: 'forged.event',
+ title: 'must not land',
+ stage: 'forged',
+ },
+ }),
+ await call(`/runtime/runs/${runId}/heartbeat`, {
+ token: args.attackerToken,
+ body: {},
+ }),
+ await call(`/runtime/runs/${runId}/finish`, {
+ token: args.attackerToken,
+ body: { status: 'failed', summary: 'forged finish', tokenCount: 999 },
+ }),
+ await call('/runtime/llm-calls', {
+ token: args.attackerToken,
+ body: {
+ source: 'byoa-codex',
+ hops: [{ runId, model: 'forged-model', latencyMs: 1, status: 'ok' }],
+ },
+ }),
+ ]
+ for (const attempt of attempts) {
+ assert.equal(attempt.status, 404)
+ assert.match(String(attempt.body?.error ?? ''), /agent run not found/i)
+ }
+
+ await waitForPoolIdle()
+ assert.deepEqual(await snapshot(), before, 'foreign requests must not alter the run row')
+ const [{ rows: eventRows }, { rows: ledgerRows }] = await Promise.all([
+ pool.query(`SELECT id FROM agent_events WHERE run_id = $1`, [runId]),
+ pool.query(`SELECT id FROM llm_calls WHERE run_id = $1`, [runId]),
+ ])
+ assert.equal(eventRows.length, 0, 'foreign event must not be inserted')
+ assert.equal(ledgerRows.length, 0, 'foreign run must not be attached to an LLM ledger row')
+ return runId
+}
+
async function mintAssignedAgentRuntimeToken(args: {
agentId: string
companyId: string
@@ -681,6 +798,159 @@ test('[integration] runtime: /events row uses JWT subject for agent_id', async (
assert.equal(rows[0].company_id, companyId)
})
+test('[integration] runtime: same-tenant agents cannot mutate each other\'s run observability', async () => {
+ const owner = await seedAgent()
+ const attacker = await seedPeerAgent(owner.companyId)
+ await assertCannotMutateForeignRun({
+ ownerToken: owner.token,
+ attackerToken: attacker.token,
+ })
+})
+
+test('[integration] runtime: cross-tenant agents cannot mutate another tenant\'s run observability', async () => {
+ const owner = await seedAgent()
+ const attacker = await seedAgent()
+ await assertCannotMutateForeignRun({
+ ownerToken: owner.token,
+ attackerToken: attacker.token,
+ })
+})
+
+test('[integration] runtime: /llm-calls rejects a mixed-owner batch atomically', async () => {
+ const caller = await seedAgent()
+ const foreign = await seedAgent()
+ const ownRun = await call('/runtime/runs', {
+ token: caller.token,
+ body: { trigger: { kind: 'own' }, inboxCount: 0 },
+ })
+ const foreignRun = await call('/runtime/runs', {
+ token: foreign.token,
+ body: { trigger: { kind: 'foreign' }, inboxCount: 0 },
+ })
+ assert.equal(ownRun.status, 200)
+ assert.equal(foreignRun.status, 200)
+ assert.equal(typeof ownRun.body?.runId, 'string')
+ assert.equal(typeof foreignRun.body?.runId, 'string')
+ const runIds = [ownRun.body.runId as string, foreignRun.body.runId as string]
+ assert.ok(runIds.every((runId) => runId.startsWith('run-')))
+ assert.notEqual(runIds[0], runIds[1])
+
+ const rejected = await call('/runtime/llm-calls', {
+ token: caller.token,
+ body: {
+ source: 'byoa-codex',
+ hops: runIds.map((runId) => ({ runId, model: 'test-model', latencyMs: 1, status: 'ok' })),
+ },
+ })
+ assert.equal(rejected.status, 404)
+ assert.match(String(rejected.body?.error ?? ''), /agent run not found/i)
+
+ await waitForPoolIdle()
+ const { rows } = await pool.query(
+ `SELECT id FROM llm_calls WHERE run_id = ANY($1::text[])`,
+ [runIds],
+ )
+ assert.equal(rows.length, 0, 'an unauthorized hop must reject the whole batch before inserts start')
+})
+
+test('[integration] runtime: /llm-calls rejects oversized batches before scheduling inserts', async () => {
+ const caller = await seedAgent()
+ const model = `oversized-${randomUUID()}`
+ const rejected = await call('/runtime/llm-calls', {
+ token: caller.token,
+ body: {
+ source: 'byoa-codex',
+ hops: Array.from({ length: 101 }, () => ({ model, latencyMs: 1, status: 'ok' })),
+ },
+ })
+ assert.equal(rejected.status, 413)
+ assert.match(String(rejected.body?.error ?? ''), /too many hops/i)
+
+ await waitForPoolIdle()
+ const { rows } = await pool.query(
+ `SELECT id FROM llm_calls WHERE agent_id = $1 AND model = $2`,
+ [caller.agentId, model],
+ )
+ assert.equal(rows.length, 0, 'oversized batches must be rejected before fire-and-forget inserts start')
+})
+
+test('[integration] runtime: offboarding that wins the participant lock cancels every pending run mutation', async () => {
+ const owner = await seedAgent()
+ const created = await call('/runtime/runs', {
+ token: owner.token,
+ body: { trigger: { kind: 'offboard-race' }, inboxCount: 0 },
+ })
+ assert.equal(created.status, 200)
+ assert.equal(typeof created.body?.runId, 'string')
+ const runId = created.body.runId as string
+ const ledgerModel = `offboard-race-${randomUUID()}`
+ await pool.query(
+ `UPDATE agent_runs SET updated_at = '2000-01-01T00:00:00Z'::timestamptz WHERE id = $1`,
+ [runId],
+ )
+
+ const offboarder = await pool.connect()
+ let committed = false
+ let pending: Promise<Array<{ status: number; body: any }>> | undefined
+ try {
+ await offboarder.query('BEGIN')
+ await offboarder.query(
+ `UPDATE participants SET departed_at = NOW() WHERE id = $1 AND company_id = $2`,
+ [owner.agentId, owner.companyId],
+ )
+ pending = Promise.all([
+ call('/runtime/events', {
+ token: owner.token,
+ body: { runId, kind: 'must.not.land', title: 'revoked', stage: 'revoked' },
+ }),
+ call(`/runtime/runs/${runId}/heartbeat`, { token: owner.token, body: {} }),
+ call(`/runtime/runs/${runId}/finish`, {
+ token: owner.token,
+ body: { status: 'failed', summary: 'must not land' },
+ }),
+ call('/runtime/llm-calls', {
+ token: owner.token,
+ body: {
+ source: 'byoa-codex',
+ hops: [{ runId, model: ledgerModel, latencyMs: 1, status: 'ok' }],
+ },
+ }),
+ ])
+ await waitForBlockedQuery('%FROM participants%FOR SHARE%', 4)
+ await offboarder.query('COMMIT')
+ committed = true
+ } finally {
+ if (!committed) await offboarder.query('ROLLBACK').catch(() => {})
+ offboarder.release()
+ }
+
+ const results = await pending!
+ for (const result of results) {
+ assert.equal(result.status, 404)
+ assert.match(String(result.body?.error ?? ''), /agent run not found/i)
+ }
+ const { rows: runRows } = await pool.query(
+ `SELECT status, stage, summary,
+ updated_at = '2000-01-01T00:00:00Z'::timestamptz AS unchanged,
+ finished_at IS NULL AS unfinished
+ FROM agent_runs WHERE id = $1`,
+ [runId],
+ )
+ assert.deepEqual(runRows, [{
+ status: 'running',
+ stage: 'created',
+ summary: null,
+ unchanged: true,
+ unfinished: true,
+ }])
+ const [{ rowCount: eventCount }, { rowCount: ledgerCount }] = await Promise.all([
+ pool.query(`SELECT 1 FROM agent_events WHERE run_id = $1`, [runId]),
+ pool.query(`SELECT 1 FROM llm_calls WHERE run_id = $1 AND model = $2`, [runId, ledgerModel]),
+ ])
+ assert.equal(eventCount, 0)
+ assert.equal(ledgerCount, 0)
+})
+
// ── payload validation ────────────────────────────────────────────────
test('[integration] runtime: /events 400 when runId / kind / title is missing', async () => {
@@ -708,6 +978,77 @@ test('[integration] runtime: /runs/:runId/finish 400 when status missing', async
assert.equal(r.status, 400)
})
+test('[integration] runtime: malformed observability fields are rejected before writes', async () => {
+ const caller = await seedAgent()
+ const created = await call('/runtime/runs', {
+ token: caller.token,
+ body: { trigger: { kind: 'malformed' }, inboxCount: 0 },
+ })
+ assert.equal(created.status, 200)
+ assert.equal(typeof created.body?.runId, 'string')
+ const runId = created.body.runId as string
+ const model = `malformed-${randomUUID()}`
+
+ const attempts = [
+ await call('/runtime/events', {
+ token: caller.token,
+ body: { runId, kind: 'bad.event', title: 'bad', level: 'critical' },
+ }),
+ await call(`/runtime/runs/${runId}/finish`, {
+ token: caller.token,
+ body: { status: 'invented-status' },
+ }),
+ await call(`/runtime/runs/${runId}/finish`, {
+ token: caller.token,
+ body: {
+ status: 'completed',
+ usage: { inputTokens: '1', cachedInputTokens: 0, cacheCreationTokens: 0, outputTokens: 0 },
+ },
+ }),
+ await call(`/runtime/runs/${runId}/finish`, {
+ token: caller.token,
+ body: { status: 'completed', tokenCount: 2_147_483_648 },
+ }),
+ await call(`/runtime/runs/${runId}/finish`, {
+ token: caller.token,
+ body: {
+ status: 'completed',
+ usage: {
+ inputTokens: 2_147_483_647,
+ cachedInputTokens: 1,
+ cacheCreationTokens: 0,
+ outputTokens: 0,
+ },
+ },
+ }),
+ await call('/runtime/llm-calls', {
+ token: caller.token,
+ body: { source: 'byoa-codex', hops: { runId, model } },
+ }),
+ await call('/runtime/llm-calls', {
+ token: caller.token,
+ body: {
+ source: 'byoa-codex',
+ hops: [{ runId, model, status: 'invented-status', error: { secret: 'must not reach a 500' } }],
+ },
+ }),
+ await call('/runtime/llm-calls', {
+ token: caller.token,
+ body: { source: 'byoa-codex', hops: [{ runId, model, status: 'ok', latencyMs: 1.5 }] },
+ }),
+ ]
+ for (const attempt of attempts) assert.equal(attempt.status, 400)
+
+ const [{ rows: runRows }, { rowCount: eventCount }, { rowCount: ledgerCount }] = await Promise.all([
+ pool.query(`SELECT status, stage, finished_at FROM agent_runs WHERE id = $1`, [runId]),
+ pool.query(`SELECT 1 FROM agent_events WHERE run_id = $1`, [runId]),
+ pool.query(`SELECT 1 FROM llm_calls WHERE run_id = $1 AND model = $2`, [runId, model]),
+ ])
+ assert.deepEqual(runRows, [{ status: 'running', stage: 'created', finished_at: null }])
+ assert.equal(eventCount, 0)
+ assert.equal(ledgerCount, 0)
+})
+
test('[integration] runtime: /notices 400 when any of the required fields missing', async () => {
const { token } = await seedAgent()
const r = await call('/runtime/notices', { token, body: { conversationId: 'c-1' } })
@@ -723,6 +1064,20 @@ test('[integration] runtime: /runs + /runs/:runId/finish persists status transit
assert.equal(created.status, 200)
const runId = String(created.body.runId)
+ await pool.query(
+ `UPDATE agent_runs SET updated_at = '2000-01-01T00:00:00Z'::timestamptz WHERE id = $1`,
+ [runId],
+ )
+ const heartbeat = await call(`/runtime/runs/${runId}/heartbeat`, { token, body: {} })
+ assert.equal(heartbeat.status, 200)
+ assert.equal(heartbeat.body?.touched, true)
+ const { rows: heartbeatRows } = await pool.query<{ touched: boolean }>(
+ `SELECT updated_at > '2000-01-01T00:00:00Z'::timestamptz AS touched
+ FROM agent_runs WHERE id = $1`,
+ [runId],
+ )
+ assert.equal(heartbeatRows[0]?.touched, true)
+
const done = await call(`/runtime/runs/${runId}/finish`, {
token, body: { status: 'completed', summary: 'ok', toolCallCount: 3, tokenCount: 1234 },
})
@@ -739,3 +1094,85 @@ test('[integration] runtime: /runs + /runs/:runId/finish persists status transit
assert.equal(rows[0].token_count, 1234)
assert.equal(rows[0].agent_id, agentId)
})
+
+test('[integration] runtime: /llm-calls atomically records multiple caller-owned hops', async () => {
+ const caller = await seedAgent()
+ const created = await call('/runtime/runs', {
+ token: caller.token,
+ body: { trigger: { kind: 'llm-ledger' }, inboxCount: 0 },
+ })
+ assert.equal(created.status, 200)
+ assert.equal(typeof created.body?.runId, 'string')
+ const runId = created.body.runId as string
+ const prefix = `owned-${randomUUID()}`
+ const models = [`${prefix}-1`, `${prefix}-2`, `${prefix}-3`]
+ const recorded = await call('/runtime/llm-calls', {
+ token: caller.token,
+ body: {
+ source: 'byoa-codex',
+ daemonVersion: '9.9.9-test',
+ hops: [
+ {
+ runId,
+ purpose: 'agent-turn',
+ model: models[0],
+ usage: { inputTokens: 1, cachedInputTokens: 2, cacheCreationTokens: 3, outputTokens: 4 },
+ latencyMs: 7,
+ status: 'ok',
+ extras: { hop: 1 },
+ },
+ {
+ runId,
+ purpose: 'compaction',
+ model: models[1],
+ latencyMs: 8,
+ status: 'failed',
+ error: 'expected test failure',
+ extras: { hop: 2 },
+ },
+ {
+ runId,
+ purpose: 'completion-verify',
+ model: models[2],
+ usage: { inputTokens: 5, cachedInputTokens: 6, cacheCreationTokens: 7, outputTokens: 8 },
+ latencyMs: 9,
+ status: 'rate_limited',
+ extras: { hop: 3 },
+ },
+ ],
+ },
+ })
+ assert.equal(recorded.status, 200)
+ assert.equal(recorded.body?.inserted, 3)
+
+ await waitForPoolIdle()
+ const { rows } = await pool.query(
+ `SELECT agent_id, company_id, run_id, purpose, source, model,
+ input_tokens, cached_input_tokens, cache_creation_tokens, output_tokens,
+ measured, latency_ms, status, error, extras, daemon_version
+ FROM llm_calls
+ WHERE run_id = $1 AND model = ANY($2::text[])
+ ORDER BY model`,
+ [runId, models],
+ )
+ assert.deepEqual(rows, [
+ {
+ agent_id: caller.agentId, company_id: caller.companyId, run_id: runId,
+ purpose: 'agent-turn', source: 'byoa-codex', model: models[0],
+ input_tokens: 1, cached_input_tokens: 2, cache_creation_tokens: 3, output_tokens: 4,
+ measured: true, latency_ms: 7, status: 'ok', error: null, extras: { hop: 1 }, daemon_version: '9.9.9-test',
+ },
+ {
+ agent_id: caller.agentId, company_id: caller.companyId, run_id: runId,
+ purpose: 'compaction', source: 'byoa-codex', model: models[1],
+ input_tokens: 0, cached_input_tokens: 0, cache_creation_tokens: 0, output_tokens: 0,
+ measured: false, latency_ms: 8, status: 'failed', error: 'expected test failure', extras: { hop: 2 }, daemon_version: '9.9.9-test',
+ },
+ {
+ agent_id: caller.agentId, company_id: caller.companyId, run_id: runId,
+ purpose: 'completion-verify', source: 'byoa-codex', model: models[2],
+ input_tokens: 5, cached_input_tokens: 6, cache_creation_tokens: 7, output_tokens: 8,
+ measured: true, latency_ms: 9, status: 'rate_limited', error: null, extras: { hop: 3 }, daemon_version: '9.9.9-test',
+ },
+ ])
+})
diff --git a/server/src/agents/llm-ledger.ts b/server/src/agents/llm-ledger.ts
index cc06400..b914b2c 100644
--- a/server/src/agents/llm-ledger.ts
+++ b/server/src/agents/llm-ledger.ts
@@ -40,9 +40,10 @@
import { randomUUID } from 'node:crypto'
import type OpenAI from 'openai'
+import type { PoolClient } from 'pg'
import { pool } from '../db/pool.js'
import { getLlmClient } from '../llm.js'
-import { effectiveCostUsd, priceFor, usageFromOpenAI, EMPTY_USAGE, type TokenUsage } from './cost.js'
+import { EMPTY_USAGE, effectiveCostUsd, priceFor, type TokenUsage, usageFromOpenAI } from './cost.js'
/** The exhaustive set of business purposes that spend sub2api. Adding a new
* callsite REQUIRES adding its purpose here — that's the discipline knob that
@@ -110,43 +111,76 @@ export interface LlmCallRecord extends LlmCallContext {
daemonVersion?: string | null
}
-/** Single INSERT into `llm_calls`. Never throws — the ledger is observability,
- * not a hard dependency of the call path. */
-export async function recordLlmCall(rec: LlmCallRecord): Promise<void> {
+const LLM_CALL_COLUMNS = `
+ id, company_id, agent_id, run_id, conversation_id,
+ purpose, source, model,
+ input_tokens, cached_input_tokens, cache_creation_tokens,
+ output_tokens, reasoning_tokens,
+ cost_usd, cost_estimated, measured,
+ latency_ms, status, error, extras, daemon_version
+`
+
+function llmCallValues(rec: LlmCallRecord): unknown[] {
const measured = !!rec.usage
const usage = rec.usage ?? EMPTY_USAGE
// Cost is computed at insert time so the row is meaningful on its own.
// A later operator price change re-prices new rows only; if we later want
// back-fill, the breakdown is preserved so a recompute is one UPDATE away.
const cost = effectiveCostUsd(rec.model, usage)
+ return [
+ `llm-${randomUUID()}`,
+ rec.companyId, rec.agentId ?? null, rec.runId ?? null, rec.conversationId ?? null,
+ rec.purpose, rec.source ?? 'cloud', rec.model,
+ usage.inputTokens, usage.cachedInputTokens, usage.cacheCreationTokens,
+ usage.outputTokens, rec.reasoningTokens ?? 0,
+ measured ? cost.usd : 0, cost.estimated, measured,
+ rec.latencyMs, rec.status,
+ rec.error ? rec.error.slice(0, 500) : null,
+ rec.extras ? JSON.stringify(rec.extras) : null,
+ rec.daemonVersion ?? null,
+ ]
+}
+
+async function insertLlmCall(rec: LlmCallRecord): Promise<void> {
+ await pool.query(
+ `INSERT INTO llm_calls (${LLM_CALL_COLUMNS})
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20::jsonb,$21)`,
+ llmCallValues(rec),
+ )
+}
+
+/** Single INSERT into `llm_calls`. Never throws — the ledger is observability,
+ * not a hard dependency of the call path. */
+export async function recordLlmCall(rec: LlmCallRecord): Promise<void> {
try {
- await pool.query(
- `INSERT INTO llm_calls (
- id, company_id, agent_id, run_id, conversation_id,
- purpose, source, model,
- input_tokens, cached_input_tokens, cache_creation_tokens,
- output_tokens, reasoning_tokens,
- cost_usd, cost_estimated, measured,
- latency_ms, status, error, extras, daemon_version
- ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20::jsonb,$21)`,
- [
- `llm-${randomUUID()}`,
- rec.companyId, rec.agentId ?? null, rec.runId ?? null, rec.conversationId ?? null,
- rec.purpose, rec.source ?? 'cloud', rec.model,
- usage.inputTokens, usage.cachedInputTokens, usage.cacheCreationTokens,
- usage.outputTokens, rec.reasoningTokens ?? 0,
- measured ? cost.usd : 0, cost.estimated, measured,
- rec.latencyMs, rec.status,
- rec.error ? rec.error.slice(0, 500) : null,
- rec.extras ? JSON.stringify(rec.extras) : null,
- rec.daemonVersion ?? null,
- ],
- )
+ await insertLlmCall(rec)
} catch (err) {
console.warn('[llm-ledger] insert failed — dropping', err instanceof Error ? err.message : err)
}
}
+/** One atomic statement for a runtime hop batch. Unlike the best-effort public
+ * recorder, this deliberately throws so the surrounding authorization
+ * transaction can roll back every row together. */
+export async function recordLlmCallsBatch(
+ records: readonly LlmCallRecord[],
+ client: PoolClient,
+): Promise<void> {
+ if (records.length === 0) return
+ const values = records.flatMap(llmCallValues)
+ const rows = records.map((_, rowIndex) => {
+ const offset = rowIndex * 21
+ return `(${Array.from({ length: 21 }, (_value, columnIndex) => {
+ const placeholder = `$${offset + columnIndex + 1}`
+ return columnIndex === 19 ? `${placeholder}::jsonb` : placeholder
+ }).join(',')})`
+ })
+ await client.query(
+ `INSERT INTO llm_calls (${LLM_CALL_COLUMNS}) VALUES ${rows.join(',')}`,
+ values,
+ )
+}
+
/** Classify a thrown LLM error into one of the ledger's `status` buckets.
* Rate-limit detection mirrors `triage-core.isRateLimited` and the inbox-triage
* fail-closed branch so the same kinds of failures get the same label here.
diff --git a/server/src/agents/observability.ts b/server/src/agents/observability.ts
index 8e039e2..c550df5 100644
--- a/server/src/agents/observability.ts
+++ b/server/src/agents/observability.ts
@@ -1,11 +1,14 @@
import { randomUUID } from 'node:crypto'
+import type { PoolClient } from 'pg'
import { pool } from '../db/pool.js'
-import { effectiveCostUsd, priceFor, modelPriceTable, EMPTY_USAGE, type TokenUsage } from './cost.js'
+import { EMPTY_USAGE, effectiveCostUsd, modelPriceTable, priceFor, type TokenUsage } from './cost.js'
export type AgentRunStatus = 'running' | 'completed' | 'failed' | 'skipped'
export type TriageSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode' | 'byoa-pi' | 'byoa-gemini'
export type AgentEventLevel = 'debug' | 'info' | 'warn' | 'error'
+type Queryable = Pick<PoolClient, 'query'>
+
const MAX_STRING_CHARS = 24_000
const MAX_JSON_CHARS = 160_000
@@ -46,9 +49,9 @@ export async function createAgentRun(args: {
inputMessageIds?: string[]
inboxCount?: number
fingerprint?: string
-}): Promise<string> {
+}, db: Queryable = pool): Promise<string> {
const id = `run-${randomUUID()}`
- await pool.query(
+ await db.query(
`INSERT INTO agent_runs (
id, agent_id, company_id, trigger, status, stage,
input_message_ids, inbox_count, fingerprint
@@ -100,27 +103,91 @@ export async function recordAgentEvent(args: {
)
}
-export async function finishAgentRun(args: {
+/** Record a daemon-supplied event only when the JWT-pinned agent still owns
+ * the target run. The authorization predicate lives in the same statement as
+ * the INSERT so a guessed run id can never create an event or bump another
+ * agent's stage between a route-level check and the write itself. */
+export async function recordAgentEventForOwner(args: {
+ runId: string
+ agentId: string
+ companyId: string
+ kind: string
+ level?: AgentEventLevel
+ title: string
+ data?: Record<string, unknown>
+ stage?: string
+}, db: Queryable = pool): Promise<boolean> {
+ const result = await db.query(
+ `WITH owned_run AS MATERIALIZED (
+ SELECT ar.id
+ FROM agent_runs ar
+ WHERE ar.id = $2
+ AND ar.agent_id = $3
+ AND ar.company_id = $4
+ AND EXISTS (
+ SELECT 1 FROM participants p
+ WHERE p.id = $3 AND p.company_id = $4
+ AND p.kind = 'agent' AND p.departed_at IS NULL
+ )
+ ), inserted AS (
+ INSERT INTO agent_events (id, run_id, agent_id, company_id, kind, level, title, data)
+ SELECT $1, owned_run.id, $3, $4, $5, $6, $7, $8::jsonb
+ FROM owned_run
+ RETURNING run_id
+ )
+ UPDATE agent_runs ar
+ SET updated_at = NOW(),
+ stage = COALESCE($9, ar.stage)
+ FROM inserted
+ WHERE ar.id = inserted.run_id
+ RETURNING ar.id`,
+ [
+ `evt-${randomUUID()}`,
+ args.runId,
+ args.agentId,
+ args.companyId,
+ args.kind,
+ args.level ?? 'info',
+ args.title,
+ jsonForDb(args.data ?? {}),
+ args.stage ?? null,
+ ],
+ )
+ return result.rowCount === 1
+}
+
+interface FinishAgentRunArgs {
runId: string
status: AgentRunStatus
summary?: string
error?: string | null
toolCallCount?: number
tokenCount?: number
- /** Model id (for cache-aware pricing). */
model?: string | null
- /** Cache-aware token breakdown. When present we also store the breakdown +
- * effective cost; when absent, only the legacy fields are written (COALESCE
- * leaves the cost columns at their defaults). */
usage?: TokenUsage | null
-}): Promise<void> {
+}
+
+async function finishAgentRunRow(
+ args: FinishAgentRunArgs,
+ owner?: { agentId: string; companyId: string },
+ db: Queryable = pool,
+): Promise<boolean> {
const usage = args.usage ?? null
const cost = usage ? effectiveCostUsd(args.model, usage) : null
// Legacy token_count = input+output sum; keep it populated for back-compat.
const tokenCount = args.tokenCount ?? (usage
? usage.inputTokens + usage.cachedInputTokens + usage.cacheCreationTokens + usage.outputTokens
: 0)
- await pool.query(
+ const ownerPredicate = owner
+ ? `AND agent_id = $14
+ AND company_id = $15
+ AND EXISTS (
+ SELECT 1 FROM participants p
+ WHERE p.id = $14 AND p.company_id = $15
+ AND p.kind = 'agent' AND p.departed_at IS NULL
+ )`
+ : ''
+ const result = await db.query(
`UPDATE agent_runs
SET status = $2,
stage = $2,
@@ -137,7 +204,9 @@ export async function finishAgentRun(args: {
model = COALESCE($13, model),
updated_at = NOW(),
finished_at = NOW()
- WHERE id = $1`,
+ WHERE id = $1
+ ${ownerPredicate}
+ RETURNING id`,
[
args.runId,
args.status,
@@ -152,8 +221,23 @@ export async function finishAgentRun(args: {
cost?.usd ?? null,
cost ? cost.estimated : null,
args.model ?? null,
+ ...(owner ? [owner.agentId, owner.companyId] : []),
],
)
+ return result.rowCount === 1
+}
+
+export async function finishAgentRun(args: FinishAgentRunArgs): Promise<void> {
+ await finishAgentRunRow(args)
+}
+
+/** Finish a daemon run only when its persisted owner matches the current JWT. */
+export async function finishAgentRunForOwner(
+ args: FinishAgentRunArgs & { agentId: string; companyId: string },
+ db: Queryable = pool,
+): Promise<boolean> {
+ const { agentId, companyId, ...run } = args
+ return finishAgentRunRow(run, { agentId, companyId }, db)
}
/** Record one inbox-triage call (the small-brain gate) with its cache-aware cost.
@@ -205,6 +289,40 @@ export async function touchAgentRun(runId: string): Promise<void> {
)
}
+/** Ownership-aware daemon heartbeat. `owned` distinguishes an already-finished
+ * caller-owned run (valid no-op) from a missing or foreign run without leaking
+ * which of those two cases occurred. */
+export async function touchAgentRunForOwner(args: {
+ runId: string
+ agentId: string
+ companyId: string
+}, db: Queryable = pool): Promise<{ owned: boolean; touched: boolean }> {
+ const { rows } = await db.query<{ owned: boolean; touched: boolean }>(
+ `WITH owned_run AS MATERIALIZED (
+ SELECT ar.id, ar.status
+ FROM agent_runs ar
+ WHERE ar.id = $1
+ AND ar.agent_id = $2
+ AND ar.company_id = $3
+ AND EXISTS (
+ SELECT 1 FROM participants p
+ WHERE p.id = $2 AND p.company_id = $3
+ AND p.kind = 'agent' AND p.departed_at IS NULL
+ )
+ ), touched_run AS (
+ UPDATE agent_runs ar
+ SET updated_at = NOW()
+ FROM owned_run
+ WHERE ar.id = owned_run.id AND owned_run.status = 'running'
+ RETURNING ar.id
+ )
+ SELECT EXISTS (SELECT 1 FROM owned_run) AS owned,
+ EXISTS (SELECT 1 FROM touched_run) AS touched`,
+ [args.runId, args.agentId, args.companyId],
+ )
+ return rows[0] ?? { owned: false, touched: false }
+}
+
export async function markStaleAgentRuns(maxAgeMs: number = 10 * 60_000): Promise<Array<{ id: string; agent_id: string }>> {
const { rows } = await pool.query<{ id: string; agent_id: string }>(
`UPDATE agent_runs
diff --git a/server/src/agents/runtime/authorization.ts b/server/src/agents/runtime/authorization.ts
index ec2ec7b..c4be592 100644
--- a/server/src/agents/runtime/authorization.ts
+++ b/server/src/agents/runtime/authorization.ts
@@ -1,5 +1,5 @@
-import { pool } from '../../db/pool.js'
import type { PoolClient } from 'pg'
+import { pool } from '../../db/pool.js'
/**
* A signed runtime token captures the agent's tenant at mint time. Resolve the
@@ -21,6 +21,55 @@ export async function isRuntimeAgentAuthorized(
return rowCount === 1
}
+/** Hold the live runtime identity and every referenced run stable through an
+ * observability mutation. Participant reassignment/offboarding updates
+ * conflict with FOR SHARE; run GC and competing run mutations conflict with
+ * FOR UPDATE. Sorted run ids give concurrent batches one lock order. */
+export async function withRuntimeAgentRunAuthorization<T>(args: {
+ agentId: string
+ companyId: string
+ runIds: readonly string[]
+ task: (client: PoolClient) => Promise<T>
+}): Promise<{ authorized: boolean; result?: T }> {
+ const runIds = [...new Set(args.runIds)].sort()
+ const client = await pool.connect()
+ try {
+ await client.query('BEGIN')
+ const participant = await client.query(
+ `SELECT id FROM participants
+ WHERE id = $1 AND company_id = $2
+ AND kind = 'agent' AND departed_at IS NULL
+ FOR SHARE`,
+ [args.agentId, args.companyId],
+ )
+ if (!participant.rowCount) {
+ await client.query('ROLLBACK')
+ return { authorized: false }
+ }
+ if (runIds.length > 0) {
+ const runs = await client.query<{ id: string }>(
+ `SELECT id FROM agent_runs
+ WHERE id = ANY($1::text[])
+ AND agent_id = $2 AND company_id = $3
+ ORDER BY id FOR UPDATE`,
+ [runIds, args.agentId, args.companyId],
+ )
+ if (runs.rows.length !== runIds.length) {
+ await client.query('ROLLBACK')
+ return { authorized: false }
+ }
+ }
+ const result = await args.task(client)
+ await client.query('COMMIT')
+ return { authorized: true, result }
+ } catch (error) {
+ await client.query('ROLLBACK').catch(() => {})
+ throw error
+ } finally {
+ client.release()
+ }
+}
+
/** Hold the current agent and every requested conversation membership stable
* while an ephemeral Redis/pubsub side effect runs. Membership mutation uses
* the same participant -> conversation lock order, so a revoke is linearized
diff --git a/server/src/agents/runtime/server.ts b/server/src/agents/runtime/server.ts
index 615b1b6..7abea11 100644
--- a/server/src/agents/runtime/server.ts
+++ b/server/src/agents/runtime/server.ts
@@ -15,25 +15,33 @@
* `/api` because the cookie-auth middleware on /api would reject these
* (and we don't want pods sharing the human session cookie path).
*/
-import { Router, json, type Request, type Response, type NextFunction } from 'express'
+import { json, type NextFunction, type Request, type Response, Router } from 'express'
+import { publicBodyParserError } from '../../body-parser-errors.js'
+import { AGENDA_CLASSIFIER_ERROR, claimStallNudge, classifyAgendaActionable, gatherAgentAgenda, renderAgendaBrief } from '../agenda.js'
import { runCli } from '../cli.js'
import { buildTriageRequest, gatherClaimsByConvo } from '../inbox-triage.js'
+import {
+ createAgentRun,
+ finishAgentRunForOwner,
+ recordAgentEventForOwner,
+ recordTriage,
+ touchAgentRunForOwner,
+} from '../observability.js'
import { buildTeamRosterText, getPersona } from '../personas.js'
-import { gatherAgentAgenda, classifyAgendaActionable, renderAgendaBrief, claimStallNudge, AGENDA_CLASSIFIER_ERROR } from '../agenda.js'
import { consumeAgentTurnToken } from '../scheduler.js'
-import { touchAgentRun, recordTriage } from '../observability.js'
-import { normalizeByoaSource } from './byoa-source.js'
import {
isRuntimeAgentAuthorized,
+ withRuntimeAgentRunAuthorization,
withRuntimeConversationAuthorization,
withRuntimeMessageReadAuthorization,
} from './authorization.js'
+import { normalizeByoaSource } from './byoa-source.js'
import { buildRuntimeArgv } from './cli-argv.js'
+import type { RuntimeTokenUsage } from './client.js'
import { attachFsEndpoints } from './fs-endpoints.js'
import { inprocClient } from './inproc-client.js'
-import { verifyAgentToken, type AgentRuntimeClaims } from './jwt.js'
+import { type AgentRuntimeClaims, verifyAgentToken } from './jwt.js'
import { attachWakeStream, } from './wake-bus.js'
-import { publicBodyParserError } from '../../body-parser-errors.js'
export type { WakeEvent } from './wake-bus.js'
@@ -42,6 +50,26 @@ interface RuntimeRequest extends Request {
}
type AuthorizedAgentRuntimeClaims = AgentRuntimeClaims & { companyId: string }
+const MAX_LLM_HOPS_PER_BATCH = 100
+const MAX_PG_INTEGER = 2_147_483_647
+const RUN_STATUSES = new Set(['running', 'completed', 'failed', 'skipped'])
+const EVENT_LEVELS = new Set(['debug', 'info', 'warn', 'error'])
+const LLM_CALL_STATUSES = new Set(['ok', 'rate_limited', 'timeout', 'failed'])
+
+function isPlainRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+}
+
+function isNonNegativePgInteger(value: unknown): value is number {
+ return Number.isInteger(value) && (value as number) >= 0 && (value as number) <= MAX_PG_INTEGER
+}
+
+function isRuntimeTokenUsage(value: unknown): value is RuntimeTokenUsage {
+ if (!isPlainRecord(value)) return false
+ const counts = [value.inputTokens, value.cachedInputTokens, value.cacheCreationTokens, value.outputTokens]
+ return counts.every(isNonNegativePgInteger)
+ && (counts as number[]).reduce((sum, count) => sum + count, 0) <= MAX_PG_INTEGER
+}
async function authMiddleware(req: RuntimeRequest, res: Response, next: NextFunction): Promise<void> {
const header = req.headers['authorization']
@@ -94,7 +122,7 @@ function withAgent(
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
console.error(`[runtime] ${req.method} ${req.path} failed`, msg)
- res.status(500).json({ error: msg })
+ res.status(500).json({ error: 'runtime request failed' })
}
}
}
@@ -396,15 +424,31 @@ runtimeRouter.post('/runs', withAgent(async (c, req, res) => {
inboxCount?: number
fingerprint?: string
} | undefined
- const runId = await inprocClient.createRun({
+ if ((body !== undefined && !isPlainRecord(body))
+ || (body?.trigger !== undefined && !isPlainRecord(body.trigger))
+ || (body?.inputMessageIds !== undefined
+ && (!Array.isArray(body.inputMessageIds) || body.inputMessageIds.some((id) => typeof id !== 'string')))
+ || (body?.inboxCount !== undefined && !isNonNegativePgInteger(body.inboxCount))
+ || (body?.fingerprint !== undefined && typeof body.fingerprint !== 'string')) {
+ res.status(400).json({ error: 'invalid run payload' }); return
+ }
+ const gate = await withRuntimeAgentRunAuthorization({
agentId: c.sub,
companyId: c.companyId,
- trigger: body?.trigger,
- inputMessageIds: body?.inputMessageIds,
- inboxCount: body?.inboxCount,
- fingerprint: body?.fingerprint,
+ runIds: [],
+ task: (client) => createAgentRun({
+ agentId: c.sub,
+ companyId: c.companyId,
+ trigger: body?.trigger,
+ inputMessageIds: body?.inputMessageIds,
+ inboxCount: body?.inboxCount,
+ fingerprint: body?.fingerprint,
+ }, client),
})
- res.json({ runId })
+ if (!gate.authorized || !gate.result) {
+ res.status(403).json({ error: 'agent does not belong to token tenant' }); return
+ }
+ res.json({ runId: gate.result })
}))
runtimeRouter.post('/events', withAgent(async (c, req, res) => {
@@ -416,19 +460,32 @@ runtimeRouter.post('/events', withAgent(async (c, req, res) => {
data?: Record<string, unknown>
stage?: string
} | undefined
- if (!body?.runId || !body.kind || !body.title) {
+ if (typeof body?.runId !== 'string' || !body.runId
+ || typeof body.kind !== 'string' || !body.kind
+ || typeof body.title !== 'string' || !body.title) {
res.status(400).json({ error: 'runId, kind, title required' }); return
}
- await inprocClient.recordEvent({
- runId: body.runId,
+ if ((body.level !== undefined && !EVENT_LEVELS.has(body.level))
+ || (body.data !== undefined && !isPlainRecord(body.data))
+ || (body.stage !== undefined && typeof body.stage !== 'string')) {
+ res.status(400).json({ error: 'invalid event payload' }); return
+ }
+ const gate = await withRuntimeAgentRunAuthorization({
agentId: c.sub,
companyId: c.companyId,
- kind: body.kind,
- level: body.level,
- title: body.title,
- data: body.data,
- stage: body.stage,
+ runIds: [body.runId],
+ task: (client) => recordAgentEventForOwner({
+ runId: body.runId!,
+ agentId: c.sub,
+ companyId: c.companyId,
+ kind: body.kind!,
+ level: body.level,
+ title: body.title!,
+ data: body.data,
+ stage: body.stage,
+ }, client),
})
+ if (!gate.authorized || !gate.result) { res.status(404).json({ error: 'agent run not found' }); return }
res.json({ ok: true })
}))
@@ -445,6 +502,15 @@ runtimeRouter.post('/triage', withAgent(async (c, req, res) => {
usage?: import('./client.js').RuntimeTokenUsage | null
daemonVersion?: string
} | undefined
+ if ((body !== undefined && !isPlainRecord(body))
+ || (body?.source !== undefined && typeof body.source !== 'string')
+ || (body?.model !== undefined && body.model !== null && typeof body.model !== 'string')
+ || (body?.actionable !== undefined && typeof body.actionable !== 'boolean')
+ || (body?.reason !== undefined && body.reason !== null && typeof body.reason !== 'string')
+ || (body?.usage !== undefined && body.usage !== null && !isRuntimeTokenUsage(body.usage))
+ || (body?.daemonVersion !== undefined && typeof body.daemonVersion !== 'string')) {
+ res.status(400).json({ error: 'invalid triage payload' }); return
+ }
const daemonVersion = typeof body?.daemonVersion === 'string' && body.daemonVersion.trim() ? body.daemonVersion.trim().slice(0, 32) : null
const source = normalizeByoaSource(body?.source)
void recordTriage({
@@ -489,7 +555,8 @@ runtimeRouter.post('/triage', withAgent(async (c, req, res) => {
// every ~250ms (whichever first). This endpoint accepts a batch + inserts
// one llm_calls row per hop with the appropriate source ('byoa-claude' |
// 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode' | 'byoa-pi').
-// Fire-and-forget; a DB hiccup must never break the wake.
+// The server commits the bounded batch atomically; the daemon still treats an
+// HTTP/DB failure as best-effort so observability can never break the wake.
runtimeRouter.post('/llm-calls', withAgent(async (c, req, res) => {
const body = req.body as {
source?: string
@@ -509,11 +576,41 @@ runtimeRouter.post('/llm-calls', withAgent(async (c, req, res) => {
extras?: Record<string, unknown>
}>
} | undefined
+ if ((body !== undefined && !isPlainRecord(body))
+ || (body?.source !== undefined && typeof body.source !== 'string')
+ || (body?.daemonVersion !== undefined && typeof body.daemonVersion !== 'string')
+ || (body?.hops !== undefined && !Array.isArray(body.hops))) {
+ res.status(400).json({ error: 'invalid LLM batch payload' }); return
+ }
const source = normalizeByoaSource(body?.source)
const daemonVersion = typeof body?.daemonVersion === 'string' && body.daemonVersion.trim() ? body.daemonVersion.trim().slice(0, 32) : null
const hops = Array.isArray(body?.hops) ? body!.hops : []
if (hops.length === 0) { res.json({ ok: true, inserted: 0 }); return }
- const { recordLlmCall } = await import('../llm-ledger.js')
+ if (hops.length > MAX_LLM_HOPS_PER_BATCH) {
+ res.status(413).json({ error: `too many hops (max ${MAX_LLM_HOPS_PER_BATCH})` }); return
+ }
+ const runIds: string[] = []
+ for (const hop of hops) {
+ if (!isPlainRecord(hop)) {
+ res.status(400).json({ error: 'each hop must be an object' }); return
+ }
+ if (hop.runId !== undefined && hop.runId !== null) {
+ if (typeof hop.runId !== 'string' || !hop.runId) {
+ res.status(400).json({ error: 'runId must be a non-empty string or null' }); return
+ }
+ runIds.push(hop.runId)
+ }
+ if ((hop.purpose !== undefined && typeof hop.purpose !== 'string')
+ || (hop.conversationId !== undefined && hop.conversationId !== null && typeof hop.conversationId !== 'string')
+ || (hop.model !== undefined && typeof hop.model !== 'string')
+ || (hop.usage !== undefined && hop.usage !== null && !isRuntimeTokenUsage(hop.usage))
+ || (hop.latencyMs !== undefined && !isNonNegativePgInteger(hop.latencyMs))
+ || (hop.status !== undefined && (typeof hop.status !== 'string' || !LLM_CALL_STATUSES.has(hop.status)))
+ || (hop.error !== undefined && hop.error !== null && typeof hop.error !== 'string')
+ || (hop.extras !== undefined && !isPlainRecord(hop.extras))) {
+ res.status(400).json({ error: 'invalid hop payload' }); return
+ }
+ }
// Whitelist purposes the daemon may declare — anything else gets coerced
// to 'agent-turn' so a future daemon version naming an unknown purpose
// doesn't smuggle a free-form string into the rollup.
@@ -521,10 +618,10 @@ runtimeRouter.post('/llm-calls', withAgent(async (c, req, res) => {
'agent-turn', 'inbox-triage', 'synthetic-wake-gate', 'agenda',
'compaction', 'completion-verify', 'steer-summary',
])
- for (const h of hops) {
+ const records = hops.map((h) => {
const purpose = (typeof h.purpose === 'string' && KNOWN_PURPOSES.has(h.purpose) ? h.purpose : 'agent-turn') as 'agent-turn'
const model = typeof h.model === 'string' && h.model ? h.model : '<unknown>'
- void recordLlmCall({
+ return {
purpose,
companyId: c.companyId,
agentId: c.sub,
@@ -543,20 +640,39 @@ runtimeRouter.post('/llm-calls', withAgent(async (c, req, res) => {
error: h.error ?? null,
extras: h.extras,
daemonVersion,
- })
- }
+ }
+ })
+ const { recordLlmCallsBatch } = await import('../llm-ledger.js')
+ const gate = await withRuntimeAgentRunAuthorization({
+ agentId: c.sub,
+ companyId: c.companyId,
+ runIds,
+ task: (client) => recordLlmCallsBatch(records, client),
+ })
+ if (!gate.authorized) { res.status(404).json({ error: 'agent run not found' }); return }
res.json({ ok: true, inserted: hops.length })
}))
// Heartbeat a long engine turn so the 10-min stale-run sweeper doesn't reap it.
// BYOA emits no mid-run events (cloud does), so its daemon pings this while the
// engine turn is in flight. Best-effort: a DB hiccup must not break the turn.
-runtimeRouter.post('/runs/:runId/heartbeat', withAgent(async (_c, req, res) => {
- try { await touchAgentRun(String(req.params.runId)) } catch { /* swept-or-gone is fine */ }
- res.json({ ok: true })
+runtimeRouter.post('/runs/:runId/heartbeat', withAgent(async (c, req, res) => {
+ const runId = String(req.params.runId)
+ const gate = await withRuntimeAgentRunAuthorization({
+ agentId: c.sub,
+ companyId: c.companyId,
+ runIds: [runId],
+ task: (client) => touchAgentRunForOwner({
+ runId,
+ agentId: c.sub,
+ companyId: c.companyId,
+ }, client),
+ })
+ if (!gate.authorized || !gate.result?.owned) { res.status(404).json({ error: 'agent run not found' }); return }
+ res.json({ ok: true, touched: gate.result.touched })
}))
-runtimeRouter.post('/runs/:runId/finish', withAgent(async (_c, req, res) => {
+runtimeRouter.post('/runs/:runId/finish', withAgent(async (c, req, res) => {
const runId = String(req.params.runId)
const body = req.body as {
status?: 'running' | 'completed' | 'failed' | 'skipped'
@@ -568,16 +684,33 @@ runtimeRouter.post('/runs/:runId/finish', withAgent(async (_c, req, res) => {
usage?: import('./client.js').RuntimeTokenUsage | null
} | undefined
if (!body?.status) { res.status(400).json({ error: 'status required' }); return }
- await inprocClient.finishRun({
- runId,
- status: body.status,
- summary: body.summary,
- error: body.error,
- toolCallCount: body.toolCallCount,
- tokenCount: body.tokenCount,
- model: body.model,
- usage: body.usage,
+ if (typeof body.status !== 'string' || !RUN_STATUSES.has(body.status)
+ || (body.summary !== undefined && typeof body.summary !== 'string')
+ || (body.error !== undefined && body.error !== null && typeof body.error !== 'string')
+ || (body.toolCallCount !== undefined && !isNonNegativePgInteger(body.toolCallCount))
+ || (body.tokenCount !== undefined && !isNonNegativePgInteger(body.tokenCount))
+ || (body.model !== undefined && body.model !== null && typeof body.model !== 'string')
+ || (body.usage !== undefined && body.usage !== null && !isRuntimeTokenUsage(body.usage))) {
+ res.status(400).json({ error: 'invalid finish payload' }); return
+ }
+ const gate = await withRuntimeAgentRunAuthorization({
+ agentId: c.sub,
+ companyId: c.companyId,
+ runIds: [runId],
+ task: (client) => finishAgentRunForOwner({
+ runId,
+ agentId: c.sub,
+ companyId: c.companyId,
+ status: body.status!,
+ summary: body.summary,
+ error: body.error,
+ toolCallCount: body.toolCallCount,
+ tokenCount: body.tokenCount,
+ model: body.model,
+ usage: body.usage,
+ }, client),
})
+ if (!gate.authorized || !gate.result) { res.status(404).json({ error: 'agent run not found' }); return }
res.json({ ok: true })
}))