@inquir/compute
v0.4.7
Published
Workspace-first SDK for Inquir Compute assets.
Readme
@inquir/compute
Workspace-first SDK for defining, discovering, generating, and running Inquir Compute assets.
Install
Requires Node.js 22 or newer. Version 0.3 groups only long-lived container applications in projects; functions and pipelines remain separate assets.
npm install @inquir/compute zod@^3.23.8Release order: publish this SDK before the CLI that depends on it. CLI 0.4.0 needs SDK 0.4.0 (
isPromoteAccepted,getApplicationRollout); CLI 0.4.1 needs SDK 0.4.2 (listAppInstances,matchAppInstance,createSourceArchive,manifestBuildContext,getProductionReplacement); the CLI after 0.4.1 needs SDK 0.4.3 (addApplicationDomain(..., { acknowledgeWildcardRisks })); CLI 0.4.5 needs SDK 0.4.6 (packComposeFolderforinquir compose pack); seepackages/cli/README.md, "Publishing to npm".
What It Includes
defineFunction()anddefinePipeline()for code-first assets.loadConfig()forinquir.config.json.discoverAssets()for workspace asset scanning.generateCodegenArtifacts()/generateAndWriteCodegenArtifacts()for typed client +registry.json.runLocally()for local function execution/debug harness.- HTTP transport helpers (
createClient,invokeRemote, deploy/list helpers). client.sandboxes: create, exec (streaming), files and destroy for isolated, short-lived Linux sandboxes.- Application project helpers (
listProjects,createProject,getProject,addProjectResource) group long-lived containers: web services, APIs, databases, and workers. Project members usekind: 'application'; serverless functions are managed separately.createApplicationacceptsprojectId(ID or slug); omitting it creates a project named after the application. Archiving a project also archives all its applications, including an application shared with another project. Removing a membership leaves it running. Project lifecycle actions requireprojects:writeandapps:promote.
Pending synchronous invocations
When the server admits a finite cold invocation, invokeRemote() submits once
and follows only the authenticated invocation's /resume endpoint. Hot
invocations keep their existing path. Save each handle from onPending if the
caller must survive a restart:
import { invokeRemote, resumeRemoteInvocation, cancelRemoteInvocation,
RemoteInvocationObservationEndedError } from '@inquir/compute';
try {
const result = await invokeRemote(client, 'my-function', event, {
timeoutMs: 120_000, signal, onPending: saveHandle,
});
} catch (error) {
if (error instanceof RemoteInvocationObservationEndedError) {
saveHandle(error.pending); // PENDING/RECOVERY_HELD is not FAILED.
// Later: await resumeRemoteInvocation(client, error.pending);
// Explicit intent: await cancelRemoteInvocation(client, error.pending);
} else throw error;
}Abort/timeout stops observation, not execution. A cancellation receipt records intent, not a terminal outcome. If the initial POST reply is lost before a handle arrives, this adapter cannot recover an unknown server ID and never repeats that POST. Server admission remains independently gated; this client does not enable gateway, pipeline, durable or streaming finite execution.
Durable source commands
Source execution uses an explicit operation instead of synchronous writable
/exec. Save a lowercase UUID v4 before preparing, and atomically retain every
record supplied by the callback in private storage. Records contain command/env
secrets; they contain a credential hash rather than the credential itself.
import { createClient, prepareSourceCommand, restoreSourceCommand } from '@inquir/compute';
const client = createClient({ baseUrl: apiUrl, apiKey, workspaceId });
const operation = await prepareSourceCommand(client, {
function: 'my-function', requestId: savedUuid,
input: { command: 'npm install', timeoutMs: 60_000 },
retain: savePrivateRecordAtomically,
});
await operation.submit(); // no automatic POST retry
const state = await operation.status(); // GET only
const publication = await operation.reconcile(); // explicit source publication
// await operation.cancel(); // explicit cancellation intent
const restored = await restoreSourceCommand(client, savedRecord, {
retain: savePrivateRecordAtomically,
}); // no HTTP or submissionThe retained API, credential hash, original workspace selector and resolved
workspace/function IDs must match on restore. Later actions stay pinned to those
IDs even if the client changes. A lost response keeps the same operation UUID;
inspect status or explicitly retry the same action. Poll timeout/abort stops
observation and does not cancel or publish. EXITED and CANCEL_REQUESTED do not
prove physical removal or capacity release. A GET with publication: null does
not prove that an earlier explicit publication never happened.
Acceptance identity is retained before an action returns and after each poll
response. If storage fails, further HTTP is blocked until the pending record is
saved; operation.persist() retries storage without HTTP. Keep the updated
record returned by record() for reloads. The server must enable the source
command API after its activation gates; a 503 never falls back to writable exec.
result.logFailure and sourcePublicationState(outcome) === 'CAPTURE_FAILED'
mark unavailable log capture, preserving the real termination and exit code.
Blank Base64 fields then mean unavailable capture rather than successful empty
logs; workspace output is absent and cannot be published.
Concepts
- Function: a single compute unit with typed input/output (Zod schemas). Created with
defineFunction(). Discovered by file pattern, run locally viarunLocally(), deployed and invoked remotely via the transport helpers. - Pipeline: a declarative DAG of functions created with
definePipeline(). Included in the codegen registry; orchestration is handled server-side. - Client: the generated
client.ts(fromgenerateAndWriteCodegenArtifacts()). Provides a type-safecreateClient()factory that wrapsinvokeRemote()with your asset's I/O types. - Source of truth: local files on disk.
registry.jsonis derived — rebuild it withgenerateAndWriteCodegenArtifacts()whenever sources change. - Local ↔ remote link: remote functions store
linkedLocalName(local asset name) andsourceHash. Compare hashes to detect drift.
Quick Example
import { defineFunction } from '@inquir/compute';
import { z } from 'zod';
export const hello = defineFunction(
{
name: 'hello',
input: z.object({ name: z.string().optional() }),
output: z.object({ message: z.string() }),
},
async (input) => ({ message: `Hello, ${input.name ?? 'world'}` })
);Minimal Workspace Config
Create inquir.config.json:
{
"functionsDir": "inquir/functions",
"pipelinesDir": "inquir/pipelines",
"generatedDir": ".inquir/generated"
}Discovery + Codegen
import { discoverAssets, generateAndWriteCodegenArtifacts, loadConfig } from '@inquir/compute';
const config = loadConfig(process.cwd());
const registry = await discoverAssets(config);
await generateAndWriteCodegenArtifacts(config.absoluteGeneratedDir, registry);This generates:
.inquir/generated/client.ts.inquir/generated/registry.json
registry.json includes stable metadata such as name, kind, sourceHash, and assetRoot.
Local Run
import { runLocally } from '@inquir/compute';
const result = await runLocally(
{
kind: 'function',
name: 'hello',
filePath: '/abs/path/inquir/functions/hello/index.ts',
exportName: 'hello',
},
{ name: 'World' }
);Remote Invoke (Transport)
import { createClient, invokeRemote } from '@inquir/compute';
const client = createClient({ baseUrl: 'http://localhost:3000', apiKey: process.env.INQUIR_API_KEY });
const response = await invokeRemote(client, 'hello', { name: 'World' });Sandboxes
client.sandboxes runs code in isolated, short-lived Linux environments
(Ubuntu, Node 22, Python 3.12, git): generated code, tests, dependency
installs, untrusted repositories. The argument of create is the same
SandboxSpec the API, inquir sandbox create and the dashboard form use.
import { createClient } from '@inquir/compute';
const client = createClient({ baseUrl: 'https://api.inquir.org', apiKey: process.env.INQUIR_API_KEY });
await using sbx = await client.sandboxes.create({ network: { mode: 'proxy', allow: ['npm'] } });
await sbx.files.write('/workspace/index.js', 'console.log(1 + 1)');
const r = await sbx.exec(['node', 'index.js'], { onStdout: (chunk) => process.stdout.write(chunk) });
console.log(r.exitCode); // the sandbox is destroyed when the block exits| Call | Endpoint | Notes |
|---|---|---|
| create(spec?, { wait?, idempotencyKey? }) | POST /v1/sandboxes | waits until RUNNING unless wait: false; a random Idempotency-Key unless you pass one; returns a Sandbox handle |
| get(id) | GET /v1/sandboxes/:id | a Sandbox handle |
| list({ all?, limit?, cursor? }), iterate() | GET /v1/sandboxes | one page, or every sandbox page after page; all includes ended ones |
| exec(id, cmd, { cwd?, env?, timeoutMs?, stdin?, onStdout?, onStderr?, signal? }) | POST /v1/sandboxes/:id/exec | cmd as argv, or a string for sh -c; resolves with { exitCode, stdout, stderr, timedOut, truncated, durationMs } |
| stream(id, cmd, options?) | same | an async iterator over the frames (start, stdout, stderr, exit or error); leaving the loop cancels the exec |
| files.write/read/readText(id, path) | PUT/GET /v1/sandboxes/:id/files?path= | one file |
| files.upload/download(id, directory) | same, as tar | a directory |
| keepAlive(id) | POST /v1/sandboxes/:id/keepalive | moves the idle deadline, never past the absolute one |
| destroy(id) | DELETE /v1/sandboxes/:id | idempotent |
| capabilities() | GET /v1/sandboxes/capabilities | whether this workspace may use sandboxes, and the plan's limits |
| execDetached(id, cmd, options?), getExec(id, execId, { encoding? }) | POST …/exec?detach=1, GET …/exec/:execId | a command nobody streams; its outcome and the last 256 KiB of each stream, kept 10 minutes |
| shellTicket(id, { cols?, rows? }), shellUrl(id) | POST …/shell-ticket, WebSocket …/shell | a one-use, 60-second ticket; open the URL offering ticket.protocol as the subprotocol (frames: SandboxShellClientFrame / SandboxShellServerFrame) |
| usage() | GET /v1/sandboxes/usage | this month's sandbox-seconds, vCPU-s, GiB-s and live count next to the plan's allowance; each sandbox's own figures are info.usage |
A Sandbox handle carries id and info (the last known state) and the same
operations without the id: exec, stream, files.*, keepAlive, destroy,
refresh, and Symbol.asyncDispose for await using.
for await (const frame of sbx.stream('npm test', { cwd: '/workspace/repo', timeoutMs: 600_000 })) {
if (frame.type === 'stdout' || frame.type === 'stderr') process.stdout.write(frame.data);
if (frame.type === 'exit') process.exitCode = frame.exitCode ?? 1;
}exitCode is null when the process was killed (timeout, cancel, output cap)
or the exec ended without a status; errorCode then says why
(SANDBOX_RUNNER_UNAVAILABLE, SANDBOX_STREAM_ENDED, ...). Refusals throw
ApiError with the API's code: SANDBOX_PLAN_REQUIRED (402: sandboxes are on
the Pro and Enterprise plans; error.details.requiredPlans names them),
SANDBOX_QUOTA_EXCEEDED, SANDBOX_NOT_RUNNING,
SANDBOX_SCOPE_REQUIRED (a workspace API key needs the explicit
sandboxes:write scope; personal tokens from inquir login work as they are),
SANDBOX_CAPACITY_UNAVAILABLE, and the rest listed in the API reference.
SANDBOX_SIZES holds the S/M/L presets of the CLI and the dashboard. Never put
secrets, API keys or .env files into a sandbox, and destroy every sandbox you
create; idle ones end on their own after the idle timeout (30 minutes by default).
Readonly published-release commands (scoped rollout)
prepareReleaseCommand retains the caller's original UUID, workspace and command
before the first HTTP submission. It uses the dedicated readonly release API;
it does not invoke the writable source-command API or a function handler.
import { randomUUID } from 'node:crypto';
import { prepareReleaseCommand, restoreReleaseCommand } from '@inquir/compute';
const operation = await prepareReleaseCommand(client, {
functionId,
requestId: randomUUID(),
input: { command: 'cat package.json', timeoutMs: 60_000 },
retain: async record => saveCommandRecord(record), // Durable caller storage.
});
const first = await operation.submit(); // Submit once. Keep the retained record on a lost reply.
const outcome = first.state === 'PENDING' || first.state === 'RECOVERY_HELD'
? await restoreReleaseCommand(client, operation.record()).observe()
: first;Observation resumes the same ID and never repeats the initial POST. An expired
or aborted observer keeps that handle; operation.cancel() separately requests
durable cancellation. Cancellation acknowledgement is an intent, while REMOVED
is a validated terminal result after physical task/container cleanup. Scope or
artifact uncertainty remains held rather than becoming a fabricated failure.
CANCELLED_WITHOUT_CONTAINER separately proves an admitted reservation was
cancelled and physically retired before CREATE; its result is null because
no shell ran. CANCELLED_BEFORE_ADMISSION has no reservation to retire.
This path is disabled by default. Each exact runtime image, readonly process, source/input mount, resource and network profile must receive native qualification before its scoped operator approval and rollout switches enable admission. The initial source tests do not constitute that qualification.
Application observability
The SDK exposes resource and HTTP history, persisted runtime/HTTP logs and configurable app alerts. Every helper uses the client's credentials and workspace selector:
import {
createClient, getAppMetrics, getAppHttpMetrics, getAppLogHistory,
createAppAlertRule, updateAppAlertRule, listAppAlertIncidents,
} from '@inquir/compute';
const client = createClient({
baseUrl: 'https://inquir.org/api',
apiKey: process.env.INQUIR_TOKEN,
workspaceId: process.env.INQUIR_WORKSPACE,
});
const to = new Date().toISOString();
const from = new Date(Date.now() - 60 * 60 * 1000).toISOString();
const resources = await getAppMetrics(client, appId, { from, to });
const http = await getAppHttpMetrics(client, appId, { from, to });
const logs = await getAppLogHistory(client, appId, {
from, to, releaseId, allocationId, allocationFence: 4, level: 'error', limit: 100,
});
if (logs.nextCursor) {
const older = await getAppLogHistory(client, appId, {
from: logs.from, to: logs.to, releaseId, allocationId, allocationFence: 4,
level: 'error', limit: 100, cursor: logs.nextCursor,
});
}
const { rule } = await createAppAlertRule(client, appId, {
name: 'High RAM', enabled: true, metric: 'memory_percent',
threshold: 85, forSeconds: 120, recoveryThreshold: 65,
recoveryForSeconds: 60, noDataSeconds: 180, noData: 'alert', channels: [],
});
await updateAppAlertRule(client, appId, rule.id, { threshold: 90 });
const { incidents } = await listAppAlertIncidents(client, appId, { limit: 25 });getAppHttpLogHistory, listAppAlertRules and deleteAppAlertRule complete the API. Deletion disables the rule and resolves its active incidents; retained history is still available. Omit channels in a patch to preserve existing destinations, or pass an empty array to remove them. webhook/slack channel URLs are write-only; response types expose only channel id, type and configured status. Never log alert request inputs containing a secret URL.
Resource and HTTP retention is 30 days; runtime logs are retained for 7 days. Runtime history is attributed to the exact release, allocation/fence, runner/epoch and container, including replaced containers. Paging is newest-first and requires an unchanged date window and filters. Resource history retains unavailable values as null; use status, latestSampleAt and truncated to detect stale or incomplete results. Network and block I/O rates are measured separately; block I/O is not volume space usage. CPU/RAM alert percentages are relative to enforced limits, and the continuous maximum across current production replicas determines threshold firing.
