Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(ops): agent-contract fixes for jobs ops (B1/B2/B6/B7)
garrytan1207a1c62ef5
diff --git a/src/core/ops/jobs.ts b/src/core/ops/jobs.tsindex 24a817dbb8..7eb7b3e435 100644--- a/src/core/ops/jobs.ts+++ b/src/core/ops/jobs.ts@@ -16,11 +16,13 @@ function publicJob(job: MinionJob) {*/import type { Operation, OperationContext } from './contract.ts';-import { OperationError } from './contract.ts';+import { opError, type OperationError } from './contract.ts';+import type { Action } from '../agent-output.ts';+import { hostFix, invalidParam, readFix, scopeDeniedError } from './op-fix.ts';import { hasScope } from '../scope.ts';+import { SOURCE_ID_RE } from '../source-id.ts';import {assertEmbedBackfillQueueAdmission,- embedBackfillManualDrainCommand,InvalidEmbedBackfillSourceIdError,NoEmbedBackfillWorkerSurfaceError,} from '../minions/embed-backfill-admission.ts';@@ -52,15 +54,37 @@ function agentOwnerFence(ctx: OperationContext, opName: string): string | null {if (!ctx.auth && ctx.transport === 'stdio') return null;const clientId = ctx.auth?.clientId;if (!clientId || typeof clientId !== 'string') {- throw new OperationError(- 'permission_denied',- `${opName} without admin scope requires an authenticated OAuth client identity.`,- 'Call over HTTP MCP with an `agent`-scoped token, or use an admin-scope token for unfenced access.',- );+ throw scopeDeniedError({+ op: opName, required: ['admin'], auth: ctx.auth, transport: ctx.transport === 'http' ? 'http' : 'stdio',+ message: `${opName} without admin scope requires an authenticated OAuth client identity.`,+ legacy_error: 'permission_denied',+ });}return clientId;}+function listJobsFix(why: string): Action {+ return readFix(why, { argv: ['gbrain', 'jobs', 'list', '--json'], mcp: { tool: 'list_jobs', arguments: {} } });+}++function getJobFix(id: unknown, why: string): Action {+ if (typeof id !== 'number' || !Number.isSafeInteger(id)) return listJobsFix('Lists jobs with their ids and current status.');+ return readFix(why, { argv: ['gbrain', 'jobs', 'get', String(id), '--json'], mcp: { tool: 'get_job', arguments: { id } } });+}++/** A1 frozen pair: a missing job keeps `error: invalid_params` and reports `code: not_found`. */+function jobNotFound(message: string): OperationError {+ return opError('not_found', message,+ 'No job with that id is visible to this caller (jobs owned by another client read as missing). List jobs to find the right id.',+ { legacy_error: 'invalid_params', fix: listJobsFix('Lists the jobs this caller can see, with their ids and status.') });+}++/** The job exists but is in the wrong state for this transition; nothing changed. */+function jobStateError(id: unknown, message: string, need: string): OperationError {+ return opError('invalid_params', message, `Nothing changed. ${need} Check the job's current status first.`,+ { fix: getJobFix(id, 'Shows the job\'s current status, so you can pick the transition it allows.') });+}+/*** #4098 — SQL-side ownership check (the get_agent_job predicate, uniform* not-found). Foreign-owned and nonexistent ids are indistinguishable by@@ -73,10 +97,19 @@ async function assertJobOwned(ctx: OperationContext, id: number, owner: string):[id, owner],);if (rows.length === 0) {- throw new OperationError('invalid_params', `Job not found: ${id}`);+ throw jobNotFound(`Job not found: ${id}`);}}+function noWorkerSurface(ctx: OperationContext, e: NoEmbedBackfillWorkerSurfaceError): OperationError {+ const known = SOURCE_ID_RE.test(e.sourceId);+ const fix = hostFix(ctx, ['gbrain', 'embed', '--stale', '--source', known ? e.sourceId : '<source-id>'],+ 'Embeds the stale chunks inline in the CLI process; this engine has no worker to drain a queued backfill.', { consent: ['paid'] });+ return opError('no_worker_surface', e.message,+ 'Nothing was queued. Drain the embeddings inline with the command in fix instead of submitting a job.',+ { fix: known ? fix : { ...fix, inputs: [{ name: 'source-id', how: 'The source to embed (`gbrain sources list` shows them).' }] } });+}+const submit_job: Operation = {name: 'submit_job',idempotent: false,@@ -101,15 +134,9 @@ const submit_job: Operation = {if (remoteSubmission) jobData = remoteSubmission.data;const translateAdmissionError = (e: unknown): never => {if (e instanceof InvalidEmbedBackfillSourceIdError) {- throw new OperationError('invalid_params', e.message);- }- if (e instanceof NoEmbedBackfillWorkerSurfaceError) {- throw new OperationError(- 'no_worker_surface',- e.message,- `Run \`${embedBackfillManualDrainCommand(e.sourceId)}\` to drain embeddings inline.`,- );+ throw invalidParam(ctx, 'submit_job', 'data', e.message, { def: submit_job.params.data, example: { sourceId: ctx.sourceId ?? 'default' } });}+ if (e instanceof NoEmbedBackfillWorkerSurfaceError) throw noWorkerSurface(ctx, e);throw e;};@@ -133,7 +160,10 @@ const submit_job: Operation = {// protected job submissions. Closes the HTTP MCP shell-job RCE that surfaced// when the HTTP transport's OperationContext literal forgot to set remote.if (ctx.remote !== false && isProtectedJobName(name)) {- throw new OperationError('permission_denied', `'${name}' jobs cannot be submitted over MCP (CLI-only for security)`);+ throw opError('permission_denied', `'${name}' jobs cannot be submitted over MCP (CLI-only for security)`,+ 'Protected job types run only from the trusted local CLI on the brain host; the user or host operator submits it there (command in fix).',+ { fix: { ...hostFix(ctx, ['gbrain', 'jobs', 'submit', name, '--params', '<params>'], `'${name}' jobs can execute host commands, so only the brain host's own CLI may queue them.`),+ inputs: [{ name: 'params', how: 'The job data as one JSON object (what you passed as data).' }] } });}const { MinionQueue } = await import('../minions/queue.ts');@@ -227,6 +257,28 @@ async function probeQueueStateSafe(}}+function agentRunFix(ctx: OperationContext): Action {+ return {+ ...hostFix(ctx, ['gbrain', 'agent', 'run', '--', '<prompt>'],+ 'Runs the agent loop in a local gbrain process; submit_agent is the entry point for OAuth clients over HTTP MCP.', { consent: ['paid'] }),+ inputs: [{ name: 'prompt', how: 'The prompt you meant to submit.' }],+ };+}++const CALLER_FIXABLE_DELEGATION = ['delegated_tools_invalid', 'delegated_prefixes_invalid', 'job_namespace_cannot_be_overridden'];++function delegationDenied(ctx: OperationContext, error: Error & { reasons: string[] }): OperationError {+ const reason = error.reasons[0];+ if (error.reasons.every(r => CALLER_FIXABLE_DELEGATION.includes(r))) {+ return opError('permission_denied', error.message,+ 'Nothing was queued. Request only tools and slug prefixes inside this client\'s delegation grant, or omit allowed_tools and allowed_slug_prefixes to use the whole grant.',+ { reason });+ }+ return opError('permission_denied', error.message,+ 'Nothing was queued. This client\'s delegation grant no longer authorizes the job; the brain host operator reviews the client registration (command in fix).',+ { reason, fix: hostFix(ctx, ['gbrain', 'auth', 'clients', '--json'], 'Lists OAuth clients with their delegation bindings, so the operator can repair this one.') });+}+// v0.38 Slice 3 — D13 — remote-callable submit_agent with registration-time// binding enforcement. Distinct from `submit_job` because:// 1. It's the FIRST op that lets remote MCP callers spawn paid LLM work@@ -256,47 +308,60 @@ const submit_agent: Operation = {// binding check — `gbrain agent run` already runs through subagent.ts// directly without going through this op.if (ctx.remote === false) {- throw new OperationError('invalid_request', 'submit_agent over the local CLI: use `gbrain agent run` instead.');+ throw opError('invalid_request', 'submit_agent over the local CLI: use `gbrain agent run` instead.',+ 'On the local CLI, run the agent directly with the command in fix.', { fix: agentRunFix(ctx) });}const clientId = (ctx as { auth?: { clientId?: string } }).auth?.clientId;if (!clientId || typeof clientId !== 'string') {- throw new OperationError('permission_denied', 'submit_agent requires an OAuth client with the `agent` scope.');+ const message = 'submit_agent requires an OAuth client with the `agent` scope.';+ if (ctx.transport === 'http') throw scopeDeniedError({ op: 'submit_agent', required: ['agent'], auth: ctx.auth, transport: 'http', message, legacy_error: 'permission_denied' });+ throw opError('permission_denied', message,+ 'submit_agent needs an HTTP MCP connection authenticated as an OAuth client with the agent scope. On this machine, the user runs the agent with the command in fix.',+ { fix: agentRunFix(ctx) });}const { currentDelegationGrant, submissionSnapshot, DelegationDeniedError } = await import('../minions/delegated-policy.ts');const { hasScope } = await import('../scope.ts');if (!hasScope(ctx.auth?.scopes ?? [], 'agent')) {- throw new OperationError('permission_denied', 'submit_agent requires the agent scope.');+ throw scopeDeniedError({+ op: 'submit_agent', required: ['agent'], auth: ctx.auth, transport: ctx.transport === 'http' ? 'http' : 'stdio',+ message: 'submit_agent requires the agent scope.', legacy_error: 'permission_denied',+ });}- if (typeof p.prompt !== 'string' || p.prompt.trim() === '') throw new OperationError('invalid_params', 'prompt must be nonempty');+ const { TIER_DEFAULTS } = await import('../model-config.ts');+ const bad = (param: string, message: string, example: unknown) =>+ invalidParam(ctx, 'submit_agent', param, message, { def: submit_agent.params[param], example });+ if (typeof p.prompt !== 'string' || p.prompt.trim() === '') throw bad('prompt', 'prompt must be nonempty', "Summarize this week's new pages.");const maxTurns = p.max_turns ?? 20;if (!Number.isSafeInteger(maxTurns) || Number(maxTurns) < 1 || Number(maxTurns) > 100) {- throw new OperationError('invalid_params', 'max_turns must be an integer from 1 to 100');+ throw bad('max_turns', 'max_turns must be an integer from 1 to 100', 20);}if (p.model !== undefined && (typeof p.model !== 'string' || p.model.trim() === '')) {- throw new OperationError('invalid_params', 'model must name a supported agent tool-loop model');+ throw bad('model', 'model must name a supported agent tool-loop model', TIER_DEFAULTS.subagent);}- if (p.queue !== undefined && (typeof p.queue !== 'string' || !p.queue.trim())) throw new OperationError('invalid_params', 'queue must be nonempty');+ if (p.queue !== undefined && (typeof p.queue !== 'string' || !p.queue.trim())) throw bad('queue', 'queue must be nonempty', 'default');const { classifyCapabilities } = await import('../ai/capabilities.ts');const { normalizeModelId, splitProviderModelId } = await import('../model-id.ts');- const { resolveModel, TIER_DEFAULTS, isAnthropicProvider, isOpenRouterSubagentFamily } = await import('../model-config.ts');+ const { resolveModel, isAnthropicProvider, isOpenRouterSubagentFamily } = await import('../model-config.ts');const { isConfigTruthy } = await import('../config.ts');const resolvedModel = typeof p.model === 'string' ? p.model : await resolveModel(ctx.engine, { tier: 'subagent', configKey: 'models.subagent', fallback: TIER_DEFAULTS.subagent });const modelForVerdict = splitProviderModelId(resolvedModel).provider === null && isAnthropicProvider(resolvedModel) ? normalizeModelId(resolvedModel) : resolvedModel;if (['unknown', 'unusable:no_tools', 'unusable:no_subagent_loop'].includes(classifyCapabilities(modelForVerdict))) {- throw new OperationError('invalid_params', 'model must name a supported agent tool-loop model');+ throw bad('model', 'model must name a supported agent tool-loop model', TIER_DEFAULTS.subagent);}if (!isAnthropicProvider(resolvedModel) && !isOpenRouterSubagentFamily(resolvedModel)&& !isConfigTruthy(await ctx.engine.getConfig('agent.use_gateway_loop'))) {- throw new OperationError('invalid_params', 'This provider requires agent.use_gateway_loop=true before submitting an agent job.');+ throw opError('invalid_params', 'This provider requires agent.use_gateway_loop=true before submitting an agent job.',+ `Nothing was queued. Pass a model from an Anthropic or OpenRouter family (for example ${TIER_DEFAULTS.subagent}), or ask the brain host operator to enable agent.use_gateway_loop (command in fix).`,+ { fix: hostFix(ctx, ['gbrain', 'config', 'set', 'agent.use_gateway_loop', 'true'], 'Lets the worker run non-Anthropic providers through the gateway-native tool loop.') });}let snapshot;try {const grant = await currentDelegationGrant(ctx.engine, clientId, ctx.brainId);snapshot = submissionSnapshot(grant, p, ctx.auth?.sourceId);} catch (error) {- if (error instanceof DelegationDeniedError) throw new OperationError('permission_denied', error.message);+ if (error instanceof DelegationDeniedError) throw delegationDenied(ctx, error);throw error;}const boundSource = snapshot.sourceId;@@ -330,8 +395,12 @@ const submit_agent: Operation = {{ allowProtectedSubmit: true, delegatedClientId: clientId, submissionAuthority: authority });} catch (error) {const { isQueueQuotaExceededError } = await import('../minions/admission.ts');- if (isQueueQuotaExceededError(error)) throw new OperationError('rate_limited', error.message, 'Retry after existing work completes.');- if (error instanceof DelegationDeniedError) throw new OperationError('permission_denied', error.message);+ if (isQueueQuotaExceededError(error)) {+ throw opError('rate_limited', error.message,+ 'Nothing was queued: this client is at its concurrent agent-job limit. Check its jobs, and submit again once one finishes.',+ { fix: listJobsFix('Shows this client\'s jobs and their status, including the ones holding its concurrency slots.') });+ }+ if (error instanceof DelegationDeniedError) throw delegationDenied(ctx, error);throw error;}@@ -405,15 +474,16 @@ const get_agent_job: Operation = {handler: async (ctx, p) => {const clientId = ctx.auth?.clientId;if (!clientId || typeof clientId !== 'string') {- throw new OperationError(+ throw opError('permission_denied','get_agent_job requires an authenticated OAuth client identity.',- 'Call over HTTP MCP with an `agent`-scoped token. Transports without a per-client identity (stdio, legacy bearer) cannot read agent jobs; use admin-scope get_job from a trusted context instead.',+ 'Call over HTTP MCP with an `agent`-scoped token. Transports without a per-client identity (stdio, legacy bearer) cannot read agent jobs; read the job with admin-scope get_job instead (fix).',+ { fix: getJobFix(p.id, 'get_job reads any job for an admin-scope or trusted local caller.') },);}const id = p.id;if (typeof id !== 'number' || !Number.isInteger(id)) {- throw new OperationError('invalid_params', 'id must be an integer job id');+ throw invalidParam(ctx, 'get_agent_job', 'id', 'id must be an integer job id', { def: get_agent_job.params.id, example: 42 });}// One round-trip: the ownership fence rides the WHERE, and the@@ -450,7 +520,9 @@ const get_agent_job: Operation = {if (rows.length === 0) {// Uniform envelope: foreign-owned and nonexistent ids are// indistinguishable by design (anti-enumeration).- throw new OperationError('not_found', `Job not found: ${id}`);+ throw opError('not_found', `Job not found: ${id}`,+ 'No agent job with that id belongs to this client. List your jobs to find the right id.',+ { fix: listJobsFix('Lists the jobs this client owns, with their ids and status.') });}const row = rows[0];const iso = (v: string | Date | null): string | null =>@@ -494,7 +566,7 @@ const get_job: Operation = {const { MinionQueue } = await import('../minions/queue.ts');const queue = new MinionQueue(ctx.engine);const job = await queue.getJob(p.id as number);- if (!job) throw new OperationError('invalid_params', `Job not found: ${p.id}`);+ if (!job) throw jobNotFound(`Job not found: ${p.id}`);// private_queue_owner_token is a capability credential (lease renewal /// attach), not job data — never expose it over MCP envelopes.return publicJob(job);@@ -553,7 +625,7 @@ const cancel_job: Operation = {// fenced caller can cancel only roots it owns (descendants of an owned// root cascade as usual). Foreign and missing ids share one envelope.const cancelled = await queue.cancelJob(p.id as number, owner !== null ? { ownerClientId: owner } : undefined);- if (!cancelled) throw new OperationError('invalid_params', `Cannot cancel job ${p.id} (may already be in terminal status)`);+ if (!cancelled) throw jobStateError(p.id, `Cannot cancel job ${p.id} (may already be in terminal status)`, 'Only waiting, active, delayed or paused jobs can be cancelled.');// private_queue_owner_token is a capability credential (lease renewal /// attach), not job data — never expose it over MCP envelopes.return publicJob(cancelled);@@ -575,10 +647,10 @@ const retry_job: Operation = {const { MinionQueue } = await import('../minions/queue.ts');const queue = new MinionQueue(ctx.engine);const prior = await queue.getJob(p.id as number);- if (!prior) throw new OperationError('invalid_params', 'Job not found');+ if (!prior) throw jobNotFound('Job not found');await assertRemoteJobControl(ctx, prior);const retried = await queue.retryJob(p.id as number);- if (!retried) throw new OperationError('invalid_params', `Cannot retry job ${p.id} (must be failed or dead)`);+ if (!retried) throw jobStateError(p.id, `Cannot retry job ${p.id} (must be failed or dead)`, 'Only failed or dead jobs can be re-queued.');// private_queue_owner_token is a capability credential (lease renewal /// attach), not job data — never expose it over MCP envelopes.return publicJob(retried);@@ -602,7 +674,7 @@ const get_job_progress: Operation = {const { MinionQueue } = await import('../minions/queue.ts');const queue = new MinionQueue(ctx.engine);const job = await queue.getJob(p.id as number);- if (!job) throw new OperationError('invalid_params', `Job not found: ${p.id}`);+ if (!job) throw jobNotFound(`Job not found: ${p.id}`);return { id: job.id, name: job.name, status: job.status, progress: job.progress };},};@@ -622,7 +694,7 @@ const pause_job: Operation = {const { MinionQueue } = await import('../minions/queue.ts');const queue = new MinionQueue(ctx.engine);const job = await queue.pauseJob(p.id as number);- if (!job) throw new OperationError('invalid_params', `Job not found or not pausable: ${p.id}`);+ if (!job) throw jobStateError(p.id, `Job not found or not pausable: ${p.id}`, 'Only waiting, active or delayed jobs can be paused.');return { id: job.id, status: job.status };},};@@ -642,10 +714,10 @@ const resume_job: Operation = {const { MinionQueue } = await import('../minions/queue.ts');const queue = new MinionQueue(ctx.engine);const prior = await queue.getJob(p.id as number);- if (!prior) throw new OperationError('invalid_params', 'Job not found');+ if (!prior) throw jobNotFound('Job not found');await assertRemoteJobControl(ctx, prior);const job = await queue.resumeJob(p.id as number);- if (!job) throw new OperationError('invalid_params', `Job not found or not paused: ${p.id}`);+ if (!job) throw jobStateError(p.id, `Job not found or not paused: ${p.id}`, 'Only paused jobs can be resumed.');return { id: job.id, status: job.status };},};@@ -666,10 +738,10 @@ const replay_job: Operation = {const { MinionQueue } = await import('../minions/queue.ts');const queue = new MinionQueue(ctx.engine);const prior = await queue.getJob(p.id as number);- if (!prior) throw new OperationError('invalid_params', 'Job not found');+ if (!prior) throw jobNotFound('Job not found');await assertRemoteJobControl(ctx, prior, p.data_overrides);const job = await queue.replayJob(p.id as number, p.data_overrides as Record<string, unknown> | undefined);- if (!job) throw new OperationError('invalid_params', `Job not found or not in terminal state: ${p.id}`);+ if (!job) throw jobStateError(p.id, `Job not found or not in terminal state: ${p.id}`, 'Only completed, failed or dead jobs can be replayed.');return { id: job.id, name: job.name, status: job.status, source_id: p.id };},};@@ -699,9 +771,12 @@ const send_job_message: Operation = {if (ctx.remote !== false) {const clientId = ctx.auth?.clientId;if (!clientId) {- throw new OperationError(+ throw opError('permission_denied','send_job_message requires an authenticated client identity when called remotely',+ 'Nothing was sent. Connect over HTTP MCP as an OAuth client, or have the user send it from the trusted local CLI (command in fix).',+ { fix: { ...hostFix(ctx, ['gbrain', 'call', 'send_job_message', '<arguments>'], 'The trusted local CLI sends as admin; a remote caller needs its own authenticated identity.'),+ inputs: [{ name: 'arguments', how: 'The JSON arguments you passed: the job id and the payload to send.' }] } },);}const sender = `mcp:${clientId.slice(0, 8)}`;@@ -712,7 +787,7 @@ const send_job_message: Operation = {// raw payload object — never JSON.stringify into jsonb).const job = await queue.getJob(p.id as number);if (!job || ['completed', 'dead', 'cancelled', 'failed'].includes(job.status)) {- throw new OperationError('invalid_params', `Job not found or not messageable: ${p.id}`);+ throw jobStateError(p.id, `Job not found or not messageable: ${p.id}`, 'Only jobs that have not finished accept messages.');}const rows = await ctx.engine.executeRaw<{ id: number }>(`INSERT INTO minion_inbox (job_id, sender, payload)@@ -724,7 +799,7 @@ const send_job_message: Operation = {}const msg = await queue.sendMessage(p.id as number, p.payload, (p.sender as string) ?? 'admin');- if (!msg) throw new OperationError('invalid_params', `Job not found, not messageable, or sender unauthorized: ${p.id}`);+ if (!msg) throw jobStateError(p.id, `Job not found, not messageable, or sender unauthorized: ${p.id}`, 'Only unfinished jobs accept messages, from admin or the job\'s parent.');return { sent: true, message_id: msg.id, job_id: p.id };},};