import { reportHandledError } from '#worker/outbound/typed-failure.ts' import { defaultExecutorTimeoutMs } from '#mcp/executor-budgets.ts' import { contextRunCancelledSummary } from '#mcp/execution-timeout-next-step.ts' import { type EcpCancelReason, type EcpCapabilities, type EcpGrant, type EcpPublishBuildSource, type EcpRunRequestBody, sha256Base64Url, ecpDefaultGrant, ecpHostOperatorOnlyFeature, ecpLostAfterDeadlineMs, ecpTypeScriptSourceFeature, ecpPublishBuildFeature, ecpPackageRuntimeStoreFeature, } from '@kody-internal/shared/execution-context-protocol/index.ts' import { credentialCallMapToJson, type CredentialCallMap, } from '#worker/credentials/credential-call-map.ts' import type { RunRecordHandle } from '#worker/run-records/types.ts' import { checkPermission, computeEffectivePermissions, type EffectivePermissions, } from '#worker/authorization/authorize.ts' import { loadOrgBindingForOrg } from '#worker/orgs/repo.ts' import { loadJavaScriptParser } from '#worker/codemode-normalize-load.ts' import { deriveRequestContext } from '#worker/request-context/request-context.ts' import type { OwnerId, PersonId, } from '@kody-internal/shared/owner-person-ids.ts' import { refreshContextNotices } from './box-notices.ts' import { ExecutionContextError } from './errors.ts' import type { ExecutionContextLease, ExecutionContextRunResult, } from './session-do.ts' import type { AutomationInternalHandler } from './automation-settings.ts' import type { ExecutionContextRunTiming } from './run-timing.ts' import { runChainShapeError, type ExecuteRequirement } from './chain-rules.ts' import { type ChainEntry, type ExecutionContextRow, type UnusableReason, getChain, loadChainContexts, parseCapabilities, parseGrant, resolveExecutionContextRef, sessionStub, } from './store.ts' import { outboundTimeoutMs, withDeadline, } from '@kody-internal/shared/with-deadline.ts' export { executeRequirements, type ExecuteRequirement } from './chain-rules.ts' export type ExecuteRoutingArgs = { /** A context id or name, or `cloud`. */ context?: string /** `chain` lets a named context fall back to the caller's chain. */ fallback?: 'chain' requires?: Array /** * This run's own ordered chain: context ids or names, with `cloud` only * ever last. Replaces the caller's default chain for this run. */ chain?: Array } export type RoutingAttempt = { target: string name?: string outcome: | 'ran' | 'offline' | 'busy' | 'rejected' | 'aborted' | 'timeout' | 'skipped' | 'queued' | 'expired' | 'paused' /** Committed, then the context dropped before it started the run. */ | 'lost' reason?: string } export type ExecutionContextRunMetadata = { id: string | null name: string | null attempts: Array fellBackToCloud: boolean /** The requester runs this context's daemon (their own machine). */ yours?: boolean /** Where the run's time went, when the context reported it. */ timing?: ExecutionContextRunTiming timingMissing?: 'daemon_lost' } /** Where a run happened: Kody cloud or one execution context. */ export type RanOnTarget = | { kind: 'cloud'; id: 'cloud'; name: 'Kody cloud' } | { kind: 'context' id: string name: string yours?: boolean /** Where the run's time went, when the context reported it. */ timing?: ExecutionContextRunTiming } /** `ranOn` on every execute response: the target plus how it got there. */ export type ExecuteRanOn = RanOnTarget & { attempts: Array fellBackToCloud: boolean } export const kodyCloudTarget = { kind: 'cloud', id: 'cloud', name: 'Kody cloud', } as const satisfies RanOnTarget /** Run-history `ranOn`: null when a queued run expired before anything ran it. */ export function historyRanOn(value: unknown): ExecuteRanOn | null { const attempts = isRecord(value) && Array.isArray(value.attempts) ? (value.attempts as Array) : [] return attempts.at(-1)?.outcome === 'expired' ? null : ranOnFromMetadata(value) } /** Reads run metadata (`executionContext`) as `ranOn`; anything else is cloud. */ export function ranOnFromMetadata(value: unknown): ExecuteRanOn { const metadata = isRecord(value) ? value : null const attempts = Array.isArray(metadata?.attempts) ? (metadata.attempts as Array) : [] const fellBackToCloud = metadata?.fellBackToCloud === true if ( !fellBackToCloud && typeof metadata?.id === 'string' && metadata.id !== 'cloud' ) { return { kind: 'context', id: metadata.id, name: typeof metadata.name === 'string' ? metadata.name : metadata.id, ...(typeof metadata.yours === 'boolean' ? { yours: metadata.yours } : {}), ...(isRecord(metadata.timing) ? { timing: metadata.timing as ExecutionContextRunTiming } : {}), attempts, fellBackToCloud: false, } } return { ...kodyCloudTarget, attempts: attempts.filter((attempt) => attempt.outcome !== 'ran'), fellBackToCloud, } } /** * One line saying where a run happened, with friendly names only, e.g. * "Ran on Kody cloud after build-box was offline." */ export function describeRanOn( ranOn: ExecuteRanOn, options: { running?: boolean } = {}, ) { const passed = ranOn.attempts.filter( (attempt) => attempt.outcome !== 'ran' && !(ranOn.kind === 'context' && attempt.target === ranOn.id), ) const after = passed.length > 0 ? ` after ${joinList(passed.map(describePass))}` : '' const where = ranOn.kind === 'cloud' ? ranOn.name : `${ranOn.name} (${ranOn.yours ? 'your machine' : 'an execution context'})` const last = ranOn.attempts.at(-1) if (ranOn.kind === 'context' && last?.outcome === 'queued') { return `Waiting for ${where} to take this run${after}.` } return `${options.running ? 'Running' : 'Ran'} on ${where}${after}.` } /** * The ran-on line with the worker units this call charged, e.g. * "Ran on nautilus (your machine), 0 worker units." */ export function describeRanOnWithWorkerUnits( line: string, workerUnits: number, ) { const units = `${workerUnits} worker unit${workerUnits === 1 ? '' : 's'}` return `${line.replace(/\.$/, '')}, ${units}.` } /** The cloud-fallback line (kept for callers that only have metadata). */ export function describeCloudFallback(metadata: ExecutionContextRunMetadata) { return describeRanOn(ranOnFromMetadata(metadata)) } const passPhrases: Record = { ran: 'ran it', offline: 'was offline', busy: 'was busy', rejected: 'declined it', aborted: 'stopped it before it started', timeout: 'did not answer in time', skipped: 'was skipped', queued: 'was queued', expired: 'did not take it before the queue expired', paused: 'was paused', lost: 'dropped before it started the run', } function describePass(attempt: RoutingAttempt) { const who = (attempt.name && !looksLikeContextId(attempt.name, attempt.target) ? attempt.name : null) ?? (attempt.reason === 'gone' ? 'a context that no longer exists' : 'an execution context') const reason = attempt.reason && attempt.reason !== 'gone' ? ` (${attempt.reason.replaceAll('_', ' ')})` : '' return `${who} ${passPhrases[attempt.outcome] ?? attempt.outcome}${reason}` } /** A missing chain ref keeps the raw ref as its name; never print an id. */ function looksLikeContextId(name: string, target: string) { return name === target || /^ec_[a-z0-9]+$/i.test(name) } function joinList(items: Array) { if (items.length <= 1) return items.join('') return `${items.slice(0, -1).join(', ')} and ${items.at(-1)}` } function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value) } export type RoutingOutcome = | { kind: 'cloud'; metadata: ExecutionContextRunMetadata | null } | { kind: 'queued' runId: string contextId: string contextName: string expiresAt: number metadata: ExecutionContextRunMetadata } | { kind: 'ran' result: ExecutionContextRunResult metadata: ExecutionContextRunMetadata } | { kind: 'pending' runId: string contextId: string metadata: ExecutionContextRunMetadata } /** * Pure: a committed run whose context dropped may go to a later target only * when the context never started it (its daemon had to confirm it was ready * and did not) and the caller's routing left one, such as Kody cloud at the * end of the chain. */ export function lostRunCanMoveOn(input: { mayHaveStarted: boolean laterTargets: ReadonlyArray }) { return !input.mayHaveStarted && input.laterTargets.length > 0 } /** Pure: the ordered targets a run may try, before availability probes. */ export function planTargets(input: { named: ExecutionContextRow | 'cloud' | null fallback: 'chain' | undefined chain: Array<{ kind: 'context'; id: string } | { kind: 'cloud' }> strict: boolean requires: ReadonlyArray /** * Unset automations always fall back to Kody cloud immediately when no * context in the chain can take the run, even when the stored chain is strict. */ allowCloudFallbackOnStrictChain?: boolean }): Array<{ kind: 'context'; id: string } | { kind: 'cloud' }> { const cloudAllowed = input.requires.length === 0 const targets: Array<{ kind: 'context'; id: string } | { kind: 'cloud' }> = [] if (input.named === 'cloud') { return cloudAllowed ? [{ kind: 'cloud' }] : [] } if (input.named) { targets.push({ kind: 'context', id: input.named.id }) if (input.fallback !== 'chain') return targets } for (const entry of input.chain) { if (entry.kind === 'cloud') continue if (targets.some((t) => t.kind === 'context' && t.id === entry.id)) { continue } targets.push(entry) } const chainHasCloud = input.chain.some((entry) => entry.kind === 'cloud') if ( cloudAllowed && (chainHasCloud || (!input.named && (!input.strict || input.allowCloudFallbackOnStrictChain === true))) ) { targets.push({ kind: 'cloud' }) } return targets } /** Why a grant cannot meet the run's `requires`, or null when it can. */ export function requirementRefusal( grant: EcpGrant, requires: ReadonlyArray, capabilities: EcpCapabilities, ): string | null { if (requires.includes('fs')) { if (grant.fs.length === 0) return 'no_fs' if (!(capabilities.features ?? []).includes('fs')) return 'no_local_fs' } if (requires.includes('lan') && grant.egress.mode !== 'public-and-lan') { return 'no_lan' } return null } /** * A grant timeout the operator set. Rows stored before `timeoutMsExplicit` * existed count as explicit only when they differ from the default. */ export function grantTimeoutIsExplicit(grant: EcpGrant) { return ( grant.limits.timeoutMsExplicit === true || grant.limits.timeoutMs !== ecpDefaultGrant.limits.timeoutMs ) } /** * For ordinary context runs, use the surface budget unless the operator * set a grant timeout. Publish builds use their own deadline. */ export function contextRunTimeoutMs(input: { grant: EcpGrant surfaceTimeoutMs: number }) { return grantTimeoutIsExplicit(input.grant) ? input.grant.limits.timeoutMs : input.surfaceTimeoutMs } /** * Host folders are for the operator's own runs only. A shared run cannot * require them, and skips a context with host folders whose daemon predates * that rule (it would still mount them for every run). */ export function sharedRunHostRefusal(input: { grant: EcpGrant requires: ReadonlyArray capabilities: EcpCapabilities sharedRun: boolean }): string | null { if (!input.sharedRun) return null if (input.requires.includes('fs')) return 'fs_operator_only' if (input.grant.fs.length === 0) return null return (input.capabilities.features ?? []).includes( ecpHostOperatorOnlyFeature, ) ? null : 'fs_daemon_outdated' } /** * A daemon from before {@link ecpTypeScriptSourceFeature} runs execute code * as plain JavaScript, so code that only parses as TypeScript skips it with * a "please update" reason instead of failing there with a syntax error. */ export async function typeScriptSourceRefusal( code: string, capabilities: EcpCapabilities, ): Promise { if ((capabilities.features ?? []).includes(ecpTypeScriptSourceFeature)) { return null } const parseJavaScript = await loadJavaScriptParser() try { parseJavaScript(code, { ecmaVersion: 'latest', sourceType: 'module' }) return null } catch { return 'typescript_daemon_outdated' } } const savedPackageImportPattern = /(?:\bfrom\s*|\bimport\s*\(?\s*)['"`]kody:@/ /** * Saved package code resolves package storage, secrets, and credentials * through the run store. A daemon from before * {@link ecpPackageRuntimeStoreFeature} lacks those services, so code that * loads saved packages skips it with a "please update" reason instead of * failing partway through the run. */ export function packageRuntimeRefusal( code: string, capabilities: EcpCapabilities, ): string | null { if ((capabilities.features ?? []).includes(ecpPackageRuntimeStoreFeature)) { return null } return savedPackageImportPattern.test(code) ? 'package_runtime_daemon_outdated' : null } /** * A publish build clones with `git`. A daemon advertises * {@link ecpPublishBuildFeature} only when it found it (older daemons never * do), so a machine without git is skipped instead of failing the publish. */ export function publishBuildSupported(capabilities: EcpCapabilities) { return (capabilities.features ?? []).includes(ecpPublishBuildFeature) } /** Why a context cannot take this run, or null when it can. */ export function grantRefusal(input: { grant: EcpGrant requires: ReadonlyArray /** What the daemon advertised; `fs` means its effective mount set is non-empty. */ capabilities: EcpCapabilities /** The requester is not the operator (see {@link sharedRunHostRefusal}). */ sharedRun: boolean }): string | null { return ( requirementRefusal(input.grant, input.requires, input.capabilities) ?? sharedRunHostRefusal(input) ) } function noContext(attempts: Array, message: string): never { throw new ExecutionContextError({ status: 409, code: 'no_execution_context_available', message, details: { attempts }, }) } const acceptWindowMs = 10_000 /** How long one chain load stays fresh enough to authorize later targets. */ const chainLoadMaxAgeMs = 1_000 /** * Picks where an execute runs. Returns `cloud` to let the hosted sandbox * run it, or the context run's result. Only called when the flag is on. */ export async function routeExecute(input: { env: Env request: { userId: string handle: string | null orgId: string orgSlug: string | null scopes: Array | null credentialKind: string /** * The caller's access when it acts as a profile (ADR 0092): every * layer of its chain must hold execution_context:execute on a context, * even one the person operates. */ profileAccess?: EffectivePermissions | null /** That profile's id, carried on the lease so callbacks stay narrowed. */ profileId?: string | null /** The trigger enablement the request runs for (`enablementIdOf`). */ enablementId?: string | null } args: ExecuteRoutingArgs runId: string runRecord: RunRecordHandle | null code: string | null params: unknown conversationId?: string responseLimit?: number credentials: CredentialCallMap | null apiUrl: string waitMs: number signal?: AbortSignal /** * Queue on the first offline or busy context until it can take the run, * instead of failing, when no later target can (automations only). A * cloud entry in the targets always wins over queueing. */ queue?: { expiresAt: number } | null /** `skip` records an unknown chain entry as skipped instead of a 404. */ unknownChainRef?: 'error' | 'skip' /** * Publish offload: run the daemon's builder instead of user code. Only * contexts the requester operates may take it, it carries no credential * picks or params, and it gets the publish-build limits. */ publishBuild?: { loadSource: () => Promise limits: { timeoutMs: number; memoryMb: number } } | null /** * Unset automations fall back to Kody cloud immediately even when the * actor's stored chain is strict. */ allowCloudFallbackOnStrictChain?: boolean /** * The surface's Kody cloud sandbox budget (ms): the run gets the same on * any context, the operator's own or one shared from another org. * Unset means interactive (`defaultExecutorTimeoutMs`). */ surfaceTimeoutMs?: number | null /** A workflow step: its deadline copy says to split the step. */ workflowStep?: boolean /** * Declared non-exported automation handler authorized for this run only. */ automationHandler?: AutomationInternalHandler | null automationPackageName?: string | null }): Promise { const requires = [...new Set(input.args.requires ?? [])] const db = input.env.APP_DB const namedRef = input.args.context?.trim() || null let named: ExecutionContextRow | 'cloud' | null = null let namedMissing: RoutingAttempt | null = null if (namedRef === 'cloud') { named = 'cloud' } else if (namedRef) { named = await resolveExecutionContextRef(db, input.request.orgId, namedRef) if ( !named && input.unknownChainRef === 'skip' && input.args.fallback === 'chain' ) { namedMissing = { target: namedRef, name: namedRef, outcome: 'skipped', reason: 'not_found', } } else if (!named) { throw new ExecutionContextError({ status: 404, code: 'not_found', message: `No execution context named ${namedRef} in this org. Run executionContextList to see the ones you can use.`, }) } } const chain = input.args.chain ? await resolveRunChain(db, { orgId: input.request.orgId, refs: input.args.chain, unknownRef: input.unknownChainRef ?? 'error', }) : { ...(await getChain(db, { orgId: input.request.orgId, userId: input.request.userId, })), skipped: [] as Array, } const targets = planTargets({ named, fallback: input.args.fallback, chain: chain.entries, strict: chain.strict, requires, allowCloudFallbackOnStrictChain: input.allowCloudFallbackOnStrictChain === true && !input.args.chain, }) const attempts: Array = [ ...(namedMissing ? [namedMissing] : []), ...chain.skipped, ] const metadata = ( row: ExecutionContextRow | null, fellBackToCloud: boolean, ): ExecutionContextRunMetadata => ({ id: row?.id ?? null, name: row?.name ?? null, ...(row ? { yours: row.operator_user_id === input.request.userId } : {}), attempts, fellBackToCloud, }) const onlyCloud = targets.every((t) => t.kind === 'cloud') if (onlyCloud && targets.length > 0) { return { kind: 'cloud', metadata: attempts.length > 0 ? metadata(null, true) : null, } } const waitUntil = Date.now() + input.waitMs // Contexts left from `index` on, loaded together. An attempt that waits on // a context (an offered run that timed out, was rejected, or was lost) can // last long enough for a later one to be paused or unshared, so what is // left reloads once the load is older than `chainLoadMaxAgeMs`. Contexts // that answer offline or busy at once share one load. const loadFrom = async (index: number) => { const loadedAt = Date.now() const contexts = await loadChainContexts( db, targets .slice(index) .flatMap((target) => (target.kind === 'context' ? [target.id] : [])), { userId: input.request.userId, orgId: input.request.orgId }, ) return { ...contexts, loadedAt } } let loaded: Awaited> | null = null let lastTried: ExecutionContextRow | null = null let firstOffline: { row: ExecutionContextRow request: EcpRunRequestBody lease: ExecutionContextLease requires: Array } | null = null let unsettledLoss: (() => Promise) | null = null for (const [index, target] of targets.entries()) { if (target.kind === 'cloud') { return { kind: 'cloud', metadata: metadata(lastTried, true) } } if (!loaded || Date.now() - loaded.loadedAt > chainLoadMaxAgeMs) { loaded = await loadFrom(index) } const { rowsById, accessById } = loaded const row = named && named !== 'cloud' && named.id === target.id ? named : rowsById.get(target.id) if (!row) { attempts.push({ target: target.id, outcome: 'skipped', reason: 'gone' }) continue } lastTried = row const skip = (reason: UnusableReason | string) => attempts.push({ target: row.id, name: row.name, outcome: 'skipped', reason, }) // Every credential kind, not only CLI logins: a scoped token without // execution_context:execute never reaches a context. if (!hasContextScope(input)) { skip('credential_scope') continue } const profileAccess = input.request.profileAccess if ( profileAccess && !checkPermission(profileAccess, 'execution_context:execute', { type: 'execution_context', id: row.id, orgId: input.request.orgId as OwnerId, }).allowed ) { skip('profile_grant') continue } const access = accessById.get(row.id) if (!access?.usable) { skip(access?.unusableReason ?? 'not_granted') continue } // Paused contexts are skipped like offline ones but never queued on. if (row.paused_at) { attempts.push({ target: row.id, name: row.name, outcome: 'paused' }) continue } const grant = parseGrant(row) const sharedRun = row.operator_user_id !== input.request.userId if (sharedRun) { await refreshContextNotices(db, row, input.request.orgId, { userIds: [input.request.userId], notify: input.env, }) } const refusal = grantRefusal({ grant, requires, capabilities: parseCapabilities(row), sharedRun, }) if (refusal) { skip(refusal) continue } const sourceRefusal = input.code !== null && !input.publishBuild ? (packageRuntimeRefusal(input.code, parseCapabilities(row)) ?? (await typeScriptSourceRefusal(input.code, parseCapabilities(row)))) : null if (sourceRefusal) { skip(sourceRefusal) continue } if (input.publishBuild && sharedRun) { skip('not_operator') continue } if (input.publishBuild && !publishBuildSupported(parseCapabilities(row))) { skip('publish_build_unsupported') continue } if (!input.code && !input.publishBuild) { skip('invoke_not_supported') continue } const publishSource = await input.publishBuild?.loadSource() const now = Date.now() const surfaceTimeoutMs = input.publishBuild?.limits.timeoutMs ?? input.surfaceTimeoutMs ?? defaultExecutorTimeoutMs const effectiveTimeoutMs = input.publishBuild?.limits.timeoutMs ?? contextRunTimeoutMs({ grant, surfaceTimeoutMs, }) const deadline = now + effectiveTimeoutMs const lease: ExecutionContextLease = { runId: input.runId, ecid: row.id, requester: { userId: input.request.userId, handle: input.request.handle, }, orgId: input.request.orgId, callerScopes: input.request.scopes, ...(input.request.profileId ? { profileId: input.request.profileId } : {}), runtime: grant.runtime, deadline, timeoutMs: effectiveTimeoutMs, surfaceTimeoutMs, ...(input.workflowStep ? { workflowStep: true } : {}), sharedRun, credentials: credentialCallMapToJson(input.credentials), ...(input.automationHandler ? { automationHandler: input.automationHandler } : {}), ...(input.automationPackageName ? { automationPackageName: input.automationPackageName } : {}), ...(input.request.enablementId && !input.publishBuild ? { enablementId: input.request.enablementId } : {}), } const request: EcpRunRequestBody = { runId: input.runId, deadline, acceptBy: now + acceptWindowMs, requestedBy: { userId: input.request.userId, handle: input.request.handle, orgId: input.request.orgId, orgSlug: input.request.orgSlug, }, source: publishSource ?? { kind: 'code', code: input.code!, sha256: await sha256Base64Url(new TextEncoder().encode(input.code!)), }, params: input.publishBuild ? {} : (input.params ?? {}), ...(input.conversationId ? { conversationId: input.conversationId } : {}), ...(input.responseLimit !== undefined ? { responseLimit: input.responseLimit } : {}), credentialPicks: input.publishBuild ? {} : credentialPicks(input.credentials), limits: { timeoutMs: effectiveTimeoutMs, maxResultBytes: grant.payload.maxResultBytes, memoryMb: input.publishBuild?.limits.memoryMb ?? grant.limits.memoryMb, }, grantVersion: row.grant_version, apiUrl: input.apiUrl, ...(lease.sharedRun ? { sharedRun: true } : {}), } const stub = sessionStub(input.env, row.id) if (input.runRecord) { input.runRecord.context.metadata = { ...input.runRecord.context.metadata, executionContext: { ...metadata(row, false), attempts: [ ...attempts, { target: row.id, name: row.name, outcome: 'ran' }, ], }, } } const dispatched = await withDeadline( { label: 'stub.dispatch', timeoutMs: outboundTimeoutMs.durableObjectLongWork, }, () => stub.dispatch({ request, lease, runRecord: input.runRecord, hopRecordingExpiresAt: row.hop_recording_expires_at ?? undefined, position: attempts.length + 1, }), ) if (dispatched.outcome !== 'committed') { if ( ((dispatched.outcome === 'offline' && dispatched.code !== 'revoked') || dispatched.outcome === 'busy') && !firstOffline ) { firstOffline = { row, request, // The drain re-checks the grant, which may change while queued. lease, requires, } } attempts.push({ target: row.id, name: row.name, outcome: dispatched.outcome, ...(dispatched.code ? { reason: dispatched.code } : {}), }) continue } const ranAttempt: RoutingAttempt = { target: row.id, name: row.name, outcome: 'ran', } attempts.push(ranAttempt) const ran = metadata(row, false) const cancel = (reason: EcpCancelReason) => withDeadline( { label: 'stub.cancel', timeoutMs: outboundTimeoutMs.durableObject }, () => stub.cancel({ runId: input.runId, reason }), ).catch((error: unknown) => // The run can keep going in the context; the caller's outcome stands. reportHandledError('cancel-execution-context-run', error), ) const lostResult = (): RoutingOutcome => ({ kind: 'ran', result: failure( `${row.name} stopped answering while running this run, so its outcome is unknown. Kody did not retry it.`, 'execution_context_lost', ), metadata: ran, }) let cancelling: Promise | null = null const onAbort = () => { cancelling ??= cancel('caller_cancelled') } input.signal?.addEventListener('abort', onAbort, { once: true }) // An abort signal does not replay: a caller that left during dispatch // fired it before this listener existed, so cancel here. if (input.signal?.aborted) onAbort() try { const settled = await withDeadline( { label: 'stub.await_result', timeoutMs: outboundTimeoutMs.durableObjectLongWork, }, () => stub.awaitResult({ runId: input.runId, // One wait allowance for the whole call, however many targets ran. // Past the deadline by the lost window, so a deadline cancel // reports as one instead of as a still-pending run. waitMs: Math.max( 0, Math.min(waitUntil, deadline + ecpLostAfterDeadlineMs) - Date.now(), ), }), ) if ('result' in settled) { const { timing, ...result } = settled.result as ExecutionContextRunResult return { kind: 'ran', result, metadata: timing ? { ...ran, timing } : ran, } } switch (settled.state) { case 'cancelled': return { kind: 'ran', result: failure( contextRunCancelledSummary({ reason: settled.reason ?? 'cancelled', context: row.name, timeoutMs: effectiveTimeoutMs, surfaceTimeoutMs, workflowStep: input.workflowStep === true, timing: settled.timing ?? null, }), 'execution_context_cancelled', ), metadata: ran, } case 'lost': // The context dropped before it started the run, so a later // target (Kody cloud) can still take it. if ( lostRunCanMoveOn({ mayHaveStarted: settled.mayHaveStarted, laterTargets: targets.slice(targets.indexOf(target) + 1), }) ) { ranAttempt.outcome = 'lost' unsettledLoss = async () => { await withDeadline( { label: 'stub.record_lost_run', timeoutMs: outboundTimeoutMs.durableObject, }, () => stub.recordLostRun({ runId: input.runId }), ) return lostResult() } continue } if (!settled.mayHaveStarted) { await withDeadline( { label: 'stub.record_lost_run', timeoutMs: outboundTimeoutMs.durableObject, }, () => stub.recordLostRun({ runId: input.runId }), ) } return lostResult() case 'unknown': return lostResult() case 'pending': return { kind: 'pending', runId: input.runId, contextId: row.id, metadata: ran, } } } finally { input.signal?.removeEventListener('abort', onAbort) // A caller that gave up settles only once the context dropped the // run, so a retry or replay never starts beside it. await cancelling } } // No later target took a run that an earlier context lost unstarted, so // the loss is the outcome: it is never queued or reported as no context. if (unsettledLoss) return await unsettledLoss() if (input.queue && firstOffline) { const { row, request, lease } = firstOffline const stub = sessionStub(input.env, row.id) const queuedMetadata: ExecutionContextRunMetadata = { id: row.id, name: row.name, yours: row.operator_user_id === input.request.userId, attempts: [ ...attempts, { target: row.id, name: row.name, outcome: 'queued' }, ], fellBackToCloud: false, } if (input.runRecord) { input.runRecord.context.metadata = { ...input.runRecord.context.metadata, executionContext: queuedMetadata, } } await withDeadline( { label: 'stub.enqueue', timeoutMs: outboundTimeoutMs.durableObject }, () => stub.enqueue({ request, lease, runRecord: input.runRecord, requires: firstOffline.requires, position: attempts.length + 1, expiresAt: input.queue!.expiresAt, }), ) return { kind: 'queued', runId: input.runId, contextId: row.id, contextName: row.name, expiresAt: input.queue.expiresAt, metadata: queuedMetadata, } } if ( requires.length > 0 && (named === 'cloud' || (chain.entries.some((entry) => entry.kind === 'cloud') && (!named || input.args.fallback === 'chain'))) ) { attempts.push({ target: 'cloud', name: 'Kody cloud', outcome: 'skipped', reason: requires.includes('fs') ? 'no_fs' : 'no_lan', }) } if (named && named !== 'cloud' && input.args.fallback !== 'chain') { const namedAttempt = attempts.find((a) => a.target === named.id) noContext( attempts, namedAttempt?.outcome === 'paused' ? `${named.name} is paused, so it takes no runs. Its operator or someone with Manage on it can resume it with \`kody daemon resume --context ${named.name}\` or executionContextResume. A named context never falls back; pass fallback: "chain" to use your chain instead.` : namedAttempt?.outcome === 'busy' ? `${named.name} is busy: it is already running as many runs as it allows at once, so it could not take this run. A named context never falls back; try again when one of its runs finishes, or pass fallback: "chain" to use your chain instead.` : `${named.name} could not take this run (${describeAttempts(attempts)}). A named context never falls back; pass fallback: "chain" to use your chain instead.`, ) } noContext( attempts, attempts.length === 0 ? requires.length > 0 ? `This run requires ${requires.join(' and ')}, which Kody cloud cannot provide, and no context in your chain can take it. Add one with executionChainSet.` : 'Your chain is strict and has no contexts, so this run had nowhere to go. Add a context or Kody cloud with executionChainSet.' : `No execution context could take this run (${describeAttempts(attempts)}).`, ) } /** Scope gate for every credential kind (CLI login, API token, OAuth, ...). */ export function hasContextScope(input: { request: { scopes: Array | null } }) { const scopes = input.request.scopes return scopes === null || scopes.includes('execution_context:execute') } const contextReasonText: Record = { not_operator: 'not_operator: publish builds run only on contexts you operate yourself', profile_grant: 'profile_grant: the profile this credential acts as, or a parent profile, was not granted execution_context:execute on it', no_fs: 'no_fs: its server grant lists no host folders (grant.fs is off on the server, whatever the local policy allows); someone with Contribute or Manage on it can turn it on with `kody context grant allow --context {name}`', no_local_fs: "no_local_fs: its server grant lists host folders, but the machine's local policy allows none of them; the machine owner can allow one there with `kody context policy allow `", no_lan: 'no_lan: its server grant does not allow the local network (grant.egress is not public-and-lan); someone with Contribute or Manage on it can turn it on with `kody context grant lan on --context {name}`', fs_operator_only: "fs_operator_only: host folders are only for the operator's own runs", fs_daemon_outdated: "fs_daemon_outdated: it has host folders and its daemon is too old to keep them to the operator's runs; the operator can update it with `kody daemon update`", typescript_daemon_outdated: 'typescript_daemon_outdated: this code is TypeScript and its daemon is too old to run TypeScript; please update it with `kody daemon update`', package_runtime_daemon_outdated: 'package_runtime_daemon_outdated: this code loads saved packages and its daemon is too old to give them package storage, secrets, and credentials; please update it with `kody daemon update`', operator_left: 'operator_left: the person who runs this machine is no longer a member of this org', publish_build_unsupported: 'publish_build_unsupported: update the Kody CLI on this context. For a released install, run `kody daemon update`. For a source or branch install, update the checkout, rebuild the CLI, and restart the daemon from that build. Make sure git is installed, or publish with `--context cloud`', } export function describeAttempts(attempts: ReadonlyArray) { return attempts .map((a) => { const reason = a.reason && a.target !== 'cloud' ? (contextReasonText[a.reason]?.replaceAll( '{name}', a.name ?? '', ) ?? a.reason) : a.reason return `${a.name ?? a.target}: ${a.outcome}${reason ? ` (${reason})` : ''}` }) .join('; ') } function credentialPicks(map: CredentialCallMap | null) { const picks: Record> = {} for (const [key, values] of map ?? []) { picks[key] = values.map((pick) => ('id' in pick ? pick.id : pick.name)) } return picks } function failure(message: string, code: string): ExecutionContextRunResult { return { isError: true, content: [{ type: 'text', text: `Error: ${message}` }], structuredContent: { error: message, errorCode: code }, } } /** * Resolves a run's own chain. Shape rules (cloud last, at most * {@link ecpMaxChainContexts} contexts, no repeats) match the default chain. */ export async function resolveRunChain( db: D1Database, input: { orgId: string refs: ReadonlyArray unknownRef: 'error' | 'skip' }, ): Promise<{ entries: Array strict: boolean skipped: Array }> { const shapeError = runChainShapeError(input.refs) if (shapeError) { throw new ExecutionContextError({ status: 400, code: shapeError.code, message: shapeError.message, }) } const entries: Array = [] const skipped: Array = [] for (const raw of input.refs) { const ref = raw.trim() if (ref === 'cloud') { entries.push({ kind: 'cloud' }) continue } const row = await resolveExecutionContextRef(db, input.orgId, ref) if (!row) { if (input.unknownRef === 'error') { throw new ExecutionContextError({ status: 404, code: 'not_found', message: `No execution context named ${ref} in this org. Run executionContextList to see the ones you can use.`, }) } skipped.push({ target: ref, outcome: 'skipped', reason: 'not_found' }) continue } if (entries.some((e) => e.kind === 'context' && e.id === row.id)) continue entries.push({ kind: 'context', id: row.id }) } return { entries, strict: !entries.some((entry) => entry.kind === 'cloud'), skipped, } } /** A queued run that ended unrun (expiry, revocation): mark it `expired`. */ export function markQueuedAttemptExpired( metadata: Record, reason = 'queue_expired', ): Record { return markQueuedAttempt(metadata, { outcome: 'expired', reason }) } /** A queued run that the context took after reconnecting ran there. */ export function markQueuedAttemptRan( metadata: Record, ): Record { return markQueuedAttempt(metadata, { outcome: 'ran' }) } /** Records a finished context run's timing on its run-record metadata. */ export function withRunTiming( metadata: Record, timing: ExecutionContextRunTiming, ): Record { const context = metadata.executionContext as | ExecutionContextRunMetadata | undefined if (!context) return metadata return { ...metadata, executionContext: { ...context, timing } } } export function withLostRunTiming( metadata: Record, ): Record { const context = metadata.executionContext as | ExecutionContextRunMetadata | undefined if (!context) return metadata return { ...metadata, executionContext: { ...context, timingMissing: 'daemon_lost' }, } } function markQueuedAttempt( metadata: Record, update: Pick, ): Record { const context = metadata.executionContext as | ExecutionContextRunMetadata | undefined if (!context?.attempts?.length) return metadata return { ...metadata, executionContext: { ...context, attempts: context.attempts.map((attempt, index) => index === context.attempts.length - 1 && attempt.outcome === 'queued' ? { ...attempt, ...update } : attempt, ), }, } } /** * A queued run acting as a profile waits for a reconnect; recheck its chain * and `execution_context:execute` before it dispatches. Null means it may run. */ export async function queuedProfileRefusal(input: { env: Env lease: Pick< ExecutionContextLease, 'profileId' | 'orgId' | 'requester' | 'ecid' | 'runId' > context: { id: string; org_id: string } }): Promise { const { lease } = input if (!lease.profileId) return null const binding = await loadOrgBindingForOrg( input.env.APP_DB, lease.requester.userId, lease.orgId, ) if (!binding) return 'the person this run acts as is no longer in the org' const request = deriveRequestContext({ user: { userId: lease.requester.userId as PersonId, username: lease.requester.handle ?? lease.requester.userId, }, source: { kind: 'execution-context-run', ecid: lease.ecid, runId: lease.runId, }, orgBinding: binding, profileId: lease.profileId, }) const access = await computeEffectivePermissions({ env: input.env, request }) const decision = checkPermission(access, 'execution_context:execute', { type: 'execution_context', id: input.context.id, orgId: input.context.org_id as OwnerId, }) return decision.allowed ? null : 'the profile this run acts as, or a parent profile, is revoked, expired, or no longer granted execution_context:execute on it' }