unfazed 0.9.0 → 0.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +46 -0
- package/README.md +59 -2
- package/REFERENCE.md +2 -2
- package/dist/cli/eve-sandbox.d.ts +3 -0
- package/dist/cli/eve-sandbox.js +268 -0
- package/dist/cli/eve-sandbox.js.map +1 -0
- package/dist/cli/login.d.ts +1 -1
- package/dist/cli.js +11 -0
- package/dist/cli.js.map +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/client.js +1 -1
- package/dist/client.js.map +1 -1
- package/dist/eve-sandbox/daemon.d.ts +65 -0
- package/dist/eve-sandbox/daemon.js +687 -0
- package/dist/eve-sandbox/daemon.js.map +1 -0
- package/dist/eve-sandbox/index.d.ts +82 -0
- package/dist/eve-sandbox/index.js +368 -0
- package/dist/eve-sandbox/index.js.map +1 -0
- package/dist/eve-sandbox/protocol.d.ts +68 -0
- package/dist/eve-sandbox/protocol.js +22 -0
- package/dist/eve-sandbox/protocol.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/oidc.d.ts +3 -3
- package/dist/oidc.js +3 -3
- package/dist/oidc.js.map +1 -1
- package/dist/reference.generated.js +1 -1
- package/dist/reference.generated.js.map +1 -1
- package/package.json +14 -4
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,eAAe,EAAoB,MAAM,kBAAkB,CAAC;AACpF,OAAO,EACL,gBAAgB,EAChB,kBAAkB,EAClB,mBAAmB,EACnB,gBAAgB,EAChB,mBAAmB,GAEpB,MAAM,aAAa,CAAC;AAErB,2EAA2E;AAC3E,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAC;AAE/B;;;;;;;GAOG;AACH,MAAM,CAA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,KAAK,KAAK,SAAS;gBAAE,YAAY,CAAC,KAAK,CAAC,CAAC;YAC7C,QAAQ,EAAE,mBAAmB,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;QAC1D,CAAC;QACD,UAAU,EAAE,GAAG,EAAE,CAAC,QAAQ;KAC3B,CAAC;AACJ,CAAC","sourcesContent":["import { LOGIN_COMMAND, openStoredLogin, type StoredLogin } from \"./credentials.js\";\nimport {\n UnfazedAuthError,\n UnfazedConfigError,\n UnfazedGraphQLError,\n UnfazedHTTPError,\n UnfazedTimeoutError,\n type GraphQLResponseError,\n} from \"./errors.js\";\n\n/** SDK version, sent as the User-Agent. Keep in sync with package.json. */\nexport const VERSION = \"0.9.0\";\n\n/**\n * Default GraphQL endpoint.\n *\n * Note this is the FULL endpoint, not an origin: the platform's own documented\n * convention (`UNFZ_API_URL=\"https://unfazed.dev/query\"`, and cmd/showcase-deploy\n * in the unfazed repo) treats the /query URL as the configurable unit, so the\n * SDK matches it rather than inventing a base-URL convention.\n */\nexport const DEFAULT_ENDPOINT = \"https://unfazed.dev/query\";\n\n/** Platform origin, used to derive the endpoint when only `baseUrl` is given. */\nexport const DEFAULT_BASE_URL = \"https://unfazed.dev\";\n\n/** Path of the GraphQL endpoint under an origin. */\nexport const GRAPHQL_PATH = \"/query\";\n\n/**\n * Environment variable holding the bearer token.\n *\n * This is the platform's documented name (docs/agent-deployments.md,\n * internal/agentdocs/reference.md). It accepts either an operator API token or\n * an agent access token from POST /agents/register — /query takes both as\n * plain bearers.\n */\nexport const TOKEN_ENV_VAR = \"UNFZ_API_TOKEN\";\n\n/** Environment variable holding the full GraphQL endpoint URL. */\nexport const ENDPOINT_ENV_VAR = \"UNFZ_API_URL\";\n\n/** Minimal structural type of the `fetch` the transport needs. */\nexport type FetchLike = (\n input: string,\n init: {\n method: string;\n headers: Record<string, string>;\n body: string;\n signal?: AbortSignal;\n },\n) => Promise<{\n ok: boolean;\n status: number;\n text(): Promise<string>;\n}>;\n\nexport interface ClientOptions {\n /**\n * Bearer token. Falls back to `UNFZ_API_TOKEN`, then to the login\n * `npx unfazed login` stored (see {@link ClientOptions.login}). An agent gets\n * one from https://unfazed.dev/auth.md — the same token the MCP server uses.\n */\n token?: string;\n /**\n * Use the stored login of `npx unfazed login`\n * (`${XDG_CONFIG_HOME:-~/.config}/unfazed/credentials.json`) when no token\n * is passed and `UNFZ_API_TOKEN` is unset. Its access token is refreshed\n * before it expires and when the platform refuses it. Default `true`; it is\n * only used for the endpoint it was issued by, and is the endpoint when none\n * is configured.\n */\n login?: boolean;\n /**\n * Where `UNFZ_API_TOKEN`, `UNFZ_API_URL` and the stored login's location\n * (`XDG_CONFIG_HOME`, `HOME`) are read from. Default: `process.env`.\n */\n env?: Record<string, string | undefined>;\n /**\n * Full GraphQL endpoint URL. Wins over `baseUrl`. Falls back to\n * `UNFZ_API_URL`, then the stored login's endpoint, then\n * {@link DEFAULT_ENDPOINT}.\n */\n endpoint?: string;\n /**\n * Platform origin; `/query` is appended. Convenience for self-hosted or\n * staging control planes where only the host differs.\n */\n baseUrl?: string;\n /** Extra headers merged into every request. Authorization always wins. */\n headers?: Record<string, string>;\n /**\n * Per-request timeout in ms. Default 60_000. Pass 0 to disable.\n *\n * Bounds the WHOLE request — connect, headers and reading the response body —\n * so a proxy that answers with headers and then stalls still fails on time.\n */\n timeoutMs?: number;\n /** Injection point for tests and instrumented/proxied transports. */\n fetch?: FetchLike;\n /** Overrides the default `unfazed-sdk/<version>` User-Agent. */\n userAgent?: string;\n}\n\n/**\n * A GraphQL document.\n *\n * Structural rather than `string & {...}` on purpose: graphql-codegen emits\n * `TypedDocumentString`, a String SUBCLASS, which is not assignable to the\n * primitive `string`. Requiring only `toString()` plus the optional phantom\n * `__apiType` lets three things through with full inference:\n *\n * - generated `TypedDocumentString` documents (types inferred),\n * - documents assembled at runtime, like the batched writeFiles mutation,\n * - plain template-literal strings a caller wrote by hand.\n */\nexport interface GraphQLDocument<TResult, TVariables> {\n /** Phantom type carrier. Never called; present only to bind the generics. */\n __apiType?: (variables: TVariables) => TResult;\n toString(): string;\n}\n\n/** Result type carried by a typed document. */\nexport type ResultOf<T> = T extends GraphQLDocument<infer R, infer _V> ? R : unknown;\n\n/** Variables type carried by a typed document. */\nexport type VariablesOf<T> = T extends GraphQLDocument<infer _R, infer V> ? V : never;\n\n/** Per-request knobs. */\nexport interface RequestOptions {\n signal?: AbortSignal;\n timeoutMs?: number;\n operationName?: string;\n}\n\n/**\n * Layer 1 — a typed, dependency-free GraphQL transport over `fetch`.\n *\n * This is the SDK's entire networking surface. It understands auth, timeouts\n * and the GraphQL error envelope, and nothing about deployments. The workflow\n * layer ({@link import(\"./unfazed.js\").Unfazed}) is built strictly on top of\n * it, so you can always drop down here for any operation the workflow layer\n * does not wrap — the schema has ~660 fields and the workflow layer\n * deliberately covers only the agent-facing ones.\n *\n * ```ts\n * const client = new UnfazedClient(); // UNFZ_API_TOKEN, else `npx unfazed login`\n * const data = await client.query<{ whoami: { name: string } }, never>(\n * `query { whoami { name } }`,\n * );\n * ```\n */\nexport class UnfazedClient {\n /** Resolved GraphQL endpoint URL. */\n readonly endpoint: string;\n\n /** A fixed bearer token, or the stored login handing out refreshed ones. */\n readonly #auth: { token: string } | { login: StoredLogin };\n readonly #headers: Record<string, string>;\n readonly #timeoutMs: number;\n readonly #fetch: FetchLike;\n\n constructor(options: ClientOptions = {}) {\n const env = options.env ?? processEnv();\n\n const injected = options.fetch;\n if (injected) {\n this.#fetch = injected;\n } else {\n const globalFetch = (globalThis as { fetch?: unknown }).fetch;\n if (typeof globalFetch !== \"function\") {\n throw new UnfazedConfigError(\n \"unfazed: no global fetch. Use Bun, Node >= 20, or pass { fetch } to the client.\",\n );\n }\n this.#fetch = globalFetch.bind(globalThis) as FetchLike;\n }\n\n const ua = options.userAgent ?? `unfazed-sdk/${VERSION}`;\n\n const configured = configuredEndpoint(options, env);\n const token = options.token ?? env[TOKEN_ENV_VAR];\n if (token?.trim()) {\n this.#auth = { token: token.trim() };\n this.endpoint = configured ?? DEFAULT_ENDPOINT;\n } else {\n const stored =\n options.login === false\n ? {}\n : openStoredLogin({\n env,\n ...(configured ? { endpoint: configured } : {}),\n fetch: this.#fetch,\n // The edge refuses some generic agents; always name ourselves.\n userAgent: ua || `unfazed-sdk/${VERSION}`,\n });\n if (!stored.login) {\n throw new UnfazedAuthError(noTokenMessage(configured, stored.other?.endpoint));\n }\n this.#auth = { login: stored.login };\n this.endpoint = stored.login.endpoint;\n }\n\n this.#headers = { ...(options.headers ?? {}) };\n this.#timeoutMs = options.timeoutMs ?? 60_000;\n if (ua) this.#headers[\"User-Agent\"] = ua;\n }\n\n /**\n * Where the bearer token comes from: `\"token\"` (passed or\n * `UNFZ_API_TOKEN`) or `\"login\"` (the stored login of `npx unfazed login`).\n */\n get authSource(): \"token\" | \"login\" {\n return \"login\" in this.#auth ? \"login\" : \"token\";\n }\n\n /** Runs a query document. Identical wire behaviour to {@link mutate}. */\n query<TResult, TVariables>(\n document: GraphQLDocument<TResult, TVariables>,\n variables?: TVariables,\n options?: RequestOptions,\n ): Promise<TResult> {\n return this.request(document, variables, options);\n }\n\n /**\n * Runs a mutation document. Distinct from {@link query} for call-site\n * readability only — GraphQL over HTTP POST makes no distinction.\n */\n mutate<TResult, TVariables>(\n document: GraphQLDocument<TResult, TVariables>,\n variables?: TVariables,\n options?: RequestOptions,\n ): Promise<TResult> {\n return this.request(document, variables, options);\n }\n\n /**\n * The single code path behind {@link query} and {@link mutate}.\n *\n * Throws {@link UnfazedHTTPError} on non-2xx, {@link UnfazedGraphQLError}\n * when the body carries `errors`, {@link UnfazedTimeoutError} on timeout or\n * abort. Resolves to the `data` object on success.\n */\n async request<TResult = unknown>(\n document: string | { toString(): string },\n variables?: unknown,\n options: RequestOptions = {},\n ): Promise<TResult> {\n const timeoutMs = options.timeoutMs ?? this.#timeoutMs;\n\n // `document` may be a TypedDocumentString (a String object). JSON.stringify\n // would serialise that fine, but String(...) keeps the wire body a plain\n // primitive regardless of how the caller obtained the document.\n const body = JSON.stringify({\n query: String(document),\n ...(variables === undefined ? {} : { variables }),\n ...(options.operationName ? { operationName: options.operationName } : {}),\n });\n\n let token = await this.#token();\n let { response, text } = await this.#send(body, token, timeoutMs, options.signal);\n // A stored login's access token can be refused before its recorded\n // expiry (the clock, a sign-out elsewhere): refresh once and retry. A\n // fixed token has nothing to refresh.\n if (response.status === 401 && \"login\" in this.#auth) {\n token = await this.#auth.login.refresh(token);\n ({ response, text } = await this.#send(body, token, timeoutMs, options.signal));\n }\n\n if (!response.ok) {\n throw new UnfazedHTTPError(response.status, text, this.endpoint);\n }\n\n let parsed: { data?: TResult; errors?: GraphQLResponseError[] };\n try {\n parsed = JSON.parse(text) as typeof parsed;\n } catch {\n throw new UnfazedHTTPError(response.status, text, this.endpoint);\n }\n\n // A GraphQL 200 can still be a failure, and can be a PARTIAL failure: the\n // batched writeFiles document resolves each aliased field independently.\n // Attaching `data` to the error is what lets a caller see which writes\n // landed before the failing one.\n if (parsed.errors?.length) {\n throw new UnfazedGraphQLError(parsed.errors, parsed.data);\n }\n if (parsed.data === undefined || parsed.data === null) {\n throw new UnfazedGraphQLError(\n [{ message: \"response contained neither data nor errors\" }],\n undefined,\n );\n }\n return parsed.data;\n }\n\n #token(): Promise<string> {\n return \"login\" in this.#auth ? this.#auth.login.token() : Promise.resolve(this.#auth.token);\n }\n\n async #send(\n body: string,\n token: string,\n timeoutMs: number,\n external: AbortSignal | undefined,\n ): Promise<{ response: Awaited<ReturnType<FetchLike>>; text: string }> {\n const { signal, cleanup, didTimeout } = makeSignal(timeoutMs, external);\n // The deadline covers BOTH phases — headers AND body. A proxy that answers\n // with headers and then stalls the body is a real failure mode, and\n // stopping the clock at the end of `fetch()` would leave `response.text()`\n // hanging forever. `untilAborted` additionally races the signal itself, so\n // an injected transport that ignores `signal` still cannot outlive the\n // timeout.\n try {\n const response = await untilAborted(\n this.#fetch(this.endpoint, {\n method: \"POST\",\n headers: {\n ...this.#headers,\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n Authorization: `Bearer ${token}`,\n },\n body,\n ...(signal ? { signal } : {}),\n }),\n signal,\n );\n const text = await untilAborted(response.text(), signal);\n return { response, text };\n } catch (cause) {\n if (didTimeout()) {\n throw new UnfazedTimeoutError(`unfazed: request timed out after ${timeoutMs}ms`, { cause });\n }\n if (isAbort(cause)) {\n throw new UnfazedTimeoutError(\"unfazed: request aborted\", { cause });\n }\n throw cause;\n } finally {\n cleanup();\n }\n }\n}\n\n/**\n * The platform origin an endpoint is served from:\n * `https://unfazed.dev/query` → `https://unfazed.dev`. A path before `/query`\n * (a control plane mounted under a prefix) is kept.\n */\nexport function platformBaseUrl(endpoint: string): string {\n return trimSlash(endpoint).replace(/\\/(?:query|graphql)$/, \"\");\n}\n\n/** The endpoint the options or `UNFZ_API_URL` name, or undefined for the default. */\nexport function configuredEndpoint(\n options: Pick<ClientOptions, \"endpoint\" | \"baseUrl\">,\n env: Record<string, string | undefined>,\n): string | undefined {\n if (options.endpoint) return options.endpoint;\n if (options.baseUrl) return trimSlash(options.baseUrl) + GRAPHQL_PATH;\n const fromEnv = env[ENDPOINT_ENV_VAR];\n // UNFZ_API_URL is documented as the full /query URL and is used verbatim.\n // Tolerate a bare origin anyway, since that is the obvious mistake and\n // guessing right costs nothing.\n if (fromEnv) {\n const trimmed = trimSlash(fromEnv);\n return /\\/query$|\\/graphql$/.test(trimmed) ? trimmed : trimmed + GRAPHQL_PATH;\n }\n return undefined;\n}\n\nfunction noTokenMessage(endpoint: string | undefined, otherLogin: string | undefined): string {\n if (endpoint && otherLogin) {\n return (\n `unfazed: no API token for ${endpoint}: the stored login is for ${otherLogin}. ` +\n `Run \\`${ENDPOINT_ENV_VAR}=${endpoint} ${LOGIN_COMMAND}\\`, or pass { token } / set ${TOKEN_ENV_VAR}.`\n );\n }\n return (\n `unfazed: not signed in. Run \\`${LOGIN_COMMAND}\\` to sign in with your account, ` +\n `or pass { token } / set ${TOKEN_ENV_VAR} (an agent token: ${DEFAULT_BASE_URL}/auth.md).`\n );\n}\n\nexport function processEnv(): Record<string, string | undefined> {\n // Guarded: the SDK must also work in a browser or worker, where there is no\n // `process` at all.\n return (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};\n}\n\nfunction trimSlash(u: string): string {\n return u.replace(/\\/+$/, \"\");\n}\n\nfunction isAbort(e: unknown): boolean {\n return typeof e === \"object\" && e !== null && (e as { name?: string }).name === \"AbortError\";\n}\n\nfunction abortError(): Error {\n const e = new Error(\"The operation was aborted.\");\n e.name = \"AbortError\";\n return e;\n}\n\n/**\n * Settles with `promise`, or rejects the moment `signal` aborts.\n *\n * A global `fetch` honours the signal for headers and body alike, but an\n * injected {@link FetchLike} — a proxy, an instrumented transport, a test\n * double — need not. Racing the signal makes the timeout an upper bound on the\n * whole request regardless of what the transport does with it. The loser's\n * rejection is swallowed by the already-settled promise rather than surfacing\n * as an unhandled rejection.\n */\nexport function untilAborted<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {\n if (!signal) return promise;\n if (signal.aborted) return Promise.reject(abortError());\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(abortError());\n signal.addEventListener(\"abort\", onAbort, { once: true });\n const done = () => signal.removeEventListener(\"abort\", onAbort);\n promise.then(\n (value) => {\n done();\n resolve(value);\n },\n (error: unknown) => {\n done();\n reject(error as Error);\n },\n );\n });\n}\n\n/**\n * Combines the request timeout with any caller-supplied signal.\n *\n * `didTimeout` is tracked separately from the abort so a caller's own\n * cancellation is not mislabelled as a timeout in the thrown message.\n */\nfunction makeSignal(\n timeoutMs: number,\n external?: AbortSignal,\n): { signal?: AbortSignal; cleanup: () => void; didTimeout: () => boolean } {\n if (!timeoutMs && !external) return { cleanup: () => {}, didTimeout: () => false };\n if (typeof AbortController !== \"function\") {\n return {\n ...(external ? { signal: external } : {}),\n cleanup: () => {},\n didTimeout: () => false,\n };\n }\n\n const controller = new AbortController();\n let timedOut = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n if (timeoutMs > 0) {\n timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeoutMs);\n }\n\n const onExternalAbort = () => controller.abort();\n if (external) {\n if (external.aborted) controller.abort();\n else external.addEventListener(\"abort\", onExternalAbort, { once: true });\n }\n\n return {\n signal: controller.signal,\n cleanup: () => {\n if (timer !== undefined) clearTimeout(timer);\n external?.removeEventListener(\"abort\", onExternalAbort);\n },\n didTimeout: () => timedOut,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,eAAe,EAAoB,MAAM,kBAAkB,CAAC;AACpF,OAAO,EACL,gBAAgB,EAChB,kBAAkB,EAClB,mBAAmB,EACnB,gBAAgB,EAChB,mBAAmB,GAEpB,MAAM,aAAa,CAAC;AAErB,2EAA2E;AAC3E,MAAM,CAAC,MAAM,OAAO,GAAG,QAAQ,CAAC;AAEhC;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,2BAA2B,CAAC;AAE5D,iFAAiF;AACjF,MAAM,CAAC,MAAM,gBAAgB,GAAG,qBAAqB,CAAC;AAEtD,oDAAoD;AACpD,MAAM,CAAC,MAAM,YAAY,GAAG,QAAQ,CAAC;AAErC;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,gBAAgB,CAAC;AAE9C,kEAAkE;AAClE,MAAM,CAAC,MAAM,gBAAgB,GAAG,cAAc,CAAC;AA+F/C;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,OAAO,aAAa;IACxB,qCAAqC;IAC5B,QAAQ,CAAS;IAE1B,4EAA4E;IACnE,KAAK,CAA6C;IAClD,QAAQ,CAAyB;IACjC,UAAU,CAAS;IACnB,MAAM,CAAY;IAE3B,YAAY,UAAyB,EAAE;QACrC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,IAAI,UAAU,EAAE,CAAC;QAExC,MAAM,QAA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AC;IACzC,IAAI,QAAQ,GAAG,KAAK,CAAC;IACrB,IAAI,KAAgD,CAAC;IAErD,IAAI,SAAS,GAAG,CAAC,EAAE,CAAC;QAClB,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;YACtB,QAAQ,GAAG,IAAI,CAAC;YAChB,UAAU,CAAC,KAAK,EAAE,CAAC;QACrB,CAAC,EAAE,SAAS,CAAC,CAAC;IAChB,CAAC;IAED,MAAM,eAAe,GAAG,GAAG,EAAE,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;IACjD,IAAI,QAAQ,EAAE,CAAC;QACb,IAAI,QAAQ,CAAC,OAAO;YAAE,UAAU,CAAC,KAAK,EAAE,CAAC;;YACpC,QAAQ,CAAC,gBAAgB,CAAC,OAAO,EAAE,eAAe,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;IAC3E,CAAC;IAED,OAAO;QACL,MAAM,EAAE,UAAU,CAAC,MAAM;QACzB,OAAO,EAAE,GAAG,EAAE;YACZ,IAAI,KAAK,KAAK,SAAS;gBAAE,YAAY,CAAC,KAAK,CAAC,CAAC;YAC7C,QAAQ,EAAE,mBAAmB,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;QAC1D,CAAC;QACD,UAAU,EAAE,GAAG,EAAE,CAAC,QAAQ;KAC3B,CAAC;AACJ,CAAC","sourcesContent":["import { LOGIN_COMMAND, openStoredLogin, type StoredLogin } from \"./credentials.js\";\nimport {\n UnfazedAuthError,\n UnfazedConfigError,\n UnfazedGraphQLError,\n UnfazedHTTPError,\n UnfazedTimeoutError,\n type GraphQLResponseError,\n} from \"./errors.js\";\n\n/** SDK version, sent as the User-Agent. Keep in sync with package.json. */\nexport const VERSION = \"0.10.1\";\n\n/**\n * Default GraphQL endpoint.\n *\n * Note this is the FULL endpoint, not an origin: the platform's own documented\n * convention (`UNFZ_API_URL=\"https://unfazed.dev/query\"`, and cmd/showcase-deploy\n * in the unfazed repo) treats the /query URL as the configurable unit, so the\n * SDK matches it rather than inventing a base-URL convention.\n */\nexport const DEFAULT_ENDPOINT = \"https://unfazed.dev/query\";\n\n/** Platform origin, used to derive the endpoint when only `baseUrl` is given. */\nexport const DEFAULT_BASE_URL = \"https://unfazed.dev\";\n\n/** Path of the GraphQL endpoint under an origin. */\nexport const GRAPHQL_PATH = \"/query\";\n\n/**\n * Environment variable holding the bearer token.\n *\n * This is the platform's documented name (docs/agent-deployments.md,\n * internal/agentdocs/reference.md). It accepts either an operator API token or\n * an agent access token from POST /agents/register — /query takes both as\n * plain bearers.\n */\nexport const TOKEN_ENV_VAR = \"UNFZ_API_TOKEN\";\n\n/** Environment variable holding the full GraphQL endpoint URL. */\nexport const ENDPOINT_ENV_VAR = \"UNFZ_API_URL\";\n\n/** Minimal structural type of the `fetch` the transport needs. */\nexport type FetchLike = (\n input: string,\n init: {\n method: string;\n headers: Record<string, string>;\n body: string;\n signal?: AbortSignal;\n },\n) => Promise<{\n ok: boolean;\n status: number;\n text(): Promise<string>;\n}>;\n\nexport interface ClientOptions {\n /**\n * Bearer token. Falls back to `UNFZ_API_TOKEN`, then to the login\n * `npx unfazed login` stored (see {@link ClientOptions.login}). An agent gets\n * one from https://unfazed.dev/auth.md — the same token the MCP server uses.\n */\n token?: string;\n /**\n * Use the stored login of `npx unfazed login`\n * (`${XDG_CONFIG_HOME:-~/.config}/unfazed/credentials.json`) when no token\n * is passed and `UNFZ_API_TOKEN` is unset. Its access token is refreshed\n * before it expires and when the platform refuses it. Default `true`; it is\n * only used for the endpoint it was issued by, and is the endpoint when none\n * is configured.\n */\n login?: boolean;\n /**\n * Where `UNFZ_API_TOKEN`, `UNFZ_API_URL` and the stored login's location\n * (`XDG_CONFIG_HOME`, `HOME`) are read from. Default: `process.env`.\n */\n env?: Record<string, string | undefined>;\n /**\n * Full GraphQL endpoint URL. Wins over `baseUrl`. Falls back to\n * `UNFZ_API_URL`, then the stored login's endpoint, then\n * {@link DEFAULT_ENDPOINT}.\n */\n endpoint?: string;\n /**\n * Platform origin; `/query` is appended. Convenience for self-hosted or\n * staging control planes where only the host differs.\n */\n baseUrl?: string;\n /** Extra headers merged into every request. Authorization always wins. */\n headers?: Record<string, string>;\n /**\n * Per-request timeout in ms. Default 60_000. Pass 0 to disable.\n *\n * Bounds the WHOLE request — connect, headers and reading the response body —\n * so a proxy that answers with headers and then stalls still fails on time.\n */\n timeoutMs?: number;\n /** Injection point for tests and instrumented/proxied transports. */\n fetch?: FetchLike;\n /** Overrides the default `unfazed-sdk/<version>` User-Agent. */\n userAgent?: string;\n}\n\n/**\n * A GraphQL document.\n *\n * Structural rather than `string & {...}` on purpose: graphql-codegen emits\n * `TypedDocumentString`, a String SUBCLASS, which is not assignable to the\n * primitive `string`. Requiring only `toString()` plus the optional phantom\n * `__apiType` lets three things through with full inference:\n *\n * - generated `TypedDocumentString` documents (types inferred),\n * - documents assembled at runtime, like the batched writeFiles mutation,\n * - plain template-literal strings a caller wrote by hand.\n */\nexport interface GraphQLDocument<TResult, TVariables> {\n /** Phantom type carrier. Never called; present only to bind the generics. */\n __apiType?: (variables: TVariables) => TResult;\n toString(): string;\n}\n\n/** Result type carried by a typed document. */\nexport type ResultOf<T> = T extends GraphQLDocument<infer R, infer _V> ? R : unknown;\n\n/** Variables type carried by a typed document. */\nexport type VariablesOf<T> = T extends GraphQLDocument<infer _R, infer V> ? V : never;\n\n/** Per-request knobs. */\nexport interface RequestOptions {\n signal?: AbortSignal;\n timeoutMs?: number;\n operationName?: string;\n}\n\n/**\n * Layer 1 — a typed, dependency-free GraphQL transport over `fetch`.\n *\n * This is the SDK's entire networking surface. It understands auth, timeouts\n * and the GraphQL error envelope, and nothing about deployments. The workflow\n * layer ({@link import(\"./unfazed.js\").Unfazed}) is built strictly on top of\n * it, so you can always drop down here for any operation the workflow layer\n * does not wrap — the schema has ~660 fields and the workflow layer\n * deliberately covers only the agent-facing ones.\n *\n * ```ts\n * const client = new UnfazedClient(); // UNFZ_API_TOKEN, else `npx unfazed login`\n * const data = await client.query<{ whoami: { name: string } }, never>(\n * `query { whoami { name } }`,\n * );\n * ```\n */\nexport class UnfazedClient {\n /** Resolved GraphQL endpoint URL. */\n readonly endpoint: string;\n\n /** A fixed bearer token, or the stored login handing out refreshed ones. */\n readonly #auth: { token: string } | { login: StoredLogin };\n readonly #headers: Record<string, string>;\n readonly #timeoutMs: number;\n readonly #fetch: FetchLike;\n\n constructor(options: ClientOptions = {}) {\n const env = options.env ?? processEnv();\n\n const injected = options.fetch;\n if (injected) {\n this.#fetch = injected;\n } else {\n const globalFetch = (globalThis as { fetch?: unknown }).fetch;\n if (typeof globalFetch !== \"function\") {\n throw new UnfazedConfigError(\n \"unfazed: no global fetch. Use Bun, Node >= 20, or pass { fetch } to the client.\",\n );\n }\n this.#fetch = globalFetch.bind(globalThis) as FetchLike;\n }\n\n const ua = options.userAgent ?? `unfazed-sdk/${VERSION}`;\n\n const configured = configuredEndpoint(options, env);\n const token = options.token ?? env[TOKEN_ENV_VAR];\n if (token?.trim()) {\n this.#auth = { token: token.trim() };\n this.endpoint = configured ?? DEFAULT_ENDPOINT;\n } else {\n const stored =\n options.login === false\n ? {}\n : openStoredLogin({\n env,\n ...(configured ? { endpoint: configured } : {}),\n fetch: this.#fetch,\n // The edge refuses some generic agents; always name ourselves.\n userAgent: ua || `unfazed-sdk/${VERSION}`,\n });\n if (!stored.login) {\n throw new UnfazedAuthError(noTokenMessage(configured, stored.other?.endpoint));\n }\n this.#auth = { login: stored.login };\n this.endpoint = stored.login.endpoint;\n }\n\n this.#headers = { ...(options.headers ?? {}) };\n this.#timeoutMs = options.timeoutMs ?? 60_000;\n if (ua) this.#headers[\"User-Agent\"] = ua;\n }\n\n /**\n * Where the bearer token comes from: `\"token\"` (passed or\n * `UNFZ_API_TOKEN`) or `\"login\"` (the stored login of `npx unfazed login`).\n */\n get authSource(): \"token\" | \"login\" {\n return \"login\" in this.#auth ? \"login\" : \"token\";\n }\n\n /** Runs a query document. Identical wire behaviour to {@link mutate}. */\n query<TResult, TVariables>(\n document: GraphQLDocument<TResult, TVariables>,\n variables?: TVariables,\n options?: RequestOptions,\n ): Promise<TResult> {\n return this.request(document, variables, options);\n }\n\n /**\n * Runs a mutation document. Distinct from {@link query} for call-site\n * readability only — GraphQL over HTTP POST makes no distinction.\n */\n mutate<TResult, TVariables>(\n document: GraphQLDocument<TResult, TVariables>,\n variables?: TVariables,\n options?: RequestOptions,\n ): Promise<TResult> {\n return this.request(document, variables, options);\n }\n\n /**\n * The single code path behind {@link query} and {@link mutate}.\n *\n * Throws {@link UnfazedHTTPError} on non-2xx, {@link UnfazedGraphQLError}\n * when the body carries `errors`, {@link UnfazedTimeoutError} on timeout or\n * abort. Resolves to the `data` object on success.\n */\n async request<TResult = unknown>(\n document: string | { toString(): string },\n variables?: unknown,\n options: RequestOptions = {},\n ): Promise<TResult> {\n const timeoutMs = options.timeoutMs ?? this.#timeoutMs;\n\n // `document` may be a TypedDocumentString (a String object). JSON.stringify\n // would serialise that fine, but String(...) keeps the wire body a plain\n // primitive regardless of how the caller obtained the document.\n const body = JSON.stringify({\n query: String(document),\n ...(variables === undefined ? {} : { variables }),\n ...(options.operationName ? { operationName: options.operationName } : {}),\n });\n\n let token = await this.#token();\n let { response, text } = await this.#send(body, token, timeoutMs, options.signal);\n // A stored login's access token can be refused before its recorded\n // expiry (the clock, a sign-out elsewhere): refresh once and retry. A\n // fixed token has nothing to refresh.\n if (response.status === 401 && \"login\" in this.#auth) {\n token = await this.#auth.login.refresh(token);\n ({ response, text } = await this.#send(body, token, timeoutMs, options.signal));\n }\n\n if (!response.ok) {\n throw new UnfazedHTTPError(response.status, text, this.endpoint);\n }\n\n let parsed: { data?: TResult; errors?: GraphQLResponseError[] };\n try {\n parsed = JSON.parse(text) as typeof parsed;\n } catch {\n throw new UnfazedHTTPError(response.status, text, this.endpoint);\n }\n\n // A GraphQL 200 can still be a failure, and can be a PARTIAL failure: the\n // batched writeFiles document resolves each aliased field independently.\n // Attaching `data` to the error is what lets a caller see which writes\n // landed before the failing one.\n if (parsed.errors?.length) {\n throw new UnfazedGraphQLError(parsed.errors, parsed.data);\n }\n if (parsed.data === undefined || parsed.data === null) {\n throw new UnfazedGraphQLError(\n [{ message: \"response contained neither data nor errors\" }],\n undefined,\n );\n }\n return parsed.data;\n }\n\n #token(): Promise<string> {\n return \"login\" in this.#auth ? this.#auth.login.token() : Promise.resolve(this.#auth.token);\n }\n\n async #send(\n body: string,\n token: string,\n timeoutMs: number,\n external: AbortSignal | undefined,\n ): Promise<{ response: Awaited<ReturnType<FetchLike>>; text: string }> {\n const { signal, cleanup, didTimeout } = makeSignal(timeoutMs, external);\n // The deadline covers BOTH phases — headers AND body. A proxy that answers\n // with headers and then stalls the body is a real failure mode, and\n // stopping the clock at the end of `fetch()` would leave `response.text()`\n // hanging forever. `untilAborted` additionally races the signal itself, so\n // an injected transport that ignores `signal` still cannot outlive the\n // timeout.\n try {\n const response = await untilAborted(\n this.#fetch(this.endpoint, {\n method: \"POST\",\n headers: {\n ...this.#headers,\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n Authorization: `Bearer ${token}`,\n },\n body,\n ...(signal ? { signal } : {}),\n }),\n signal,\n );\n const text = await untilAborted(response.text(), signal);\n return { response, text };\n } catch (cause) {\n if (didTimeout()) {\n throw new UnfazedTimeoutError(`unfazed: request timed out after ${timeoutMs}ms`, { cause });\n }\n if (isAbort(cause)) {\n throw new UnfazedTimeoutError(\"unfazed: request aborted\", { cause });\n }\n throw cause;\n } finally {\n cleanup();\n }\n }\n}\n\n/**\n * The platform origin an endpoint is served from:\n * `https://unfazed.dev/query` → `https://unfazed.dev`. A path before `/query`\n * (a control plane mounted under a prefix) is kept.\n */\nexport function platformBaseUrl(endpoint: string): string {\n return trimSlash(endpoint).replace(/\\/(?:query|graphql)$/, \"\");\n}\n\n/** The endpoint the options or `UNFZ_API_URL` name, or undefined for the default. */\nexport function configuredEndpoint(\n options: Pick<ClientOptions, \"endpoint\" | \"baseUrl\">,\n env: Record<string, string | undefined>,\n): string | undefined {\n if (options.endpoint) return options.endpoint;\n if (options.baseUrl) return trimSlash(options.baseUrl) + GRAPHQL_PATH;\n const fromEnv = env[ENDPOINT_ENV_VAR];\n // UNFZ_API_URL is documented as the full /query URL and is used verbatim.\n // Tolerate a bare origin anyway, since that is the obvious mistake and\n // guessing right costs nothing.\n if (fromEnv) {\n const trimmed = trimSlash(fromEnv);\n return /\\/query$|\\/graphql$/.test(trimmed) ? trimmed : trimmed + GRAPHQL_PATH;\n }\n return undefined;\n}\n\nfunction noTokenMessage(endpoint: string | undefined, otherLogin: string | undefined): string {\n if (endpoint && otherLogin) {\n return (\n `unfazed: no API token for ${endpoint}: the stored login is for ${otherLogin}. ` +\n `Run \\`${ENDPOINT_ENV_VAR}=${endpoint} ${LOGIN_COMMAND}\\`, or pass { token } / set ${TOKEN_ENV_VAR}.`\n );\n }\n return (\n `unfazed: not signed in. Run \\`${LOGIN_COMMAND}\\` to sign in with your account, ` +\n `or pass { token } / set ${TOKEN_ENV_VAR} (an agent token: ${DEFAULT_BASE_URL}/auth.md).`\n );\n}\n\nexport function processEnv(): Record<string, string | undefined> {\n // Guarded: the SDK must also work in a browser or worker, where there is no\n // `process` at all.\n return (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};\n}\n\nfunction trimSlash(u: string): string {\n return u.replace(/\\/+$/, \"\");\n}\n\nfunction isAbort(e: unknown): boolean {\n return typeof e === \"object\" && e !== null && (e as { name?: string }).name === \"AbortError\";\n}\n\nfunction abortError(): Error {\n const e = new Error(\"The operation was aborted.\");\n e.name = \"AbortError\";\n return e;\n}\n\n/**\n * Settles with `promise`, or rejects the moment `signal` aborts.\n *\n * A global `fetch` honours the signal for headers and body alike, but an\n * injected {@link FetchLike} — a proxy, an instrumented transport, a test\n * double — need not. Racing the signal makes the timeout an upper bound on the\n * whole request regardless of what the transport does with it. The loser's\n * rejection is swallowed by the already-settled promise rather than surfacing\n * as an unhandled rejection.\n */\nexport function untilAborted<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {\n if (!signal) return promise;\n if (signal.aborted) return Promise.reject(abortError());\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(abortError());\n signal.addEventListener(\"abort\", onAbort, { once: true });\n const done = () => signal.removeEventListener(\"abort\", onAbort);\n promise.then(\n (value) => {\n done();\n resolve(value);\n },\n (error: unknown) => {\n done();\n reject(error as Error);\n },\n );\n });\n}\n\n/**\n * Combines the request timeout with any caller-supplied signal.\n *\n * `didTimeout` is tracked separately from the abort so a caller's own\n * cancellation is not mislabelled as a timeout in the thrown message.\n */\nfunction makeSignal(\n timeoutMs: number,\n external?: AbortSignal,\n): { signal?: AbortSignal; cleanup: () => void; didTimeout: () => boolean } {\n if (!timeoutMs && !external) return { cleanup: () => {}, didTimeout: () => false };\n if (typeof AbortController !== \"function\") {\n return {\n ...(external ? { signal: external } : {}),\n cleanup: () => {},\n didTimeout: () => false,\n };\n }\n\n const controller = new AbortController();\n let timedOut = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n if (timeoutMs > 0) {\n timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeoutMs);\n }\n\n const onExternalAbort = () => controller.abort();\n if (external) {\n if (external.aborted) controller.abort();\n else external.addEventListener(\"abort\", onExternalAbort, { once: true });\n }\n\n return {\n signal: controller.signal,\n cleanup: () => {\n if (timer !== undefined) clearTimeout(timer);\n external?.removeEventListener(\"abort\", onExternalAbort);\n },\n didTimeout: () => timedOut,\n };\n}\n"]}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The eve sandbox daemon: runs as root inside an unfazed box and gives the
|
|
3
|
+
* apps it trusts sandboxes, one Unix user per eve session.
|
|
4
|
+
*
|
|
5
|
+
* It serves the box's :3000, which unfazed publishes at the box's URL, and
|
|
6
|
+
* accepts only workload identity tokens (OIDC, issuer
|
|
7
|
+
* `https://unfazed.dev/oidc`) whose audience is that URL and whose app is on
|
|
8
|
+
* its allow list. A session's commands and file operations run as that
|
|
9
|
+
* session's user, so the kernel keeps sessions apart; the daemon itself only
|
|
10
|
+
* creates and removes users and relays bytes.
|
|
11
|
+
*
|
|
12
|
+
* Started by a box boot hook (`/data/boot.d/50-eve-sandbox`, see setup.ts):
|
|
13
|
+
*
|
|
14
|
+
* node|bun <this file> serve [--config /data/eve-sandbox/config.json]
|
|
15
|
+
*
|
|
16
|
+
* and invoked as the session user for file operations:
|
|
17
|
+
*
|
|
18
|
+
* setpriv --reuid U --regid G --init-groups -- node|bun <this file> fileop
|
|
19
|
+
*/
|
|
20
|
+
import { type IncomingMessage, type ServerResponse } from "node:http";
|
|
21
|
+
export interface DaemonConfig {
|
|
22
|
+
/** The audience every token must carry: the box's URL. */
|
|
23
|
+
readonly audience: string;
|
|
24
|
+
/** App ids (`app_id` claim) allowed to use this box; `owner:<id>` allows every app of an owner. */
|
|
25
|
+
readonly allow: readonly string[];
|
|
26
|
+
readonly issuer: string;
|
|
27
|
+
readonly port: number;
|
|
28
|
+
/** Where session homes live. */
|
|
29
|
+
readonly homeRoot: string;
|
|
30
|
+
/** Kill a session's processes after this long without a call; 0 never. */
|
|
31
|
+
readonly idleMinutes: number;
|
|
32
|
+
/** Delete a session (user, home, files) after this many days without a call; 0 never. */
|
|
33
|
+
readonly retentionDays: number;
|
|
34
|
+
/** Extra environment for every command (e.g. PLAYWRIGHT_BROWSERS_PATH). */
|
|
35
|
+
readonly env: Readonly<Record<string, string>>;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The box's env snapshot (the work drive, rebuilt on every boot). The box
|
|
39
|
+
* init exports it to SSH sessions but not to boot hooks, so a daemon started
|
|
40
|
+
* at boot reads the box's URL from here.
|
|
41
|
+
*/
|
|
42
|
+
export declare const BOX_ENV_SNAPSHOT = "/work/.unfazed/env.json";
|
|
43
|
+
export declare function loadConfig(path?: string, env?: NodeJS.ProcessEnv, snapshot?: string): DaemonConfig;
|
|
44
|
+
export declare class TokenVerifier {
|
|
45
|
+
private readonly config;
|
|
46
|
+
private readonly fetchJson;
|
|
47
|
+
private readonly now;
|
|
48
|
+
private keys;
|
|
49
|
+
private fetchedAt;
|
|
50
|
+
private refreshing;
|
|
51
|
+
constructor(config: Pick<DaemonConfig, "audience" | "issuer" | "allow">, fetchJson?: (url: string) => Promise<unknown>, now?: () => number);
|
|
52
|
+
/** The calling app's namespace (its app id) for a valid, allowed token. */
|
|
53
|
+
verify(authorization: string | undefined): Promise<string>;
|
|
54
|
+
private key;
|
|
55
|
+
private refresh;
|
|
56
|
+
}
|
|
57
|
+
/** The Unix name of an app's session: bounded, derived from the ids only. */
|
|
58
|
+
export declare function sessionName(app: string, sessionId: string): string;
|
|
59
|
+
/** The `fileop` subcommand: one request on stdin, run with the caller's own permissions. */
|
|
60
|
+
export declare function runFileOp(): never;
|
|
61
|
+
export declare function createDaemon(config: DaemonConfig, verifier?: TokenVerifier): {
|
|
62
|
+
server: import("http").Server<typeof IncomingMessage, typeof ServerResponse>;
|
|
63
|
+
listen(port?: number): Promise<void>;
|
|
64
|
+
close(): void;
|
|
65
|
+
};
|