@tangle-network/agent-app 3.0.37 → 4.0.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.
@@ -40,7 +40,7 @@ import {
40
40
  observeNativeCompletion,
41
41
  readCompletedSandboxTurn,
42
42
  recoverSandboxAssistantMessage
43
- } from "../chunk-X2NXWJ6P.js";
43
+ } from "../chunk-HES3IABJ.js";
44
44
  import {
45
45
  runProtectedRouterTurn
46
46
  } from "../chunk-AFMLLZWU.js";
@@ -69,16 +69,15 @@ export interface NativeCompletionTurnReceipt {
69
69
  /** The sidecar's reason for that terminal, used when the replay is not read. */
70
70
  export declare const RUNTIME_RESTARTED_ERROR = "Execution interrupted: the agent runtime restarted before the run produced a terminal event. The run cannot be resumed; retry it.";
71
71
  /**
72
- * Serialized UTF-8 budget for one terminal receipt. A Cloudflare Workflow
73
- * refuses a step result over 1 MiB and D1 refuses a row over 2 MB, and a
74
- * receipt approaches both as tool payloads accumulate over a long turn.
72
+ * Serialized UTF-8 budget for inline native completion checkpoints and final
73
+ * Workflow output. Product transcript storage retains its own separate limit.
75
74
  */
76
75
  export declare const NATIVE_COMPLETION_RECEIPT_MAX_BYTES: number;
77
76
  /**
78
- * Fit a terminal receipt inside {@link NATIVE_COMPLETION_RECEIPT_MAX_BYTES}.
79
- * A receipt under the budget is returned unchanged. Over it, the longest
80
- * strings in tool payloads and reasoning are clipped with a marker, at
81
- * successively smaller caps, so a long turn's answer is always persistable.
77
+ * Assert the aggregate serialized UTF-8 bound without changing native facts.
78
+ * Large receipts must travel by reference; clipping text, file data or tool
79
+ * output here would also change what product preparation and settlement see.
80
+ * The native Workflow adapter uses its exact-result reader for that case.
82
81
  */
83
82
  export declare function boundNativeCompletionReceipt(receipt: NativeCompletionReceipt, maxBytes?: number): NativeCompletionReceipt;
84
83
  /** Assemble admitted exact receipts in dispatch order. Missing usage stays unknown. */
@@ -195,69 +195,15 @@ function replayableExecution(run) {
195
195
  return typeof run.eventCount === "number" && run.eventCount <= INTERRUPTED_RESULT_REPLAY_MAX_EVENTS;
196
196
  }
197
197
  var NATIVE_COMPLETION_RECEIPT_MAX_BYTES = 900 * 1024;
198
- var RECEIPT_STRING_CAPS = [16384, 4096, 1024, 256];
199
198
  var encoder = new TextEncoder();
200
- function serializedBytes(value) {
201
- return encoder.encode(JSON.stringify(value)).length;
202
- }
203
- function capString(value, cap) {
204
- if (value.length <= cap) return value;
205
- return `${value.slice(0, cap)}\u2026[truncated ${value.length - cap} characters; the Sandbox session keeps the full value]`;
206
- }
207
- function capStrings(value, cap) {
208
- if (typeof value === "string") return capString(value, cap);
209
- if (Array.isArray(value)) return value.map((item) => capStrings(item, cap));
210
- const object = record(value);
211
- if (!object) return value;
212
- return Object.fromEntries(Object.entries(object).map(([key, item]) => [key, capStrings(item, cap)]));
213
- }
214
- function capReceiptPart(part, cap) {
215
- const type = String(part.type ?? "");
216
- if (type === "tool") {
217
- const state = record(part.state);
218
- if (!state) return part;
219
- const capped = capStrings(state, cap);
220
- if (serializedBytes(capped) === serializedBytes(state)) return part;
221
- return { ...part, state: { ...capped, metadata: { ...record(capped.metadata), receiptTruncated: true } } };
222
- }
223
- if (type === "reasoning" && typeof part.text === "string" && part.text.length > cap) {
224
- return { ...part, text: capString(part.text, cap), receiptTruncated: true };
225
- }
226
- return part;
227
- }
228
- function skeletonPart(part) {
229
- const type = String(part.type ?? "");
230
- if (type === "reasoning") return null;
231
- if (type !== "tool") return part;
232
- const state = record(part.state);
233
- return {
234
- type: "tool",
235
- ...part.id !== void 0 ? { id: part.id } : {},
236
- ...part.tool !== void 0 ? { tool: part.tool } : {},
237
- state: { status: state?.status ?? "completed", metadata: { receiptTruncated: true } }
238
- };
239
- }
240
199
  function boundNativeCompletionReceipt(receipt, maxBytes = NATIVE_COMPLETION_RECEIPT_MAX_BYTES) {
241
- if (serializedBytes(receipt) <= maxBytes) return receipt;
242
- for (const cap of RECEIPT_STRING_CAPS) {
243
- const bounded = { ...receipt, parts: receipt.parts.map((part) => capReceiptPart(part, cap)) };
244
- if (serializedBytes(bounded) <= maxBytes) return bounded;
245
- }
246
- const skeleton = {
247
- ...receipt,
248
- parts: receipt.parts.map(skeletonPart).filter((part) => part !== null)
249
- };
250
- if (serializedBytes(skeleton) <= maxBytes) return skeleton;
251
- const textBudget = Math.max(0, Math.floor(maxBytes / 4));
252
- return {
253
- ...skeleton,
254
- text: capString(skeleton.text, textBudget),
255
- parts: skeleton.parts.map((part) => part.type === "text" && typeof part.text === "string" ? { ...part, text: capString(part.text, textBudget) } : part)
256
- };
200
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new RangeError("Native completion byte budget must be a positive safe integer");
201
+ const bytes = encoder.encode(JSON.stringify(receipt)).byteLength;
202
+ if (bytes > maxBytes) throw new Error(`Native completion receipt is ${bytes} bytes; use an exact native result reference above ${maxBytes} bytes`);
203
+ return receipt;
257
204
  }
258
205
  function terminal(receipt) {
259
- const bounded = boundNativeCompletionReceipt(receipt);
260
- return bounded.state === "completed" ? { state: "completed", receipt: bounded } : { state: "failed", receipt: bounded };
206
+ return receipt.state === "completed" ? { state: "completed", receipt } : { state: "failed", receipt };
261
207
  }
262
208
  function timestamp(value) {
263
209
  if (value instanceof Date) return value.getTime();
@@ -500,4 +446,4 @@ export {
500
446
  TOOL_ABORTED_ERROR,
501
447
  observeNativeCompletion
502
448
  };
503
- //# sourceMappingURL=chunk-X2NXWJ6P.js.map
449
+ //# sourceMappingURL=chunk-HES3IABJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/chat-routes/completed-sandbox-turn.ts","../src/chat-routes/native-completion.ts"],"sourcesContent":["/**\n * Recover a detached Sandbox turn from its durable completed records.\n *\n * A fast detached run can finish before the live event subscriber receives\n * every message-part event. The Sandbox still retains two exact records: a\n * turn-id keyed result cache and the completed assistant message on the\n * session. This adapter joins them without guessing across turns, then returns\n * the same `DetachedTurnFinal` shape `runDetachedTurn` already consumes.\n */\n\nimport { readTokenCostUsd } from '@tangle-network/agent-core/telemetry'\nimport type { SandboxInstance, SessionMessage } from '@tangle-network/sandbox'\nimport {\n asRecord,\n asString,\n collapseRedundantTextParts,\n finalizeAssistantParts,\n getPartKey,\n mergePersistedPart,\n normalizePersistedPart,\n type JsonRecord,\n} from '../stream/index'\nimport { addStepFinishUsage } from './sandbox-turn-usage'\nimport type { DetachedTurnFinal } from './detached-turn'\nimport type { ChatTurnModelAttribution, ChatTurnUsage } from './turn-routes'\n\n/** The official Sandbox methods needed for completed-turn recovery. */\nexport type CompletedSandboxTurnSource = Pick<\n SandboxInstance,\n 'findCompletedTurn' | 'session'\n>\n\n/** Options for resolving one exact detached turn. */\nexport interface ReadCompletedSandboxTurnOptions {\n turnId: string\n sessionId: string\n /** Read only session messages newer than this Unix-ms time. A long session\n * holds more than one page of messages, oldest first, so an unbounded read\n * both grows with the session and can miss the newest turn. */\n since?: number\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\nfunction finiteNumber(value: unknown): number | undefined {\n if (typeof value === 'number') return Number.isFinite(value) ? value : undefined\n if (typeof value !== 'string' || !value.trim()) return undefined\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : undefined\n}\n\nfunction firstNumber(record: JsonRecord | undefined, keys: string[]): number | undefined {\n for (const key of keys) {\n const value = finiteNumber(record?.[key])\n if (value !== undefined) return value\n }\n return undefined\n}\n\n/** @internal Decode a raw runtime result, whose cost is the harness's own report; callers must establish exact turn identity. */\nexport function usageFromResult(result: JsonRecord | undefined): ChatTurnUsage {\n const raw = asRecord(result?.usage) ?? asRecord(result?.tokenUsage)\n const inputTokens = firstNumber(raw, ['inputTokens', 'promptTokens', 'input'])\n const outputTokens = firstNumber(raw, ['outputTokens', 'completionTokens', 'output'])\n const reasoningTokens = firstNumber(raw, ['reasoningTokens', 'reasoning'])\n const cacheReadTokens = firstNumber(raw, [\n 'cacheReadTokens',\n 'cacheReadInputTokens',\n 'cacheRead',\n ])\n const cacheWriteTokens = firstNumber(raw, [\n 'cacheWriteTokens',\n 'cacheCreationInputTokens',\n 'cacheWrite',\n ])\n const harnessCostUsd = result ? readTokenCostUsd(result) : undefined\n\n return {\n ...(inputTokens !== undefined ? { inputTokens } : {}),\n ...(outputTokens !== undefined ? { outputTokens } : {}),\n ...(reasoningTokens !== undefined ? { reasoningTokens } : {}),\n ...(cacheReadTokens !== undefined ? { cacheReadTokens } : {}),\n ...(cacheWriteTokens !== undefined ? { cacheWriteTokens } : {}),\n ...(harnessCostUsd !== undefined ? { harnessCostUsd } : {}),\n }\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim() ? value : undefined\n}\n\n/** @internal Attribution travels with the same validated result as content and usage. */\nexport function attributionFromResult(result: Record<string, unknown> | undefined): Pick<\n ChatTurnModelAttribution,\n 'servedModel' | 'servedProvider' | 'servedSource'\n> {\n const metadata = asRecord(result?.metadata)\n const modelAttribution = asRecord(result?.modelAttribution) ?? asRecord(metadata?.modelAttribution)\n const backend = asRecord(result?.effectiveBackend) ?? asRecord(metadata?.effectiveBackend)\n const source = nonEmptyString(result?.servedSource)\n ?? nonEmptyString(modelAttribution?.servedSource)\n ?? nonEmptyString(backend?.source)\n const servedSource = source === 'request' || source === 'environment' || source === 'profile'\n ? source\n : undefined\n const servedModel = nonEmptyString(result?.servedModel)\n ?? nonEmptyString(modelAttribution?.servedModel)\n ?? nonEmptyString(backend?.model)\n const servedProvider = nonEmptyString(result?.servedProvider)\n ?? nonEmptyString(modelAttribution?.servedProvider)\n ?? nonEmptyString(backend?.provider)\n return {\n ...(servedModel ? { servedModel } : {}),\n ...(servedProvider ? { servedProvider } : {}),\n ...(servedSource ? { servedSource } : {}),\n }\n}\n\nfunction textFromResult(result: JsonRecord | undefined): string | undefined {\n return asString(result?.response)\n ?? asString(result?.finalText)\n ?? asString(result?.text)\n ?? asString(result?.output)\n}\n\nfunction completedMessagesForTurn(\n messages: SessionMessage[],\n turnId: string,\n): SessionMessage[] {\n return messages.filter((message) =>\n message.role === 'assistant'\n && message.metadata?.turnId === turnId\n && message.metadata?.interrupted !== true\n && (\n message.metadata?.completed === true\n || message.metadata?.status === 'completed'\n ),\n )\n}\n\nfunction normalizedMessageParts(\n message: SessionMessage,\n): { parts: JsonRecord[]; usage: ChatTurnUsage; derivedText: string } {\n const normalized: JsonRecord[] = []\n const usage: ChatTurnUsage = {}\n for (const raw of message.parts) {\n const record = asRecord(raw)\n if (!record) continue\n const part = normalizePersistedPart(record)\n if (!part) continue\n normalized.push(part)\n if (part.type === 'step-finish') addStepFinishUsage(part, usage)\n }\n\n const collapsed = collapseRedundantTextParts(normalized)\n const derivedText = collapsed\n .filter((part) => part.type === 'text')\n .map((part) => String(part.text ?? ''))\n .join('')\n return { parts: normalized, usage, derivedText }\n}\n\nfunction projectMessageParts(parts: JsonRecord[], finalText: string): JsonRecord[] {\n const order: string[] = []\n const map = new Map<string, JsonRecord>()\n for (let index = 0; index < parts.length; index += 1) {\n const part = parts[index]!\n const type = String(part.type ?? '')\n // A session's aggregate message contains every step receipt. Preserve each\n // occurrence just as the live producer does; other kinds merge by their\n // canonical identity.\n const key = type === 'step-start' || type === 'step-finish'\n ? `${type}:#${index}`\n : getPartKey(part)\n if (!map.has(key)) order.push(key)\n map.set(key, mergePersistedPart(map.get(key), part))\n }\n return finalizeAssistantParts(order, map, finalText)\n}\n\n/**\n * Recover the durable content a Sandbox recorder attached to one assistant\n * message. The caller is responsible for proving that the message belongs to\n * the exact terminal turn; this projection deliberately makes no conclusion\n * about whether that terminal state was completed or interrupted.\n */\nexport function recoverSandboxAssistantMessage(message: SessionMessage): DetachedTurnFinal {\n const recovered = normalizedMessageParts(message)\n return {\n ...(recovered.derivedText ? { text: recovered.derivedText } : {}),\n ...(hasUsage(recovered.usage) ? { usage: recovered.usage } : {}),\n parts: projectMessageParts(recovered.parts, recovered.derivedText),\n }\n}\n\nfunction hasUsage(usage: ChatTurnUsage): boolean {\n return Object.values(usage).some((value) =>\n typeof value === 'number' && Number.isFinite(value),\n )\n}\n\n/**\n * Read the exact completed turn from its keyed cache and completed message.\n * Never borrow a session-wide aggregate from a concurrently advancing session.\n * Observation failure is retryable and distinct from successful absent reads.\n * Model attribution comes from that same identity-checked cache record, never\n * from a second unchecked lookup that could belong to a different turn.\n */\nexport async function readCompletedSandboxTurn(\n box: CompletedSandboxTurnSource,\n options: ReadCompletedSandboxTurnOptions,\n): Promise<(DetachedTurnFinal & Pick<ChatTurnModelAttribution, 'servedModel' | 'servedProvider' | 'servedSource'>) | null> {\n const { turnId, sessionId, log } = options\n const session = box.session(sessionId)\n const [cacheOutcome, messagesOutcome] = await Promise.allSettled([\n box.findCompletedTurn(turnId, { sessionId }),\n session.messages({ limit: 1_000, ...(options.since !== undefined ? { since: options.since } : {}) }),\n ])\n\n if (cacheOutcome.status === 'rejected') {\n log?.('[chat-routes] completed Sandbox turn cache lookup failed', {\n turnId,\n sessionId,\n error: String(cacheOutcome.reason),\n })\n }\n if (messagesOutcome.status === 'rejected') {\n log?.('[chat-routes] completed Sandbox session message lookup failed', {\n turnId,\n sessionId,\n error: String(messagesOutcome.reason),\n })\n }\n\n const rawCached = cacheOutcome.status === 'fulfilled' ? cacheOutcome.value : null\n const cached = rawCached\n && rawCached.turnId === turnId\n && rawCached.sessionId === sessionId\n ? rawCached\n : null\n if (rawCached && !cached) {\n log?.('[chat-routes] ignored mismatched completed Sandbox turn cache record', {\n turnId,\n sessionId,\n })\n }\n\n const messages = messagesOutcome.status === 'fulfilled'\n ? messagesOutcome.value\n : []\n const matchingMessages = completedMessagesForTurn(messages, turnId)\n const matchingCount = matchingMessages.length\n const message = matchingCount === 1 ? matchingMessages[0]! : null\n if (matchingCount > 1) {\n log?.('[chat-routes] ignored ambiguous completed Sandbox session messages', {\n turnId,\n sessionId,\n matchingCount,\n })\n }\n\n if (!cached && !message) {\n // A failed read is unknown, not proof that the turn is absent. The durable\n // owner must retry observation rather than admit another execution.\n if (cacheOutcome.status === 'rejected' || messagesOutcome.status === 'rejected') {\n throw new Error('Completed Sandbox turn could not be verified; retry the exact read')\n }\n if (rawCached || matchingCount > 1) {\n throw new Error('Completed Sandbox turn identity is inconsistent; reconciliation is required')\n }\n return null\n }\n\n // Only turn-addressed evidence is safe. A newer turn can complete between\n // reading the message list and reading a session-wide aggregate result.\n const result = cached ? asRecord(cached.result) : undefined\n\n const recovered = message ? normalizedMessageParts(message) : null\n const text = textFromResult(result) ?? recovered?.derivedText\n const resultUsage = usageFromResult(result)\n const usage = { ...(recovered?.usage ?? {}), ...resultUsage }\n const resultParts = Array.isArray(result?.parts)\n ? result.parts\n .map((part) => asRecord(part))\n .filter((part): part is JsonRecord => Boolean(part))\n .map((part) => normalizePersistedPart(part))\n .filter((part): part is JsonRecord => Boolean(part))\n : null\n const sourceParts = recovered?.parts ?? resultParts\n const parts = sourceParts\n ? projectMessageParts(sourceParts, text ?? recovered?.derivedText ?? '')\n : undefined\n\n return {\n ...(text !== undefined ? { text } : {}),\n ...(hasUsage(usage) ? { usage } : {}),\n ...(parts ? { parts } : {}),\n ...attributionFromResult(result),\n }\n}\n","/**\n * Exact terminal observation for a native Sandbox execution that another\n * request already admitted. This module never sends a prompt, calls\n * `driveTurn`, or cancels a run.\n */\n\nimport { readTokenCostUsd } from '@tangle-network/agent-core/telemetry'\nimport type { SandboxInstance, SessionInfo, SessionMessage } from '@tangle-network/sandbox'\nimport type { ChatTurnUsage } from './turn-routes'\nimport type { SessionExecutionInfo } from '@tangle-network/sandbox'\nimport {\n attributionFromResult,\n readCompletedSandboxTurn,\n recoverSandboxAssistantMessage,\n usageFromResult,\n} from './completed-sandbox-turn'\nimport { TURN_USAGE_KEYS } from './sandbox-turn-usage'\n\nexport interface NativeCompletionReceipt {\n state: 'completed' | 'failed'\n text: string\n parts: Array<Record<string, unknown>>\n /** An empty object is an unknown usage receipt, never a measured zero. */\n usage: ChatTurnUsage\n servedModel?: string\n servedProvider?: string\n servedSource?: 'request' | 'environment' | 'profile'\n error?: string\n completedTurnIds: string[]\n}\n\nexport interface NativeCompletionAdmission {\n executionId: string\n state: 'open' | 'closed'\n admittedTurnIds: readonly string[]\n ownerLeaseUntil: Date | number\n updatedAt?: Date | number\n closedAt?: Date | number | null\n}\n\n/** Product persistence for the one admission that authorizes this observer. */\nexport interface NativeCompletionAdmissionStore {\n read(executionId: string): Promise<NativeCompletionAdmission | null>\n renew(executionId: string, now: Date): Promise<NativeCompletionAdmission | null>\n closeExpired(executionId: string, now: Date): Promise<NativeCompletionAdmission | null>\n}\n\n/** The official Sandbox reads needed for exact native completion observation. */\nexport type NativeCompletionSessionSource = Pick<SandboxInstance, 'findCompletedTurn' | 'session'>\n\nexport interface NativeCompletionObservationOptions {\n /** Null when the product cannot currently resolve the admitted Sandbox. */\n source: NativeCompletionSessionSource | null\n admissionStore: NativeCompletionAdmissionStore\n executionId: string\n sessionId: string\n turnId: string\n registeredAt: number\n absentDispatchDeadlineMs?: number\n receiptDeadlineMs?: number\n now?: number\n}\n\nexport type NativeCompletionObservation =\n | { state: 'running' }\n | { state: 'completed'; receipt: NativeCompletionReceipt }\n | { state: 'failed'; receipt: NativeCompletionReceipt }\n\n/** One exact turn receipt before an admission's ordered aggregate. */\nexport interface NativeCompletionTurnReceipt {\n turnId: string\n state: 'completed' | 'failed'\n text: string\n parts: Array<Record<string, unknown>>\n usage: ChatTurnUsage\n servedModel?: string\n servedProvider?: string\n servedSource?: 'request' | 'environment' | 'profile'\n error?: string\n}\n\nconst DEFAULT_ABSENT_DISPATCH_DEADLINE_MS = 10 * 60_000\nconst DEFAULT_RECEIPT_DEADLINE_MS = 10 * 60_000\n/** Session messages are read from this long before registration, so clock\n * skew between the product Worker and the Sandbox cannot hide the turn. */\nconst MESSAGE_READ_SKEW_MS = 10 * 60_000\n\n/**\n * Largest interrupted execution whose event stream is replayed for its\n * terminal result. The replay parses every event and re-compares the growing\n * response text on each token, so its CPU grows faster than the run; a longer\n * run takes its receipt from the recorded message and failure reason alone.\n */\nconst INTERRUPTED_RESULT_REPLAY_MAX_EVENTS = 2_000\n/** Bound on the second replay that reads a failed execution's harness cost. */\nconst HARNESS_COST_REPLAY_MS = 10_000\n/**\n * The fixed id of the terminal the sidecar appends when it fails an execution\n * whose runtime restarted before the run ended.\n */\nconst RUNTIME_RESTART_TERMINAL_EVENT_ID = 'interrupted-done'\n/** The sidecar's reason for that terminal, used when the replay is not read. */\nexport const RUNTIME_RESTARTED_ERROR = 'Execution interrupted: the agent runtime restarted before the run produced a terminal event. The run cannot be resumed; retry it.'\n\nfunction replayableExecution(run: Pick<SessionExecutionInfo, 'eventCount'>): boolean {\n return typeof run.eventCount === 'number' && run.eventCount <= INTERRUPTED_RESULT_REPLAY_MAX_EVENTS\n}\n\n/**\n * Serialized UTF-8 budget for inline native completion checkpoints and final\n * Workflow output. Product transcript storage retains its own separate limit.\n */\nexport const NATIVE_COMPLETION_RECEIPT_MAX_BYTES = 900 * 1024\n\nconst encoder = new TextEncoder()\n\n/**\n * Assert the aggregate serialized UTF-8 bound without changing native facts.\n * Large receipts must travel by reference; clipping text, file data or tool\n * output here would also change what product preparation and settlement see.\n * The native Workflow adapter uses its exact-result reader for that case.\n */\nexport function boundNativeCompletionReceipt(\n receipt: NativeCompletionReceipt,\n maxBytes: number = NATIVE_COMPLETION_RECEIPT_MAX_BYTES,\n): NativeCompletionReceipt {\n if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new RangeError('Native completion byte budget must be a positive safe integer')\n const bytes = encoder.encode(JSON.stringify(receipt)).byteLength\n if (bytes > maxBytes) throw new Error(`Native completion receipt is ${bytes} bytes; use an exact native result reference above ${maxBytes} bytes`)\n return receipt\n}\n\nfunction terminal(receipt: NativeCompletionReceipt): NativeCompletionObservation {\n return receipt.state === 'completed'\n ? { state: 'completed', receipt }\n : { state: 'failed', receipt }\n}\n\nfunction timestamp(value: Date | number | null | undefined): number | undefined {\n if (value instanceof Date) return value.getTime()\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown>\n : undefined\n}\n\nfunction isSandboxNotFoundError(value: unknown): boolean {\n const error = record(value)\n return error?.name === 'NotFoundError' || error?.code === 'NOT_FOUND' || error?.status === 404\n}\n\nfunction isCanonicalUserStop(error: unknown): boolean {\n return error === 'Execution cancelled by user' || error === 'Execution cancelled by the user'\n}\n\n/** A terminal receipt is public; runtime stderr stays in the native record. */\nfunction terminalFailureMessage(error: string, provenUserStop: boolean): string {\n if (provenUserStop) return 'Execution cancelled by the user'\n if (/\\bENOSPC\\b|no space left on device/i.test(error)) {\n return 'The Sandbox ran out of disk space before the execution finished.'\n }\n if (error === RUNTIME_RESTARTED_ERROR) return RUNTIME_RESTARTED_ERROR\n if (/\\bcancelled\\b|\\bcanceled\\b/i.test(error)) return 'Native Sandbox execution was cancelled.'\n if (/MCP.*(?:did not become ready|bootstrap)|(?:MCP|runtime) bootstrap failed/i.test(error)) {\n return 'The Sandbox could not start the agent runtime.'\n }\n return 'Native Sandbox execution failed before producing an answer.'\n}\n\n/** The SDK reads this execution's replay; reject contradictory terminal identity. */\nfunction exactFailedResult(value: unknown, turnId: string, sessionId: string): Record<string, unknown> | undefined {\n const result = record(value)\n if (result?.executionId !== turnId || (result.sessionId !== undefined && result.sessionId !== sessionId)) return undefined\n if (result.success !== false || !['error', 'failed', 'cancelled'].includes(String(result.status))) return undefined\n return typeof result.error === 'string' && result.error.trim() ? result : undefined\n}\n\n/**\n * Usage of a failed execution's SDK result. Its `costUsd` is the Platform\n * ledger charge alone (Sandbox 1.0.264), so the harness's own token cost is\n * read from the replayed terminal frames, where the sidecar puts a failure's\n * `totalCostUsd` on `error` and `done`; an unread replay leaves it unknown.\n */\nasync function failedResultUsage(\n session: ReturnType<NativeCompletionSessionSource['session']>, executionId: string, result: Record<string, unknown> | undefined,\n): Promise<ChatTurnUsage> {\n if (!result) return {}\n let harnessCostUsd: number | undefined\n try {\n for await (const event of session.events({ since: '0', executionId, signal: AbortSignal.timeout(HARNESS_COST_REPLAY_MS) })) {\n if (['result', 'error', 'done'].includes(event.type)) harnessCostUsd = readTokenCostUsd(record(event.data) ?? {}) ?? harnessCostUsd\n }\n } catch { /* unknown, never zero */ }\n const ledger = typeof result.costUsd === 'number' && Number.isFinite(result.costUsd) && result.costUsd >= 0 ? result.costUsd : undefined\n return {\n ...usageFromResult({ usage: result.usage }),\n ...(ledger !== undefined ? { costUsd: ledger } : {}),\n ...(harnessCostUsd !== undefined ? { harnessCostUsd } : {}),\n }\n}\n\nfunction interruptedMessages(messages: SessionMessage[], turnId: string): SessionMessage[] {\n return messages.filter((message) =>\n message.role === 'assistant'\n && message.metadata?.turnId === turnId\n && (message.metadata.interrupted === true || message.metadata.status === 'interrupted'),\n )\n}\n\nfunction turnAssistantMessages(messages: SessionMessage[], turnId: string): SessionMessage[] {\n return messages.filter((message) => message.role === 'assistant' && message.metadata?.turnId === turnId)\n}\n\nfunction consistent<T>(values: Array<T | undefined>): T | undefined {\n if (values.length === 0 || values.some((value) => value === undefined)) return undefined\n const first = values[0] as T\n return values.every((value) => value === first) ? first : undefined\n}\n\nfunction sum(values: Array<number | undefined>): number | undefined {\n if (values.some((value) => value === undefined)) return undefined\n return (values as number[]).reduce((total, value) => total + value, 0)\n}\n\n/** Assemble admitted exact receipts in dispatch order. Missing usage stays unknown. */\nexport function aggregateNativeCompletionReceipts(turns: readonly NativeCompletionTurnReceipt[]): NativeCompletionReceipt {\n const failed = turns.some((turn) => turn.state === 'failed')\n const usage: ChatTurnUsage = {}\n for (const key of TURN_USAGE_KEYS) {\n const total = sum(turns.map((turn) => turn.usage[key]))\n if (total !== undefined) usage[key] = total\n }\n // A missing exact receipt is the terminal observer failure even when an\n // earlier execution also failed. Preserve that earlier partial transcript,\n // but surface why this aggregate could not be fully reconciled.\n const error = turns.find((turn) =>\n turn.error?.startsWith('Admitted native execution did not produce')\n || turn.error?.startsWith('Native Sandbox execution ledger is missing'),\n )?.error ?? turns.find((turn) => turn.error)?.error\n return {\n state: failed ? 'failed' : 'completed',\n text: turns.map((turn) => turn.text).join(''),\n parts: turns.flatMap((turn) => turn.parts),\n usage,\n ...(consistent(turns.map((turn) => turn.servedModel)) ? { servedModel: consistent(turns.map((turn) => turn.servedModel)) } : {}),\n ...(consistent(turns.map((turn) => turn.servedProvider)) ? { servedProvider: consistent(turns.map((turn) => turn.servedProvider)) } : {}),\n ...(consistent(turns.map((turn) => turn.servedSource)) ? { servedSource: consistent(turns.map((turn) => turn.servedSource)) } : {}),\n ...(error ? { error } : {}),\n completedTurnIds: turns.map((turn) => turn.turnId),\n }\n}\n\n/** The failure a completed run with an aborted tool call settles with. */\nexport const TOOL_ABORTED_ERROR = 'The Sandbox aborted a tool call before the turn finished, as when its runtime restarts mid-turn'\n\n/**\n * The name of a tool whose call the Sandbox aborted, or undefined. OpenCode\n * marks a tool interrupted by a runtime restart with \"Tool execution aborted\";\n * an ordinary tool error (a missing file, an HTTP 403) does not end the turn.\n */\nfunction abortedToolCall(parts: ReadonlyArray<Record<string, unknown>>): string | undefined {\n for (const part of parts) {\n if (part.type !== 'tool') continue\n const state = part.state as { status?: unknown; error?: unknown } | undefined\n if (state?.status === 'error' && /tool execution aborted/i.test(String(state.error ?? ''))) {\n return typeof part.tool === 'string' ? part.tool : 'tool'\n }\n }\n return undefined\n}\n\n/**\n * Whether the session still runs this admission's work, so its lease should be\n * renewed. The session's own status is not enough: it keeps a persisted\n * `running` status when the runtime restarts under it (the sidecar may report\n * that as recovery state `stale`, or not at all), while its execution ledger\n * has already failed the interrupted run. Renewing on status alone observed\n * GTM b81b's restarted completions forever. Live means an\n * admitted turn's execution is active, or not yet recorded while its dispatch\n * can still be on the way.\n */\nfunction admittedWorkIsLive(\n status: SessionInfo,\n runsByTurnId: ReadonlyMap<string, SessionExecutionInfo>,\n admittedTurnIds: readonly string[],\n dispatchMayBePending: boolean,\n): boolean {\n if (status.status !== 'queued' && status.status !== 'running') return false\n if (status.raw?.state === 'stale') return false\n return admittedTurnIds.some((turnId) => {\n const run = runsByTurnId.get(turnId)\n return run ? run.status === 'active' : dispatchMayBePending\n })\n}\n\nfunction missingTurnReceipt(turnId: string, error: string): NativeCompletionTurnReceipt {\n // An execution ledger entry proves this turn reached a terminal state, but\n // not that its terminal transcript was retained. Keep any earlier exact\n // evidence when the bounded wait expires; `{}` means aggregate usage is\n // unknown because this turn has no usage receipt.\n return { turnId, state: 'failed', text: '', parts: [], usage: {}, error }\n}\n\n/**\n * Observe only the turns admitted under `executionId`. Transport failures throw\n * so the durable owner retries. A missing or partial terminal record remains\n * `running` until the configured deadline; it never starts another run.\n */\nexport async function observeNativeCompletion(\n options: NativeCompletionObservationOptions,\n): Promise<NativeCompletionObservation> {\n const now = options.now ?? Date.now()\n let admission = await options.admissionStore.read(options.executionId)\n if (!admission) throw new Error('Native completion admission is missing')\n if (admission.executionId !== options.executionId) throw new Error('Native completion admission identity conflict')\n const leaseUntil = timestamp(admission.ownerLeaseUntil) ?? 0\n const source = options.source\n const session = source?.session(options.sessionId)\n let status: SessionInfo | null\n if (!session) {\n status = null\n } else {\n try {\n status = await session.status()\n } catch (error) {\n if (!isSandboxNotFoundError(error)) throw error\n status = null\n }\n }\n\n if (!status || !session || !source) {\n if (admission.state === 'open' && leaseUntil <= now) {\n admission = await options.admissionStore.closeExpired(options.executionId, new Date(now)) ?? admission\n }\n if (admission.state === 'open' || now - options.registeredAt < (options.absentDispatchDeadlineMs ?? DEFAULT_ABSENT_DISPATCH_DEADLINE_MS)) {\n return { state: 'running' }\n }\n return terminal(aggregateNativeCompletionReceipts([\n missingTurnReceipt(options.turnId, 'Native Sandbox dispatch was not observed before the admission deadline'),\n ]))\n }\n const exactSession = session\n const dispatchMayBePending = now - options.registeredAt < (options.absentDispatchDeadlineMs ?? DEFAULT_ABSENT_DISPATCH_DEADLINE_MS)\n let runsByTurnId: Map<string, SessionExecutionInfo> | undefined\n const readRuns = async () => runsByTurnId ??= new Map((await exactSession.runs()).map((run) => [run.executionId, run]))\n\n if (admission.state === 'open') {\n if (admittedWorkIsLive(status, await readRuns(), admission.admittedTurnIds, dispatchMayBePending)) {\n admission = await options.admissionStore.renew(options.executionId, new Date(now)) ?? admission\n } else if (leaseUntil <= now) {\n admission = await options.admissionStore.closeExpired(options.executionId, new Date(now)) ?? admission\n }\n if (admission.state === 'open') return { state: 'running' }\n }\n // `closeExpired` may return the current row after another owner appended a\n // continuation. Read its full ordered ledger rather than observing the\n // earlier snapshot from before the close attempt.\n const admittedTurnIds = [...admission.admittedTurnIds]\n if (admittedTurnIds.length === 0 || admittedTurnIds[0] !== options.turnId) {\n throw new Error('Native completion admission has an invalid turn sequence')\n }\n\n const ledger = await readRuns()\n const missingExecution = admittedTurnIds.find((turnId) => !ledger.has(turnId))\n if (missingExecution && dispatchMayBePending) return { state: 'running' }\n if (admittedTurnIds.some((turnId) => ledger.get(turnId)?.status === 'active')) return { state: 'running' }\n\n // Completed recovery owns its message read. Load interrupted history only\n // when it is needed, and share that one read across failed continuations.\n // Both reads start shortly before registration, so their size follows this\n // turn rather than the whole session.\n const since = Math.max(0, options.registeredAt - MESSAGE_READ_SKEW_MS)\n let messages: SessionMessage[] | undefined\n const recovered: NativeCompletionTurnReceipt[] = []\n for (const turnId of admittedTurnIds) {\n const run = ledger.get(turnId)\n if (!run) {\n recovered.push(missingTurnReceipt(turnId, 'Native Sandbox execution ledger is missing the admitted turn'))\n continue\n }\n const completed = run.status === 'completed'\n ? await readCompletedSandboxTurn(source, { turnId, sessionId: options.sessionId, since })\n : null\n if (run.status === 'completed' && completed) {\n const aborted = abortedToolCall(completed.parts ?? [])\n recovered.push({\n ...completed,\n turnId,\n // A run the runtime ended while a tool was still running reports\n // completed, but its reply stops mid-work. It is a failed turn.\n state: aborted ? 'failed' : 'completed',\n text: completed.text ?? '',\n parts: completed.parts ?? [],\n usage: completed.usage ?? {},\n ...(aborted ? { error: `${TOOL_ABORTED_ERROR} (${aborted})` } : {}),\n })\n continue\n }\n // The process that would stamp a turn interrupted is gone when its runtime\n // restarts; the sidecar fails the execution on restart, and the turn's own\n // assistant message holds whatever reply it had streamed.\n const restarted = run.status === 'failed' && run.lastEventId === RUNTIME_RESTART_TERMINAL_EVENT_ID\n let interrupted = run.status === 'failed' || run.status === 'cancelled'\n ? interruptedMessages(messages ??= await exactSession.messages({ limit: 1_000, since }), turnId)\n : []\n if (restarted && interrupted.length === 0) interrupted = turnAssistantMessages(messages ?? [], turnId)\n if (restarted && interrupted.length !== 1) {\n recovered.push({ turnId, state: 'failed', text: '', parts: [], usage: {}, error: RUNTIME_RESTARTED_ERROR })\n continue\n }\n // Bootstrap can fail before the runtime creates an assistant message. The\n // terminal execution replay is independent of that transcript projection.\n if ((run.status === 'failed' || run.status === 'cancelled') && interrupted.length === 0\n && turnAssistantMessages(messages ?? [], turnId).length === 0\n && run.sessionId === options.sessionId && replayableExecution(run)) {\n const result = exactFailedResult(await exactSession.result({ executionId: turnId }), turnId, options.sessionId)\n if (result) {\n recovered.push({\n turnId, state: 'failed', text: '', parts: [], usage: await failedResultUsage(exactSession, turnId, result),\n ...attributionFromResult(result), error: terminalFailureMessage(result.error as string, run.status === 'cancelled' && isCanonicalUserStop(result.error)),\n })\n continue\n }\n }\n if ((run.status === 'failed' || run.status === 'cancelled') && interrupted.length === 1) {\n const message = recoverSandboxAssistantMessage(interrupted[0]!)\n const result = replayableExecution(run)\n ? await exactSession.result({ executionId: turnId }) as unknown as Record<string, unknown>\n : undefined\n const provenUserStop = run.status === 'cancelled'\n && (isCanonicalUserStop(interrupted[0]!.metadata?.interruptReason)\n || isCanonicalUserStop(exactFailedResult(result, turnId, options.sessionId)?.error))\n recovered.push({\n turnId,\n state: 'failed',\n text: message.text ?? (typeof result?.response === 'string' ? result.response : undefined) ?? '',\n parts: message.parts ?? [],\n usage: { ...message.usage, ...await failedResultUsage(exactSession, turnId, result) },\n ...attributionFromResult(result),\n error: terminalFailureMessage((typeof result?.error === 'string' ? result.error : undefined)\n ?? interrupted[0]!.metadata?.interruptReason\n ?? (restarted ? RUNTIME_RESTARTED_ERROR : undefined)\n ?? status.failureReason?.message\n ?? 'Native Sandbox execution failed.', provenUserStop),\n })\n continue\n }\n const closedAt = timestamp(admission.closedAt)\n ?? timestamp(admission.updatedAt)\n ?? options.registeredAt\n if (now - closedAt < (options.receiptDeadlineMs ?? DEFAULT_RECEIPT_DEADLINE_MS)) return { state: 'running' }\n recovered.push(missingTurnReceipt(\n turnId,\n `Admitted native execution did not produce an exact completion: ${turnId}`,\n ))\n }\n return terminal(aggregateNativeCompletionReceipts(recovered))\n}\n"],"mappings":";;;;;;;;;;;;;;;AAUA,SAAS,wBAAwB;AAiCjC,SAAS,aAAa,OAAoC;AACxD,MAAI,OAAO,UAAU,SAAU,QAAO,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE,MAAI,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,EAAG,QAAO;AACvD,QAAM,SAAS,OAAO,KAAK;AAC3B,SAAO,OAAO,SAAS,MAAM,IAAI,SAAS;AAC5C;AAEA,SAAS,YAAYA,SAAgC,MAAoC;AACvF,aAAW,OAAO,MAAM;AACtB,UAAM,QAAQ,aAAaA,UAAS,GAAG,CAAC;AACxC,QAAI,UAAU,OAAW,QAAO;AAAA,EAClC;AACA,SAAO;AACT;AAGO,SAAS,gBAAgB,QAA+C;AAC7E,QAAM,MAAM,SAAS,QAAQ,KAAK,KAAK,SAAS,QAAQ,UAAU;AAClE,QAAM,cAAc,YAAY,KAAK,CAAC,eAAe,gBAAgB,OAAO,CAAC;AAC7E,QAAM,eAAe,YAAY,KAAK,CAAC,gBAAgB,oBAAoB,QAAQ,CAAC;AACpF,QAAM,kBAAkB,YAAY,KAAK,CAAC,mBAAmB,WAAW,CAAC;AACzE,QAAM,kBAAkB,YAAY,KAAK;AAAA,IACvC;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AACD,QAAM,mBAAmB,YAAY,KAAK;AAAA,IACxC;AAAA,IACA;AAAA,IACA;AAAA,EACF,CA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A0B,WACvC,OAAO,eAAe,WACtB,oCAAoC,cAAc;AAAA,MACzD,CAAC;AACD;AAAA,IACF;AACA,UAAM,WAAW,UAAU,UAAU,QAAQ,KACxC,UAAU,UAAU,SAAS,KAC7B,QAAQ;AACb,QAAI,MAAM,YAAY,QAAQ,qBAAqB,6BAA8B,QAAO,EAAE,OAAO,UAAU;AAC3G,cAAU,KAAK;AAAA,MACb;AAAA,MACA,kEAAkE,MAAM;AAAA,IAC1E,CAAC;AAAA,EACH;AACA,SAAO,SAAS,kCAAkC,SAAS,CAAC;AAC9D;","names":["record","readTokenCostUsd","readTokenCostUsd"]}
@@ -349,13 +349,16 @@ async function checkDeployedApp(options) {
349
349
  if (access) {
350
350
  const open = access;
351
351
  await check("plain-turn", async () => ({ value: true, detail: await plainTurn(open, turnMs) }));
352
- await check("computer-turn", async () => ({
353
- value: true,
354
- detail: await computerTurn(open, turnMs, options.computer ?? "digest", options.fileDir ?? "proof", options.computerModel ?? DEFAULT_COMPUTER_MODEL)
355
- }));
352
+ const proof = options.computer ?? "digest";
353
+ if (proof !== "none") {
354
+ await check("computer-turn", async () => ({
355
+ value: true,
356
+ detail: await computerTurn(open, turnMs, proof, options.fileDir ?? "proof", options.computerModel ?? DEFAULT_COMPUTER_MODEL)
357
+ }));
358
+ }
356
359
  } else {
357
360
  blocked("plain-turn", "blocked by operator-access");
358
- blocked("computer-turn", "blocked by operator-access");
361
+ if (options.computer !== "none") blocked("computer-turn", "blocked by operator-access");
359
362
  }
360
363
  const mintedKey = minted;
361
364
  if (mintedKey && session) {
@@ -371,4 +374,4 @@ async function checkDeployedApp(options) {
371
374
  export {
372
375
  checkDeployedApp
373
376
  };
374
- //# sourceMappingURL=chunk-PABZALSD.js.map
377
+ //# sourceMappingURL=chunk-LBMFQLBS.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/conformance/session.ts","../src/conformance/revision.ts","../src/conformance/turns.ts","../src/conformance/run.ts"],"sourcesContent":["/**\n * Sign-in for the conformance runner: the two ways a member reaches an agent app, and one question both answer,\n * \"does the app accept this session?\". Nothing here is specific to an app; a product whose sign-in differs\n * fails the check with the status it answered.\n */\n\nexport type SignInMode = 'password' | 'sso'\n\n/** A check failed for a reason worth reporting; its message is the cause. */\nexport class Failure extends Error {}\n\nexport interface MemberSession {\n origin: string\n /** A request to the app as the signed-in member; `path` is root-relative. */\n fetch(path: string, init?: RequestInit): Promise<Response>\n}\n\nconst REQUEST_MS = 30_000\n\n/** Cookies by origin: enough of a jar for one sign-in and the calls after it. */\nclass Jar {\n private readonly byOrigin = new Map<string, Map<string, string>>()\n\n header(url: string): string {\n return [...(this.byOrigin.get(new URL(url).origin) ?? [])].map(([name, value]) => `${name}=${value}`).join('; ')\n }\n\n async send(url: string, init: RequestInit = {}): Promise<Response> {\n const headers = new Headers(init.headers)\n const cookie = this.header(url)\n if (cookie) headers.set('cookie', cookie)\n const response = await fetch(url, { ...init, headers, redirect: 'manual', signal: init.signal ?? AbortSignal.timeout(REQUEST_MS) })\n this.absorb(url, response)\n return response\n }\n\n private absorb(url: string, response: Response): void {\n const origin = new URL(url).origin\n const jar = this.byOrigin.get(origin) ?? new Map<string, string>()\n for (const line of response.headers.getSetCookie()) {\n const [pair = '', ...attributes] = line.split(';')\n const eq = pair.indexOf('=')\n if (eq < 1) continue\n const name = pair.slice(0, eq).trim()\n const value = pair.slice(eq + 1).trim()\n const attribute = (key: string) => attributes.map(item => item.trim()).find(item => item.toLowerCase().startsWith(`${key}=`))?.slice(key.length + 1)\n const maxAge = attribute('max-age')\n const expires = attribute('expires')\n const gone = !value || (maxAge !== undefined && Number(maxAge) <= 0)\n || (maxAge === undefined && expires !== undefined && Date.parse(expires) <= Date.now())\n if (gone) jar.delete(name)\n else jar.set(name, value)\n }\n this.byOrigin.set(origin, jar)\n }\n}\n\nconst snippet = async (response: Response) => (await response.text().catch(() => '')).replace(/\\s+/g, ' ').slice(0, 160)\n\n/** A sign-in POST. An auth service that answers 429 is asked again after its Retry-After (at most 20 s), twice at most. */\nasync function postSignIn(jar: Jar, origin: string, email: string, password: string): Promise<Response> {\n for (let attempt = 0; ; attempt += 1) {\n const response = await jar.send(`${origin}/api/auth/sign-in/email`, {\n method: 'POST', headers: { 'content-type': 'application/json', origin }, body: JSON.stringify({ email, password }),\n })\n if (response.status !== 429 || attempt === 2) return response\n const wait = Number(response.headers.get('retry-after'))\n await response.body?.cancel().catch(() => {})\n await new Promise(resolve => setTimeout(resolve, Math.min(20, Number.isFinite(wait) && wait > 0 ? wait : 5) * 1000))\n }\n}\n\nasync function passwordSignIn(jar: Jar, origin: string, email: string, password: string): Promise<void> {\n const response = await postSignIn(jar, origin, email, password)\n if (response.status !== 200) throw new Failure(`password sign-in answered ${response.status}: ${await snippet(response)}`)\n}\n\nconst TANGLE_AUTH_PATH = /(^|\\/)auth\\/tangle\\//\n\n/**\n * The app's \"Log in with Tangle\": its start route sends the browser to Platform, Platform signs the member in and\n * authorizes, and the app's callback sets its own session. Apps mount the start route at `/auth/tangle/start` or\n * under `/api`.\n */\nasync function ssoSignIn(jar: Jar, origin: string, email: string, password: string): Promise<void> {\n const answers: string[] = []\n let location: string | null = null\n for (const path of ['/auth/tangle/start', '/api/auth/tangle/start']) {\n const start = await jar.send(`${origin}${path}`)\n location = start.headers.get('location')\n if (location) break\n answers.push(`${path} answered ${start.status}`)\n }\n if (!location) throw new Failure(`SSO start sent the member nowhere (${answers.join('; ')})`)\n const authorize = new URL(location, origin)\n const platform = authorize.origin\n const member = await postSignIn(jar, platform, email, password)\n if (member.status !== 200) throw new Failure(`Platform sign-in answered ${member.status}: ${await snippet(member)}`)\n let next = authorize.href\n for (let hop = 0; hop < 8; hop += 1) {\n const response = await jar.send(next)\n const redirect = response.headers.get('location')\n if (!redirect) throw new Failure(`SSO stopped at ${new URL(next).pathname} with ${response.status}`)\n const url = new URL(redirect, next)\n if (url.origin === origin && !TANGLE_AUTH_PATH.test(url.pathname)) {\n if (url.pathname.startsWith('/login') || url.searchParams.has('error') || url.searchParams.get('connection') === 'failed') {\n throw new Failure(`the app's SSO callback sent the member to ${url.pathname}${url.search.slice(0, 80)}`)\n }\n return\n }\n next = url.href\n }\n throw new Failure('SSO did not return to the app within 8 redirects')\n}\n\n/** A redirect to sign-in or an error page is an app that did not accept the session. */\nasync function sessionAccepted(session: MemberSession): Promise<string> {\n const who = await session.fetch('/api/auth/get-session')\n if (who.status === 200) {\n const body = await who.json().catch(() => null) as { user?: { id?: unknown } } | null\n if (typeof body?.user?.id === 'string' && body.user.id) return 'GET /api/auth/get-session returned the user'\n }\n const workspaces = await session.fetch('/api/workspaces')\n if (workspaces.status === 200) return 'GET /api/workspaces answered 200 as the member'\n throw new Failure(`signed in, but the app does not accept the session: GET /api/auth/get-session answered ${who.status}, GET /api/workspaces ${workspaces.status}`)\n}\n\n/** Signs in and proves the app accepts the session; the detail names the proof. */\nexport async function signIn(input: { origin: string; mode: SignInMode; email: string; password: string }): Promise<{ session: MemberSession; detail: string }> {\n const jar = new Jar()\n if (input.mode === 'password') await passwordSignIn(jar, input.origin, input.email, input.password)\n else await ssoSignIn(jar, input.origin, input.email, input.password)\n const session: MemberSession = {\n origin: input.origin,\n fetch: (path, init = {}) => {\n const headers = new Headers(init.headers)\n if (!headers.has('origin')) headers.set('origin', input.origin)\n return jar.send(`${input.origin}${path}`, { ...init, headers })\n },\n }\n return { session, detail: `${input.mode}: ${await sessionAccepted(session)}` }\n}\n","/**\n * The served revision, read the way an operator reads it: from the app's own `GET /api/health` body, or from the\n * `x-<app>-revision` / `x-<app>-version` header the app puts on its responses. An app that serves neither cannot\n * say what it is running, so a release cannot be told from the one before it.\n */\n\nimport { Failure } from './session.js'\n\nconst REVISION_HEADER = /^x-[a-z0-9-]+-(revision|version)$/i\nconst REQUEST_MS = 20_000\n\nconst text = (value: unknown): string | null => typeof value === 'string' && value.trim() ? value.trim() : null\n\n/** The revision a health body carries: `revision`, or what `release` carries. */\nfunction fromHealth(body: unknown): string | null {\n if (!body || typeof body !== 'object') return null\n const record = body as Record<string, unknown>\n const release = record.release && typeof record.release === 'object' ? record.release as Record<string, unknown> : {}\n return text(record.revision) ?? text(release.revision) ?? text(release.sha) ?? text(release.tag)\n}\n\nfunction fromHeaders(response: Response): { name: string; value: string } | null {\n for (const [name, value] of response.headers) if (REVISION_HEADER.test(name) && value.trim()) return { name, value: value.trim() }\n return null\n}\n\n/**\n * Reads the revision, or throws a Failure naming every place it looked. `source` says where it was read, e.g.\n * `GET /api/health` or `GET / x-creative-revision`.\n */\nexport async function readRevision(origin: string, expect?: string): Promise<{ revision: string; source: string }> {\n const looked: string[] = []\n const found = await (async (): Promise<{ revision: string; source: string } | null> => {\n for (const path of ['/api/health', '/']) {\n let response: Response\n try {\n response = await fetch(`${origin}${path}`, { headers: { accept: 'application/json' }, redirect: 'manual', signal: AbortSignal.timeout(REQUEST_MS) })\n } catch (error) {\n looked.push(`GET ${path} failed (${error instanceof Error ? error.name : 'error'})`)\n continue\n }\n const header = fromHeaders(response)\n if (path === '/api/health' && response.ok) {\n const revision = fromHealth(await response.json().catch(() => null))\n if (revision) return { revision, source: 'GET /api/health' }\n }\n if (header) return { revision: header.value, source: `GET ${path} ${header.name}` }\n await response.body?.cancel().catch(() => {})\n looked.push(`GET ${path} answered ${response.status} without a revision`)\n }\n return null\n })()\n if (!found) throw new Failure(`the app serves no readable revision (${looked.join('; ')})`)\n if (expect) {\n const [a, b] = [found.revision.toLowerCase(), expect.trim().toLowerCase()]\n if (b.length < 7 || !(a.startsWith(b) || b.startsWith(a))) {\n throw new Failure(`the app serves revision ${found.revision} (${found.source}), not the expected ${expect}`)\n }\n }\n return found\n}\n","/**\n * The conformance turns, run through the operator API every agent app mounts the same way\n * (docs/operator-api.md), so one runner drives every product. The verdict is the settled turn the app stored.\n *\n * plain a reply with text;\n * computer a turn only the workspace computer can answer: either the digest of a fresh nonce, which the model\n * cannot know without running the command, or a file the computer saves that the app then serves back.\n */\n\nimport { createHash, randomBytes, randomUUID } from 'node:crypto'\nimport { createOperatorClient, type OperatorClient } from '../operator/client.js'\nimport type { OperatorTurn, OperatorWorkspace } from '../operator/contract.js'\nimport { Failure, type MemberSession } from './session.js'\n\nexport type ComputerProof = 'digest' | 'file'\n\nconst REQUEST_MS = 30_000\nconst KEY_LIFETIME_MS = 60 * 60_000\n\nexport interface OperatorAccess {\n client: OperatorClient\n workspace: OperatorWorkspace\n /** The app's own account of what the key may do. */\n scopes: readonly string[]\n}\n\n/** An expiring key for the signed-in member, through the route every app's API access page uses. */\nexport async function mintKey(session: MemberSession): Promise<{ id: string; key: string }> {\n const response = await session.fetch('/api/keys', {\n method: 'POST', headers: { 'content-type': 'application/json' }, signal: AbortSignal.timeout(REQUEST_MS),\n body: JSON.stringify({\n name: `conformance ${new Date().toISOString()}`, scopes: ['operator:read', 'operator:run'],\n expiresAt: new Date(Date.now() + KEY_LIFETIME_MS).toISOString(), workspaceIds: [],\n }),\n })\n if (response.status === 404) {\n throw new Failure('the app has no key route (POST /api/keys answered 404), so a conformance turn has no credential; give it an operator key')\n }\n const body = await response.json().catch(() => null) as { id?: unknown; key?: unknown; error?: unknown } | null\n if (!response.ok || typeof body?.id !== 'string' || typeof body.key !== 'string') {\n throw new Failure(`POST /api/keys answered ${response.status}: ${typeof body?.error === 'string' ? body.error.slice(0, 160) : 'no key in the response'}`)\n }\n return { id: body.id, key: body.key }\n}\n\n/** Revokes a key this run created. Apps accept the id in the path, or in the body of the collection route. */\nexport async function revokeKey(session: MemberSession, id: string): Promise<void> {\n const byPath = await session.fetch(`/api/keys/${encodeURIComponent(id)}`, { method: 'DELETE', signal: AbortSignal.timeout(REQUEST_MS) })\n if (byPath.ok) return\n const byBody = await session.fetch('/api/keys', {\n method: 'DELETE', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id }), signal: AbortSignal.timeout(REQUEST_MS),\n })\n if (byBody.ok) return\n throw new Failure(`the minted key ${id} was not revoked: DELETE /api/keys/:id answered ${byPath.status}, DELETE /api/keys ${byBody.status} (it expires within the hour)`)\n}\n\n/**\n * Opens the operator API with `key` and picks the workspace the turns run in: `workspace` is its id or exact name,\n * and omitted, the key must reach exactly one. `requestMs` bounds any one request, a held turn read included.\n */\nexport async function openOperatorAccess(\n { origin, key, workspace, requestMs }: { origin: string; key: string; workspace: string | undefined; requestMs: number },\n): Promise<OperatorAccess> {\n const client = createOperatorClient({\n origin,\n getApiKey: () => key,\n fetchImpl: (url, init) => fetch(url, { ...init, signal: init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(requestMs)]) : AbortSignal.timeout(requestMs) }),\n })\n const described = await client.describe()\n if (!described.succeeded) throw new Failure(`GET /api/operator/v1 answered ${described.status} ${described.code}: ${described.error.slice(0, 160)}`)\n const scopes = described.value.principal.scopes\n const missing = ['operator:read', 'operator:run'].filter(scope => !scopes.includes(scope) && !scopes.includes('*'))\n if (missing.length) throw new Failure(`the operator key lacks ${missing.join(' and ')}`)\n const listed = await client.listWorkspaces()\n if (!listed.succeeded) throw new Failure(`GET /api/operator/v1/workspaces answered ${listed.status} ${listed.code}: ${listed.error.slice(0, 160)}`)\n const chosen = workspace\n ? listed.value.filter(candidate => candidate.id === workspace || candidate.name === workspace)\n : listed.value.length === 1 ? listed.value : []\n if (chosen.length !== 1) {\n const names = listed.value.slice(0, 12).map(candidate => `${candidate.name} (${candidate.id.slice(0, 8)})`).join(', ')\n throw new Failure(workspace\n ? `${chosen.length} of the key's ${listed.value.length} workspaces match \"${workspace}\": ${names}`\n : `the key reaches ${listed.value.length} workspaces; name the canary workspace: ${names}`)\n }\n return { client, workspace: chosen[0]!, scopes }\n}\n\nconst reply = (turn: OperatorTurn) => (turn.reply?.content ?? '').trim()\n\n/** One turn on a new thread, followed until it settles. */\nasync function runTurn(access: OperatorAccess, title: string, content: string, turnMs: number, model?: string): Promise<{ turn: OperatorTurn; where: string }> {\n const turnId = randomUUID()\n const started = await access.client.startTurn(access.workspace.id, { turnId, content, title, ...(model ? { model } : {}) })\n if (!started.succeeded) throw new Failure(`the turn was refused: ${started.status} ${started.code}: ${started.error.slice(0, 200)}`)\n const where = `thread ${started.value.threadId}`\n const settled = await access.client.waitForTurn(access.workspace.id, started.value.threadId, started.value.turnId, { timeoutMs: turnMs })\n if (!settled.succeeded) throw new Failure(`reading the turn answered ${settled.status} ${settled.code}: ${settled.error.slice(0, 160)} (${where})`)\n const turn = settled.value\n if (turn.state === 'failed') throw new Failure(`the turn failed${turn.failure?.code ? ` (${turn.failure.code})` : ''}: ${(turn.failure?.message ?? 'no message').slice(0, 300)} (${where})`)\n if (turn.state === 'input-required' || turn.approvals.length > 0) throw new Failure(`the turn is waiting on a decision, which no one can answer in a conformance run (${where})`)\n if (turn.state !== 'succeeded') throw new Failure(`the turn had not settled after ${Math.round(turnMs / 1000)} s (state ${turn.state}; ${where})`)\n return { turn, where }\n}\n\nexport async function plainTurn(access: OperatorAccess, turnMs: number): Promise<string> {\n const { turn, where } = await runTurn(access, 'Conformance: plain turn',\n 'Conformance check: reply with one short sentence confirming you can answer.', turnMs)\n if (!reply(turn)) throw new Failure(`the turn succeeded with an empty reply (${where})`)\n return `${reply(turn).length} characters from ${turn.model ?? 'an unreported model'} (${where})`\n}\n\nexport async function computerTurn(access: OperatorAccess, turnMs: number, proof: ComputerProof, fileDir: string, model: string): Promise<string> {\n const nonce = `conformance-${randomBytes(12).toString('hex')}`\n if (proof === 'digest') {\n const digest = createHash('sha256').update(nonce).digest('hex')\n const { turn, where } = await runTurn(access, 'Conformance: computer turn',\n 'Conformance check: run this exact shell command on the workspace computer (sandbox_run when you have it), then reply with only '\n + `the 64-character hex digest it prints:\\nprintf %s '${nonce}' | sha256sum`, turnMs, model)\n if (!reply(turn).includes(digest)) {\n throw new Failure(`the reply does not hold the digest of the fresh nonce, so the computer did not run the command: \"${reply(turn).slice(0, 160)}\" (${where})`)\n }\n return `the reply carries the digest ${digest.slice(0, 12)}… (${where})`\n }\n const path = `${fileDir.replace(/\\/+$/, '')}/${nonce}.md`\n const { where } = await runTurn(access, 'Conformance: computer turn',\n `Conformance check: use the workspace computer to save a file at ${path} whose whole content is this one line, then reply with the word saved:\\n${nonce}`, turnMs, model)\n const read = await access.client.readFile(access.workspace.id, path)\n if (!read.succeeded) throw new Failure(`the turn succeeded, but the app does not serve ${path}: ${read.status} ${read.code} (${where})`)\n if (read.value.content.trim() !== nonce) {\n throw new Failure(`${path} holds ${JSON.stringify(read.value.content.slice(0, 80))}, not the nonce (${where})`)\n }\n return `the app serves ${path} with the nonce (${where})`\n}\n","import { readRevision } from './revision.js'\nimport { Failure, signIn, type MemberSession, type SignInMode } from './session.js'\nimport { computerTurn, mintKey, openOperatorAccess, plainTurn, revokeKey, type ComputerProof, type OperatorAccess } from './turns.js'\n\nexport type CheckName = 'sign-in' | 'revision' | 'operator-access' | 'plain-turn' | 'computer-turn' | 'key-revoke'\n\n/**\n * One check's verdict. `blocked` means an earlier check it depends on failed, so nothing was measured; a blocked\n * check fails the run like a failed one, and its cause names the check that blocked it.\n */\nexport interface CheckResult {\n /** When the check started, ISO 8601. */\n at: string\n app: string\n url: string\n check: CheckName\n status: 'pass' | 'fail' | 'blocked'\n ms: number\n /** Why a failed or blocked check is not a pass. */\n cause?: string\n /** What a passing check observed: the revision read, the thread a turn ran in. */\n detail?: string\n}\n\nexport interface ConformanceOptions {\n /** A label for the result lines, e.g. `gtm`. */\n app: string\n /** The deployed origin, e.g. `https://gtm.tangle.tools`. */\n origin: string\n /** The member that signs in. Required: sign-in is the first thing a customer does. */\n member?: { mode: SignInMode; email: string; password: string }\n /** A key that already has `operator:read` and `operator:run`; without one, the signed-in member mints a one-hour key. */\n operatorKey?: string\n /** Id or exact name of the workspace the turns run in: the app's canary or smoke workspace, never a customer's. */\n workspace?: string\n /** `digest` hashes a fresh nonce on the workspace computer; `file` has the computer save a file the app serves back. */\n computer?: ComputerProof\n /** The computer turn's model. The plain turn keeps the app's own model, so the served model is still checked once. */\n computerModel?: string\n /** Where the `file` proof is saved, relative to the workspace root. */\n fileDir?: string\n /** The budget of each turn, a cold box included. */\n turnMs?: number\n /** Fail unless the served revision starts with, or is a prefix of, this. */\n expectRevision?: string\n /** Called with each result as it lands. */\n onResult?(result: CheckResult): void\n}\n\nconst DEFAULT_TURN_MS = 300_000\n// Company spend rule: checks run on the flat-rate plan; per-token models are for product serving with real users.\nconst DEFAULT_COMPUTER_MODEL = 'glm-5.3'\n\n/** Why an unexpected error is not a pass, in a line. */\nfunction describe(error: unknown): string {\n if (error instanceof Failure) return error.message\n if (error instanceof Error) {\n const cause = error.cause as { code?: unknown } | undefined\n return `${error.name}: ${error.message}${typeof cause?.code === 'string' ? ` (${cause.code})` : ''}`\n }\n return String(error)\n}\n\n/** Runs the checks against one deployed app and returns every result, in the order they ran. */\nexport async function checkDeployedApp(options: ConformanceOptions): Promise<CheckResult[]> {\n const origin = options.origin.replace(/\\/+$/, '')\n const turnMs = options.turnMs ?? DEFAULT_TURN_MS\n const secrets = [options.member?.password, options.operatorKey].filter((value): value is string => Boolean(value && value.length >= 6))\n const redact = (text: string) => secrets.reduce((out, secret) => out.split(secret).join('[redacted]'), text)\n const results: CheckResult[] = []\n\n const record = (result: CheckResult) => {\n const clean = { ...result, ...(result.cause ? { cause: redact(result.cause) } : {}), ...(result.detail ? { detail: redact(result.detail) } : {}) }\n results.push(clean)\n options.onResult?.(clean)\n }\n /** Runs `body`; whatever it returns is the passing detail, whatever it throws is the cause. */\n async function check<T>(name: CheckName, body: () => Promise<{ value: T; detail?: string }>): Promise<T | undefined> {\n const at = new Date().toISOString()\n const started = Date.now()\n const base = { at, app: options.app, url: origin, check: name }\n try {\n const { value, detail } = await body()\n record({ ...base, status: 'pass', ms: Date.now() - started, ...(detail ? { detail } : {}) })\n return value\n } catch (error) {\n record({ ...base, status: 'fail', ms: Date.now() - started, cause: describe(error) })\n return undefined\n }\n }\n const blocked = (name: CheckName, because: string) =>\n record({ at: new Date().toISOString(), app: options.app, url: origin, check: name, status: 'blocked', ms: 0, cause: because })\n\n let session: MemberSession | undefined\n if (!options.member) {\n const at = new Date().toISOString()\n record({ at, app: options.app, url: origin, check: 'sign-in', status: 'fail', ms: 0, cause: 'no member is configured: give the canary member email and password' })\n } else {\n const member = options.member\n session = await check('sign-in', async () => {\n const signedIn = await signIn({ origin, ...member })\n return { value: signedIn.session, detail: signedIn.detail }\n })\n }\n\n await check('revision', async () => {\n const served = await readRevision(origin, options.expectRevision)\n return { value: served, detail: `${served.revision} (${served.source})` }\n })\n\n let minted: { id: string } | null = null\n let access: OperatorAccess | undefined\n if (!options.operatorKey && !session) {\n blocked('operator-access', 'blocked by sign-in: no operator key is configured, and the member did not sign in to mint one')\n } else {\n access = await check('operator-access', async () => {\n let secret = options.operatorKey\n if (!secret) {\n const created = await mintKey(session!)\n secrets.push(created.key)\n secret = created.key\n minted = { id: created.id }\n }\n const opened = await openOperatorAccess({ origin, key: secret, workspace: options.workspace, requestMs: turnMs + 60_000 })\n return {\n value: opened,\n detail: `${minted ? 'a minted one-hour key' : 'the configured operator key'} reaches \"${opened.workspace.name}\" with ${opened.scopes.join(', ')}`,\n }\n })\n }\n\n if (access) {\n const open = access\n await check('plain-turn', async () => ({ value: true, detail: await plainTurn(open, turnMs) }))\n await check('computer-turn', async () => ({\n value: true, detail: await computerTurn(open, turnMs, options.computer ?? 'digest', options.fileDir ?? 'proof', options.computerModel ?? DEFAULT_COMPUTER_MODEL),\n }))\n } else {\n blocked('plain-turn', 'blocked by operator-access')\n blocked('computer-turn', 'blocked by operator-access')\n }\n\n // A key this run minted is revoked whether or not the turns ran: it names the member and would outlive the run.\n const mintedKey = minted as { id: string } | null\n if (mintedKey && session) {\n const member = session\n await check('key-revoke', async () => {\n await revokeKey(member, mintedKey.id)\n return { value: true, detail: 'the minted key was revoked' }\n })\n }\n return results\n}\n"],"mappings":";;;;;AASO,IAAM,UAAN,cAAsB,MAAM;AAAC;AAQpC,IAAM,aAAa;AAGnB,IAAM,MAAN,MAAU;AAAA,EACS,WAAW,oBAAI,IAAiC;AAAA,EAEjE,OAAO,KAAqB;AAC1B,WAAO,CAAC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AM,UAAU,MAAM,QAAQ,OAAQ;AACtC,gBAAQ,KAAK,QAAQ,GAAG;AACxB,iBAAS,QAAQ;AACjB,iBAAS,EAAE,IAAI,QAAQ,GAAG;AAAA,MAC5B;AACA,YAAM,SAAS,MAAM,mBAAmB,EAAE,QAAQ,KAAK,QAAQ,WAAW,QAAQ,WAAW,WAAW,SAAS,IAAO,CAAC;AACzH,aAAO;AAAA,QACL,OAAO;AAAA,QACP,QAAQ,GAAG,SAAS,0BAA0B,6BAA6B,aAAa,OAAO,UAAU,IAAI,UAAU,OAAO,OAAO,KAAK,IAAI,CAAC;AAAA,MACjJ;AAAA,IACF,CAAC;AAAA,EACH;AAEA,MAAI,QAAQ;AACV,UAAM,OAAO;AACb,UAAM,MAAM,cAAc,aAAa,EAAE,OAAO,MAAM,QAAQ,MAAM,UAAU,MAAM,MAAM,EAAE,EAAE;AAC9F,UAAM,MAAM,iBAAiB,aAAa;AAAA,MACxC,OAAO;AAAA,MAAM,QAAQ,MAAM,aAAa,MAAM,QAAQ,QAAQ,YAAY,UAAU,QAAQ,WAAW,SAAS,QAAQ,iBAAiB,sBAAsB;AAAA,IACjK,EAAE;AAAA,EACJ,OAAO;AACL,YAAQ,cAAc,4BAA4B;AAClD,YAAQ,iBAAiB,4BAA4B;AAAA,EACvD;AAGA,QAAM,YAAY;AAClB,MAAI,aAAa,SAAS;AACxB,UAAM,SAAS;AACf,UAAM,MAAM,cAAc,YAAY;AACpC,YAAM,UAAU,QAAQ,UAAU,EAAE;AACpC,aAAO,EAAE,OAAO,MAAM,QAAQ,6BAA6B;AAAA,IAC7D,CAAC;AAAA,EACH;AACA,SAAO;AACT;","names":["REQUEST_MS","REQUEST_MS","where","text"]}
1
+ {"version":3,"sources":["../src/conformance/session.ts","../src/conformance/revision.ts","../src/conformance/turns.ts","../src/conformance/run.ts"],"sourcesContent":["/**\n * Sign-in for the conformance runner: the two ways a member reaches an agent app, and one question both answer,\n * \"does the app accept this session?\". Nothing here is specific to an app; a product whose sign-in differs\n * fails the check with the status it answered.\n */\n\nexport type SignInMode = 'password' | 'sso'\n\n/** A check failed for a reason worth reporting; its message is the cause. */\nexport class Failure extends Error {}\n\nexport interface MemberSession {\n origin: string\n /** A request to the app as the signed-in member; `path` is root-relative. */\n fetch(path: string, init?: RequestInit): Promise<Response>\n}\n\nconst REQUEST_MS = 30_000\n\n/** Cookies by origin: enough of a jar for one sign-in and the calls after it. */\nclass Jar {\n private readonly byOrigin = new Map<string, Map<string, string>>()\n\n header(url: string): string {\n return [...(this.byOrigin.get(new URL(url).origin) ?? [])].map(([name, value]) => `${name}=${value}`).join('; ')\n }\n\n async send(url: string, init: RequestInit = {}): Promise<Response> {\n const headers = new Headers(init.headers)\n const cookie = this.header(url)\n if (cookie) headers.set('cookie', cookie)\n const response = await fetch(url, { ...init, headers, redirect: 'manual', signal: init.signal ?? AbortSignal.timeout(REQUEST_MS) })\n this.absorb(url, response)\n return response\n }\n\n private absorb(url: string, response: Response): void {\n const origin = new URL(url).origin\n const jar = this.byOrigin.get(origin) ?? new Map<string, string>()\n for (const line of response.headers.getSetCookie()) {\n const [pair = '', ...attributes] = line.split(';')\n const eq = pair.indexOf('=')\n if (eq < 1) continue\n const name = pair.slice(0, eq).trim()\n const value = pair.slice(eq + 1).trim()\n const attribute = (key: string) => attributes.map(item => item.trim()).find(item => item.toLowerCase().startsWith(`${key}=`))?.slice(key.length + 1)\n const maxAge = attribute('max-age')\n const expires = attribute('expires')\n const gone = !value || (maxAge !== undefined && Number(maxAge) <= 0)\n || (maxAge === undefined && expires !== undefined && Date.parse(expires) <= Date.now())\n if (gone) jar.delete(name)\n else jar.set(name, value)\n }\n this.byOrigin.set(origin, jar)\n }\n}\n\nconst snippet = async (response: Response) => (await response.text().catch(() => '')).replace(/\\s+/g, ' ').slice(0, 160)\n\n/** A sign-in POST. An auth service that answers 429 is asked again after its Retry-After (at most 20 s), twice at most. */\nasync function postSignIn(jar: Jar, origin: string, email: string, password: string): Promise<Response> {\n for (let attempt = 0; ; attempt += 1) {\n const response = await jar.send(`${origin}/api/auth/sign-in/email`, {\n method: 'POST', headers: { 'content-type': 'application/json', origin }, body: JSON.stringify({ email, password }),\n })\n if (response.status !== 429 || attempt === 2) return response\n const wait = Number(response.headers.get('retry-after'))\n await response.body?.cancel().catch(() => {})\n await new Promise(resolve => setTimeout(resolve, Math.min(20, Number.isFinite(wait) && wait > 0 ? wait : 5) * 1000))\n }\n}\n\nasync function passwordSignIn(jar: Jar, origin: string, email: string, password: string): Promise<void> {\n const response = await postSignIn(jar, origin, email, password)\n if (response.status !== 200) throw new Failure(`password sign-in answered ${response.status}: ${await snippet(response)}`)\n}\n\nconst TANGLE_AUTH_PATH = /(^|\\/)auth\\/tangle\\//\n\n/**\n * The app's \"Log in with Tangle\": its start route sends the browser to Platform, Platform signs the member in and\n * authorizes, and the app's callback sets its own session. Apps mount the start route at `/auth/tangle/start` or\n * under `/api`.\n */\nasync function ssoSignIn(jar: Jar, origin: string, email: string, password: string): Promise<void> {\n const answers: string[] = []\n let location: string | null = null\n for (const path of ['/auth/tangle/start', '/api/auth/tangle/start']) {\n const start = await jar.send(`${origin}${path}`)\n location = start.headers.get('location')\n if (location) break\n answers.push(`${path} answered ${start.status}`)\n }\n if (!location) throw new Failure(`SSO start sent the member nowhere (${answers.join('; ')})`)\n const authorize = new URL(location, origin)\n const platform = authorize.origin\n const member = await postSignIn(jar, platform, email, password)\n if (member.status !== 200) throw new Failure(`Platform sign-in answered ${member.status}: ${await snippet(member)}`)\n let next = authorize.href\n for (let hop = 0; hop < 8; hop += 1) {\n const response = await jar.send(next)\n const redirect = response.headers.get('location')\n if (!redirect) throw new Failure(`SSO stopped at ${new URL(next).pathname} with ${response.status}`)\n const url = new URL(redirect, next)\n if (url.origin === origin && !TANGLE_AUTH_PATH.test(url.pathname)) {\n if (url.pathname.startsWith('/login') || url.searchParams.has('error') || url.searchParams.get('connection') === 'failed') {\n throw new Failure(`the app's SSO callback sent the member to ${url.pathname}${url.search.slice(0, 80)}`)\n }\n return\n }\n next = url.href\n }\n throw new Failure('SSO did not return to the app within 8 redirects')\n}\n\n/** A redirect to sign-in or an error page is an app that did not accept the session. */\nasync function sessionAccepted(session: MemberSession): Promise<string> {\n const who = await session.fetch('/api/auth/get-session')\n if (who.status === 200) {\n const body = await who.json().catch(() => null) as { user?: { id?: unknown } } | null\n if (typeof body?.user?.id === 'string' && body.user.id) return 'GET /api/auth/get-session returned the user'\n }\n const workspaces = await session.fetch('/api/workspaces')\n if (workspaces.status === 200) return 'GET /api/workspaces answered 200 as the member'\n throw new Failure(`signed in, but the app does not accept the session: GET /api/auth/get-session answered ${who.status}, GET /api/workspaces ${workspaces.status}`)\n}\n\n/** Signs in and proves the app accepts the session; the detail names the proof. */\nexport async function signIn(input: { origin: string; mode: SignInMode; email: string; password: string }): Promise<{ session: MemberSession; detail: string }> {\n const jar = new Jar()\n if (input.mode === 'password') await passwordSignIn(jar, input.origin, input.email, input.password)\n else await ssoSignIn(jar, input.origin, input.email, input.password)\n const session: MemberSession = {\n origin: input.origin,\n fetch: (path, init = {}) => {\n const headers = new Headers(init.headers)\n if (!headers.has('origin')) headers.set('origin', input.origin)\n return jar.send(`${input.origin}${path}`, { ...init, headers })\n },\n }\n return { session, detail: `${input.mode}: ${await sessionAccepted(session)}` }\n}\n","/**\n * The served revision, read the way an operator reads it: from the app's own `GET /api/health` body, or from the\n * `x-<app>-revision` / `x-<app>-version` header the app puts on its responses. An app that serves neither cannot\n * say what it is running, so a release cannot be told from the one before it.\n */\n\nimport { Failure } from './session.js'\n\nconst REVISION_HEADER = /^x-[a-z0-9-]+-(revision|version)$/i\nconst REQUEST_MS = 20_000\n\nconst text = (value: unknown): string | null => typeof value === 'string' && value.trim() ? value.trim() : null\n\n/** The revision a health body carries: `revision`, or what `release` carries. */\nfunction fromHealth(body: unknown): string | null {\n if (!body || typeof body !== 'object') return null\n const record = body as Record<string, unknown>\n const release = record.release && typeof record.release === 'object' ? record.release as Record<string, unknown> : {}\n return text(record.revision) ?? text(release.revision) ?? text(release.sha) ?? text(release.tag)\n}\n\nfunction fromHeaders(response: Response): { name: string; value: string } | null {\n for (const [name, value] of response.headers) if (REVISION_HEADER.test(name) && value.trim()) return { name, value: value.trim() }\n return null\n}\n\n/**\n * Reads the revision, or throws a Failure naming every place it looked. `source` says where it was read, e.g.\n * `GET /api/health` or `GET / x-creative-revision`.\n */\nexport async function readRevision(origin: string, expect?: string): Promise<{ revision: string; source: string }> {\n const looked: string[] = []\n const found = await (async (): Promise<{ revision: string; source: string } | null> => {\n for (const path of ['/api/health', '/']) {\n let response: Response\n try {\n response = await fetch(`${origin}${path}`, { headers: { accept: 'application/json' }, redirect: 'manual', signal: AbortSignal.timeout(REQUEST_MS) })\n } catch (error) {\n looked.push(`GET ${path} failed (${error instanceof Error ? error.name : 'error'})`)\n continue\n }\n const header = fromHeaders(response)\n if (path === '/api/health' && response.ok) {\n const revision = fromHealth(await response.json().catch(() => null))\n if (revision) return { revision, source: 'GET /api/health' }\n }\n if (header) return { revision: header.value, source: `GET ${path} ${header.name}` }\n await response.body?.cancel().catch(() => {})\n looked.push(`GET ${path} answered ${response.status} without a revision`)\n }\n return null\n })()\n if (!found) throw new Failure(`the app serves no readable revision (${looked.join('; ')})`)\n if (expect) {\n const [a, b] = [found.revision.toLowerCase(), expect.trim().toLowerCase()]\n if (b.length < 7 || !(a.startsWith(b) || b.startsWith(a))) {\n throw new Failure(`the app serves revision ${found.revision} (${found.source}), not the expected ${expect}`)\n }\n }\n return found\n}\n","/**\n * The conformance turns, run through the operator API every agent app mounts the same way\n * (docs/operator-api.md), so one runner drives every product. The verdict is the settled turn the app stored.\n *\n * plain a reply with text;\n * computer a turn only the workspace computer can answer: either the digest of a fresh nonce, which the model\n * cannot know without running the command, or a file the computer saves that the app then serves back.\n */\n\nimport { createHash, randomBytes, randomUUID } from 'node:crypto'\nimport { createOperatorClient, type OperatorClient } from '../operator/client.js'\nimport type { OperatorTurn, OperatorWorkspace } from '../operator/contract.js'\nimport { Failure, type MemberSession } from './session.js'\n\nexport type ComputerProof = 'digest' | 'file'\n\nconst REQUEST_MS = 30_000\nconst KEY_LIFETIME_MS = 60 * 60_000\n\nexport interface OperatorAccess {\n client: OperatorClient\n workspace: OperatorWorkspace\n /** The app's own account of what the key may do. */\n scopes: readonly string[]\n}\n\n/** An expiring key for the signed-in member, through the route every app's API access page uses. */\nexport async function mintKey(session: MemberSession): Promise<{ id: string; key: string }> {\n const response = await session.fetch('/api/keys', {\n method: 'POST', headers: { 'content-type': 'application/json' }, signal: AbortSignal.timeout(REQUEST_MS),\n body: JSON.stringify({\n name: `conformance ${new Date().toISOString()}`, scopes: ['operator:read', 'operator:run'],\n expiresAt: new Date(Date.now() + KEY_LIFETIME_MS).toISOString(), workspaceIds: [],\n }),\n })\n if (response.status === 404) {\n throw new Failure('the app has no key route (POST /api/keys answered 404), so a conformance turn has no credential; give it an operator key')\n }\n const body = await response.json().catch(() => null) as { id?: unknown; key?: unknown; error?: unknown } | null\n if (!response.ok || typeof body?.id !== 'string' || typeof body.key !== 'string') {\n throw new Failure(`POST /api/keys answered ${response.status}: ${typeof body?.error === 'string' ? body.error.slice(0, 160) : 'no key in the response'}`)\n }\n return { id: body.id, key: body.key }\n}\n\n/** Revokes a key this run created. Apps accept the id in the path, or in the body of the collection route. */\nexport async function revokeKey(session: MemberSession, id: string): Promise<void> {\n const byPath = await session.fetch(`/api/keys/${encodeURIComponent(id)}`, { method: 'DELETE', signal: AbortSignal.timeout(REQUEST_MS) })\n if (byPath.ok) return\n const byBody = await session.fetch('/api/keys', {\n method: 'DELETE', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id }), signal: AbortSignal.timeout(REQUEST_MS),\n })\n if (byBody.ok) return\n throw new Failure(`the minted key ${id} was not revoked: DELETE /api/keys/:id answered ${byPath.status}, DELETE /api/keys ${byBody.status} (it expires within the hour)`)\n}\n\n/**\n * Opens the operator API with `key` and picks the workspace the turns run in: `workspace` is its id or exact name,\n * and omitted, the key must reach exactly one. `requestMs` bounds any one request, a held turn read included.\n */\nexport async function openOperatorAccess(\n { origin, key, workspace, requestMs }: { origin: string; key: string; workspace: string | undefined; requestMs: number },\n): Promise<OperatorAccess> {\n const client = createOperatorClient({\n origin,\n getApiKey: () => key,\n fetchImpl: (url, init) => fetch(url, { ...init, signal: init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(requestMs)]) : AbortSignal.timeout(requestMs) }),\n })\n const described = await client.describe()\n if (!described.succeeded) throw new Failure(`GET /api/operator/v1 answered ${described.status} ${described.code}: ${described.error.slice(0, 160)}`)\n const scopes = described.value.principal.scopes\n const missing = ['operator:read', 'operator:run'].filter(scope => !scopes.includes(scope) && !scopes.includes('*'))\n if (missing.length) throw new Failure(`the operator key lacks ${missing.join(' and ')}`)\n const listed = await client.listWorkspaces()\n if (!listed.succeeded) throw new Failure(`GET /api/operator/v1/workspaces answered ${listed.status} ${listed.code}: ${listed.error.slice(0, 160)}`)\n const chosen = workspace\n ? listed.value.filter(candidate => candidate.id === workspace || candidate.name === workspace)\n : listed.value.length === 1 ? listed.value : []\n if (chosen.length !== 1) {\n const names = listed.value.slice(0, 12).map(candidate => `${candidate.name} (${candidate.id.slice(0, 8)})`).join(', ')\n throw new Failure(workspace\n ? `${chosen.length} of the key's ${listed.value.length} workspaces match \"${workspace}\": ${names}`\n : `the key reaches ${listed.value.length} workspaces; name the canary workspace: ${names}`)\n }\n return { client, workspace: chosen[0]!, scopes }\n}\n\nconst reply = (turn: OperatorTurn) => (turn.reply?.content ?? '').trim()\n\n/** One turn on a new thread, followed until it settles. */\nasync function runTurn(access: OperatorAccess, title: string, content: string, turnMs: number, model?: string): Promise<{ turn: OperatorTurn; where: string }> {\n const turnId = randomUUID()\n const started = await access.client.startTurn(access.workspace.id, { turnId, content, title, ...(model ? { model } : {}) })\n if (!started.succeeded) throw new Failure(`the turn was refused: ${started.status} ${started.code}: ${started.error.slice(0, 200)}`)\n const where = `thread ${started.value.threadId}`\n const settled = await access.client.waitForTurn(access.workspace.id, started.value.threadId, started.value.turnId, { timeoutMs: turnMs })\n if (!settled.succeeded) throw new Failure(`reading the turn answered ${settled.status} ${settled.code}: ${settled.error.slice(0, 160)} (${where})`)\n const turn = settled.value\n if (turn.state === 'failed') throw new Failure(`the turn failed${turn.failure?.code ? ` (${turn.failure.code})` : ''}: ${(turn.failure?.message ?? 'no message').slice(0, 300)} (${where})`)\n if (turn.state === 'input-required' || turn.approvals.length > 0) throw new Failure(`the turn is waiting on a decision, which no one can answer in a conformance run (${where})`)\n if (turn.state !== 'succeeded') throw new Failure(`the turn had not settled after ${Math.round(turnMs / 1000)} s (state ${turn.state}; ${where})`)\n return { turn, where }\n}\n\nexport async function plainTurn(access: OperatorAccess, turnMs: number): Promise<string> {\n const { turn, where } = await runTurn(access, 'Conformance: plain turn',\n 'Conformance check: reply with one short sentence confirming you can answer.', turnMs)\n if (!reply(turn)) throw new Failure(`the turn succeeded with an empty reply (${where})`)\n return `${reply(turn).length} characters from ${turn.model ?? 'an unreported model'} (${where})`\n}\n\nexport async function computerTurn(access: OperatorAccess, turnMs: number, proof: ComputerProof, fileDir: string, model: string): Promise<string> {\n const nonce = `conformance-${randomBytes(12).toString('hex')}`\n if (proof === 'digest') {\n const digest = createHash('sha256').update(nonce).digest('hex')\n const { turn, where } = await runTurn(access, 'Conformance: computer turn',\n 'Conformance check: run this exact shell command on the workspace computer (sandbox_run when you have it), then reply with only '\n + `the 64-character hex digest it prints:\\nprintf %s '${nonce}' | sha256sum`, turnMs, model)\n if (!reply(turn).includes(digest)) {\n throw new Failure(`the reply does not hold the digest of the fresh nonce, so the computer did not run the command: \"${reply(turn).slice(0, 160)}\" (${where})`)\n }\n return `the reply carries the digest ${digest.slice(0, 12)}… (${where})`\n }\n const path = `${fileDir.replace(/\\/+$/, '')}/${nonce}.md`\n const { where } = await runTurn(access, 'Conformance: computer turn',\n `Conformance check: use the workspace computer to save a file at ${path} whose whole content is this one line, then reply with the word saved:\\n${nonce}`, turnMs, model)\n const read = await access.client.readFile(access.workspace.id, path)\n if (!read.succeeded) throw new Failure(`the turn succeeded, but the app does not serve ${path}: ${read.status} ${read.code} (${where})`)\n if (read.value.content.trim() !== nonce) {\n throw new Failure(`${path} holds ${JSON.stringify(read.value.content.slice(0, 80))}, not the nonce (${where})`)\n }\n return `the app serves ${path} with the nonce (${where})`\n}\n","import { readRevision } from './revision.js'\nimport { Failure, signIn, type MemberSession, type SignInMode } from './session.js'\nimport { computerTurn, mintKey, openOperatorAccess, plainTurn, revokeKey, type ComputerProof, type OperatorAccess } from './turns.js'\n\nexport type CheckName = 'sign-in' | 'revision' | 'operator-access' | 'plain-turn' | 'computer-turn' | 'key-revoke'\n\n/**\n * One check's verdict. `blocked` means an earlier check it depends on failed, so nothing was measured; a blocked\n * check fails the run like a failed one, and its cause names the check that blocked it.\n */\nexport interface CheckResult {\n /** When the check started, ISO 8601. */\n at: string\n app: string\n url: string\n check: CheckName\n status: 'pass' | 'fail' | 'blocked'\n ms: number\n /** Why a failed or blocked check is not a pass. */\n cause?: string\n /** What a passing check observed: the revision read, the thread a turn ran in. */\n detail?: string\n}\n\nexport interface ConformanceOptions {\n /** A label for the result lines, e.g. `gtm`. */\n app: string\n /** The deployed origin, e.g. `https://gtm.tangle.tools`. */\n origin: string\n /** The member that signs in. Required: sign-in is the first thing a customer does. */\n member?: { mode: SignInMode; email: string; password: string }\n /** A key that already has `operator:read` and `operator:run`; without one, the signed-in member mints a one-hour key. */\n operatorKey?: string\n /** Id or exact name of the workspace the turns run in: the app's canary or smoke workspace, never a customer's. */\n workspace?: string\n /** `digest` hashes a fresh nonce on the workspace computer; `file` has the computer save a file the app serves back;\n * `none` runs the plain turn only, for a check that asks exactly once (a post-serve first ask). */\n computer?: ComputerProof | 'none'\n /** The computer turn's model. The plain turn keeps the app's own model, so the served model is still checked once. */\n computerModel?: string\n /** Where the `file` proof is saved, relative to the workspace root. */\n fileDir?: string\n /** The budget of each turn, a cold box included. */\n turnMs?: number\n /** Fail unless the served revision starts with, or is a prefix of, this. */\n expectRevision?: string\n /** Called with each result as it lands. */\n onResult?(result: CheckResult): void\n}\n\nconst DEFAULT_TURN_MS = 300_000\n// Company spend rule: checks run on the flat-rate plan; per-token models are for product serving with real users.\nconst DEFAULT_COMPUTER_MODEL = 'glm-5.3'\n\n/** Why an unexpected error is not a pass, in a line. */\nfunction describe(error: unknown): string {\n if (error instanceof Failure) return error.message\n if (error instanceof Error) {\n const cause = error.cause as { code?: unknown } | undefined\n return `${error.name}: ${error.message}${typeof cause?.code === 'string' ? ` (${cause.code})` : ''}`\n }\n return String(error)\n}\n\n/** Runs the checks against one deployed app and returns every result, in the order they ran. */\nexport async function checkDeployedApp(options: ConformanceOptions): Promise<CheckResult[]> {\n const origin = options.origin.replace(/\\/+$/, '')\n const turnMs = options.turnMs ?? DEFAULT_TURN_MS\n const secrets = [options.member?.password, options.operatorKey].filter((value): value is string => Boolean(value && value.length >= 6))\n const redact = (text: string) => secrets.reduce((out, secret) => out.split(secret).join('[redacted]'), text)\n const results: CheckResult[] = []\n\n const record = (result: CheckResult) => {\n const clean = { ...result, ...(result.cause ? { cause: redact(result.cause) } : {}), ...(result.detail ? { detail: redact(result.detail) } : {}) }\n results.push(clean)\n options.onResult?.(clean)\n }\n /** Runs `body`; whatever it returns is the passing detail, whatever it throws is the cause. */\n async function check<T>(name: CheckName, body: () => Promise<{ value: T; detail?: string }>): Promise<T | undefined> {\n const at = new Date().toISOString()\n const started = Date.now()\n const base = { at, app: options.app, url: origin, check: name }\n try {\n const { value, detail } = await body()\n record({ ...base, status: 'pass', ms: Date.now() - started, ...(detail ? { detail } : {}) })\n return value\n } catch (error) {\n record({ ...base, status: 'fail', ms: Date.now() - started, cause: describe(error) })\n return undefined\n }\n }\n const blocked = (name: CheckName, because: string) =>\n record({ at: new Date().toISOString(), app: options.app, url: origin, check: name, status: 'blocked', ms: 0, cause: because })\n\n let session: MemberSession | undefined\n if (!options.member) {\n const at = new Date().toISOString()\n record({ at, app: options.app, url: origin, check: 'sign-in', status: 'fail', ms: 0, cause: 'no member is configured: give the canary member email and password' })\n } else {\n const member = options.member\n session = await check('sign-in', async () => {\n const signedIn = await signIn({ origin, ...member })\n return { value: signedIn.session, detail: signedIn.detail }\n })\n }\n\n await check('revision', async () => {\n const served = await readRevision(origin, options.expectRevision)\n return { value: served, detail: `${served.revision} (${served.source})` }\n })\n\n let minted: { id: string } | null = null\n let access: OperatorAccess | undefined\n if (!options.operatorKey && !session) {\n blocked('operator-access', 'blocked by sign-in: no operator key is configured, and the member did not sign in to mint one')\n } else {\n access = await check('operator-access', async () => {\n let secret = options.operatorKey\n if (!secret) {\n const created = await mintKey(session!)\n secrets.push(created.key)\n secret = created.key\n minted = { id: created.id }\n }\n const opened = await openOperatorAccess({ origin, key: secret, workspace: options.workspace, requestMs: turnMs + 60_000 })\n return {\n value: opened,\n detail: `${minted ? 'a minted one-hour key' : 'the configured operator key'} reaches \"${opened.workspace.name}\" with ${opened.scopes.join(', ')}`,\n }\n })\n }\n\n if (access) {\n const open = access\n await check('plain-turn', async () => ({ value: true, detail: await plainTurn(open, turnMs) }))\n const proof = options.computer ?? 'digest'\n if (proof !== 'none') {\n await check('computer-turn', async () => ({\n value: true, detail: await computerTurn(open, turnMs, proof, options.fileDir ?? 'proof', options.computerModel ?? DEFAULT_COMPUTER_MODEL),\n }))\n }\n } else {\n blocked('plain-turn', 'blocked by operator-access')\n if (options.computer !== 'none') blocked('computer-turn', 'blocked by operator-access')\n }\n\n // A key this run minted is revoked whether or not the turns ran: it names the member and would outlive the run.\n const mintedKey = minted as { id: string } | null\n if (mintedKey && session) {\n const member = session\n await check('key-revoke', async () => {\n await revokeKey(member, mintedKey.id)\n return { value: true, detail: 'the minted key was revoked' }\n })\n }\n return results\n}\n"],"mappings":";;;;;AASO,IAAM,UAAN,cAAsB,MAAM;AAAC;AAQpC,IAAM,aAAa;AAGnB,IAAM,MAAN,MAAU;AAAA,EACS,WAAW,oBAAI,IAAiC;AAAA,EAEjE,OAAO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
- } from "../chunk-PABZALSD.js";
4
+ } from "../chunk-LBMFQLBS.js";
5
5
  import "../chunk-EI27JMS6.js";
6
6
  import {
7
7
  invokedAsScript
@@ -31,7 +31,7 @@ function parseConformanceArgs(argv, env = process.env) {
31
31
  const mode = flags.get("--auth") ?? "password";
32
32
  if (mode !== "password" && mode !== "sso") throw new Error("--auth is password or sso");
33
33
  const computer = flags.get("--computer") ?? "digest";
34
- if (computer !== "digest" && computer !== "file") throw new Error("--computer is digest or file");
34
+ if (computer !== "digest" && computer !== "file" && computer !== "none") throw new Error("--computer is digest, file or none");
35
35
  const turnMs = Number(flags.get("--turn-ms") ?? 3e5);
36
36
  if (!Number.isFinite(turnMs) || turnMs < 1e3) throw new Error("--turn-ms is a number of milliseconds, at least 1000");
37
37
  const email = flags.get("--email") ?? env.CONFORMANCE_EMAIL?.trim();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/conformance/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * `agent-app-conformance` — the basics every deployed agent app must do, checked against its production origin:\n * sign in, read the served revision, answer a plain turn, and answer a turn only the workspace computer can.\n * It prints one JSON line per check as the check ends: app, url, check, status, ms, and the cause of a failure.\n *\n * agent-app-conformance --app-url https://gtm.tangle.tools --auth password --workspace \"GTM release canary\"\n *\n * The member comes from the environment so it never reaches a process listing:\n * CONFORMANCE_EMAIL, CONFORMANCE_PASSWORD the canary member (--email / --password are accepted but visible to `ps`)\n * CONFORMANCE_OPERATOR_KEY optional: an operator key with operator:read and operator:run;\n * without one the signed-in member mints an hour-long key and revokes it\n *\n * Options:\n * --app-url <origin> required\n * --app <label> names the app in each line (default: the origin's first host label)\n * --auth password|sso how the member signs in (default password); sso goes through Tangle Platform\n * --workspace <id|name> the canary or smoke workspace the turns run in (default: the key's only workspace)\n * --computer digest|file digest: hash a fresh nonce on the computer; file: the computer saves a file the app serves back\n * --computer-model <id> the computer turn's model (default glm-5.3, flat-rate); the plain turn keeps the app's model\n * --file-dir <dir> where the file proof is saved (default proof)\n * --turn-ms <ms> the budget of each turn, a cold box included (default 300000)\n * --expect-revision <sha> fail unless the served revision matches\n *\n * Exits 0 when every check passes, 1 when any fails or is blocked, 2 on a usage error.\n */\nimport { invokedAsScript } from '../signoff/invoked-as-script.js'\nimport { checkDeployedApp, type ConformanceOptions } from './run.js'\nimport type { ComputerProof } from './turns.js'\nimport type { SignInMode } from './session.js'\n\nconst VALUE_FLAGS = new Set(['--app-url', '--app', '--auth', '--email', '--password', '--workspace', '--computer', '--computer-model', '--file-dir', '--turn-ms', '--expect-revision'])\n\nfunction parseConformanceArgs(argv: readonly string[], env: NodeJS.ProcessEnv = process.env): ConformanceOptions {\n const flags = new Map<string, string>()\n for (let index = 0; index < argv.length; index += 1) {\n const [flag = '', inline] = argv[index]!.split(/=(.*)/s, 2)\n if (!VALUE_FLAGS.has(flag)) throw new Error(`unknown option ${argv[index]}`)\n const value = inline ?? argv[++index]\n if (value === undefined || value === '') throw new Error(`${flag} needs a value`)\n flags.set(flag, value)\n }\n const url = flags.get('--app-url')\n if (!url) throw new Error('--app-url is required')\n let origin: URL\n try { origin = new URL(url) } catch { throw new Error(`--app-url is not a URL: ${url}`) }\n if (origin.protocol !== 'https:') throw new Error('--app-url must be an https origin')\n const mode = flags.get('--auth') ?? 'password'\n if (mode !== 'password' && mode !== 'sso') throw new Error('--auth is password or sso')\n const computer = flags.get('--computer') ?? 'digest'\n if (computer !== 'digest' && computer !== 'file') throw new Error('--computer is digest or file')\n const turnMs = Number(flags.get('--turn-ms') ?? 300_000)\n if (!Number.isFinite(turnMs) || turnMs < 1_000) throw new Error('--turn-ms is a number of milliseconds, at least 1000')\n const email = flags.get('--email') ?? env.CONFORMANCE_EMAIL?.trim()\n const password = flags.get('--password') ?? env.CONFORMANCE_PASSWORD\n const operatorKey = env.CONFORMANCE_OPERATOR_KEY?.trim()\n return {\n app: flags.get('--app') ?? origin.hostname.split('.')[0]!,\n origin: origin.origin,\n ...(email && password ? { member: { mode: mode as SignInMode, email, password } } : {}),\n ...(operatorKey ? { operatorKey } : {}),\n ...(flags.has('--workspace') ? { workspace: flags.get('--workspace')! } : {}),\n computer: computer as ComputerProof,\n ...(flags.has('--computer-model') ? { computerModel: flags.get('--computer-model')! } : {}),\n ...(flags.has('--file-dir') ? { fileDir: flags.get('--file-dir')! } : {}),\n turnMs,\n ...(flags.has('--expect-revision') ? { expectRevision: flags.get('--expect-revision')! } : {}),\n }\n}\n\nasync function main(): Promise<number> {\n let options: ConformanceOptions\n try {\n options = parseConformanceArgs(process.argv.slice(2))\n } catch (error) {\n console.error(`agent-app-conformance: ${error instanceof Error ? error.message : String(error)}`)\n return 2\n }\n const results = await checkDeployedApp({ ...options, onResult: result => process.stdout.write(`${JSON.stringify(result)}\\n`) })\n return results.every(result => result.status === 'pass') ? 0 : 1\n}\n\nif (invokedAsScript(import.meta.url, process.argv[1])) {\n main().then(code => process.stdout.write('', () => process.exit(code)))\n}\n"],"mappings":";;;;;;;;;;;AA+BA,IAAM,cAAc,oBAAI,IAAI,CAAC,aAAa,SAAS,UAAU,WAAW,cAAc,eAAe,cAAc,oBAAoB,cAAc,aAAa,mBAAmB,CAAC;AAEtL,SAAS,qBAAqB,MAAyB,MAAyB,QAAQ,KAAyB;AAC/G,QAAM,QAAQ,oBAAI,IAAoB;AACtC,WAAS,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS,GAAG;AACnD,UAAM,CAAC,OAAO,IAAI,MAAM,IAAI,KAAK,KAAK,EAAG,MAAM,UAAU,CAAC;AAC1D,QAAI,CAAC,YAAY,IAAI,IAAI,EAAG,OAAM,IAAI,MAAM,kBAAkB,KAAK,KAAK,CAAC,EAAE;AAC3E,UAAM,QAAQ,UAAU,KAAK,EAAE,KAAK;AACpC,QAAI,UAAU,UAAa,UAAU,GAAI,OAAM,IAAI,MAAM,GAAG,IAAI,gBAAgB;AAChF,UAAM,IAAI,MAAM,KAAK;AAAA,EACvB;AACA,QAAM,MAAM,MAAM,IAAI,WAAW;AACj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AAM,IAAI,YAAY,EAAG,IAAI,CAAC;AAAA,IACvE;AAAA,IACA,GAAI,MAAM,IAAI,mBAAmB,IAAI,EAAE,gBAAgB,MAAM,IAAI,mBAAmB,EAAG,IAAI,CAAC;AAAA,EAC9F;AACF;AAEA,eAAe,OAAwB;AACrC,MAAI;AACJ,MAAI;AACF,cAAU,qBAAqB,QAAQ,KAAK,MAAM,CAAC,CAAC;AAAA,EACtD,SAAS,OAAO;AACd,YAAQ,MAAM,0BAA0B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AAChG,WAAO;AAAA,EACT;AACA,QAAM,UAAU,MAAM,iBAAiB,EAAE,GAAG,SAAS,UAAU,YAAU,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,MAAM,CAAC;AAAA,CAAI,EAAE,CAAC;AAC9H,SAAO,QAAQ,MAAM,YAAU,OAAO,WAAW,MAAM,IAAI,IAAI;AACjE;AAEA,IAAI,gBAAgB,YAAY,KAAK,QAAQ,KAAK,CAAC,CAAC,GAAG;AACrD,OAAK,EAAE,KAAK,UAAQ,QAAQ,OAAO,MAAM,IAAI,MAAM,QAAQ,KAAK,IAAI,CAAC,CAAC;AACxE;","names":[]}
1
+ {"version":3,"sources":["../../src/conformance/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * `agent-app-conformance` — the basics every deployed agent app must do, checked against its production origin:\n * sign in, read the served revision, answer a plain turn, and answer a turn only the workspace computer can.\n * It prints one JSON line per check as the check ends: app, url, check, status, ms, and the cause of a failure.\n *\n * agent-app-conformance --app-url https://gtm.tangle.tools --auth password --workspace \"GTM release canary\"\n *\n * The member comes from the environment so it never reaches a process listing:\n * CONFORMANCE_EMAIL, CONFORMANCE_PASSWORD the canary member (--email / --password are accepted but visible to `ps`)\n * CONFORMANCE_OPERATOR_KEY optional: an operator key with operator:read and operator:run;\n * without one the signed-in member mints an hour-long key and revokes it\n *\n * Options:\n * --app-url <origin> required\n * --app <label> names the app in each line (default: the origin's first host label)\n * --auth password|sso how the member signs in (default password); sso goes through Tangle Platform\n * --workspace <id|name> the canary or smoke workspace the turns run in (default: the key's only workspace)\n * --computer digest|file|none digest: hash a fresh nonce on the computer; file: the computer saves a file the app\n * serves back; none: the plain turn only (one ask, for a post-serve first-ask check)\n * --computer-model <id> the computer turn's model (default glm-5.3, flat-rate); the plain turn keeps the app's model\n * --file-dir <dir> where the file proof is saved (default proof)\n * --turn-ms <ms> the budget of each turn, a cold box included (default 300000)\n * --expect-revision <sha> fail unless the served revision matches\n *\n * Exits 0 when every check passes, 1 when any fails or is blocked, 2 on a usage error.\n */\nimport { invokedAsScript } from '../signoff/invoked-as-script.js'\nimport { checkDeployedApp, type ConformanceOptions } from './run.js'\nimport type { ComputerProof } from './turns.js'\nimport type { SignInMode } from './session.js'\n\nconst VALUE_FLAGS = new Set(['--app-url', '--app', '--auth', '--email', '--password', '--workspace', '--computer', '--computer-model', '--file-dir', '--turn-ms', '--expect-revision'])\n\nfunction parseConformanceArgs(argv: readonly string[], env: NodeJS.ProcessEnv = process.env): ConformanceOptions {\n const flags = new Map<string, string>()\n for (let index = 0; index < argv.length; index += 1) {\n const [flag = '', inline] = argv[index]!.split(/=(.*)/s, 2)\n if (!VALUE_FLAGS.has(flag)) throw new Error(`unknown option ${argv[index]}`)\n const value = inline ?? argv[++index]\n if (value === undefined || value === '') throw new Error(`${flag} needs a value`)\n flags.set(flag, value)\n }\n const url = flags.get('--app-url')\n if (!url) throw new Error('--app-url is required')\n let origin: URL\n try { origin = new URL(url) } catch { throw new Error(`--app-url is not a URL: ${url}`) }\n if (origin.protocol !== 'https:') throw new Error('--app-url must be an https origin')\n const mode = flags.get('--auth') ?? 'password'\n if (mode !== 'password' && mode !== 'sso') throw new Error('--auth is password or sso')\n const computer = flags.get('--computer') ?? 'digest'\n if (computer !== 'digest' && computer !== 'file' && computer !== 'none') throw new Error('--computer is digest, file or none')\n const turnMs = Number(flags.get('--turn-ms') ?? 300_000)\n if (!Number.isFinite(turnMs) || turnMs < 1_000) throw new Error('--turn-ms is a number of milliseconds, at least 1000')\n const email = flags.get('--email') ?? env.CONFORMANCE_EMAIL?.trim()\n const password = flags.get('--password') ?? env.CONFORMANCE_PASSWORD\n const operatorKey = env.CONFORMANCE_OPERATOR_KEY?.trim()\n return {\n app: flags.get('--app') ?? origin.hostname.split('.')[0]!,\n origin: origin.origin,\n ...(email && password ? { member: { mode: mode as SignInMode, email, password } } : {}),\n ...(operatorKey ? { operatorKey } : {}),\n ...(flags.has('--workspace') ? { workspace: flags.get('--workspace')! } : {}),\n computer: computer as ComputerProof | 'none',\n ...(flags.has('--computer-model') ? { computerModel: flags.get('--computer-model')! } : {}),\n ...(flags.has('--file-dir') ? { fileDir: flags.get('--file-dir')! } : {}),\n turnMs,\n ...(flags.has('--expect-revision') ? { expectRevision: flags.get('--expect-revision')! } : {}),\n }\n}\n\nasync function main(): Promise<number> {\n let options: ConformanceOptions\n try {\n options = parseConformanceArgs(process.argv.slice(2))\n } catch (error) {\n console.error(`agent-app-conformance: ${error instanceof Error ? error.message : String(error)}`)\n return 2\n }\n const results = await checkDeployedApp({ ...options, onResult: result => process.stdout.write(`${JSON.stringify(result)}\\n`) })\n return results.every(result => result.status === 'pass') ? 0 : 1\n}\n\nif (invokedAsScript(import.meta.url, process.argv[1])) {\n main().then(code => process.stdout.write('', () => process.exit(code)))\n}\n"],"mappings":";;;;;;;;;;;AAgCA,IAAM,cAAc,oBAAI,IAAI,CAAC,aAAa,SAAS,UAAU,WAAW,cAAc,eAAe,cAAc,oBAAoB,cAAc,aAAa,mBAAmB,CAAC;AAEtL,SAAS,qBAAqB,MAAyB,MAAyB,QAAQ,KAAyB;AAC/G,QAAM,QAAQ,oBAAI,IAAoB;AACtC,WAAS,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS,GAAG;AACnD,UAAM,CAAC,OAAO,IAAI,MAAM,IAAI,KAAK,KAAK,EAAG,MAAM,UAAU,CAAC;AAC1D,QAAI,CAAC,YAA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,cAAc,EAAE,YAAY,IAAI,CAAC;AAAA,IACrC,GAAI,MAAM,IAAI,aAAa,IAAI,EAAE,WAAW,MAAM,IAAI,aAAa,EAAG,IAAI,CAAC;AAAA,IAC3E;AAAA,IACA,GAAI,MAAM,IAAI,kBAAkB,IAAI,EAAE,eAAe,MAAM,IAAI,kBAAkB,EAAG,IAAI,CAAC;AAAA,IACzF,GAAI,MAAM,IAAI,YAAY,IAAI,EAAE,SAAS,MAAM,IAAI,YAAY,EAAG,IAAI,CAAC;AAAA,IACvE;AAAA,IACA,GAAI,MAAM,IAAI,mBAAmB,IAAI,EAAE,gBAAgB,MAAM,IAAI,mBAAmB,EAAG,IAAI,CAAC;AAAA,EAC9F;AACF;AAEA,eAAe,OAAwB;AACrC,MAAI;AACJ,MAAI;AACF,cAAU,qBAAqB,QAAQ,KAAK,MAAM,CAAC,CAAC;AAAA,EACtD,SAAS,OAAO;AACd,YAAQ,MAAM,0BAA0B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AAChG,WAAO;AAAA,EACT;AACA,QAAM,UAAU,MAAM,iBAAiB,EAAE,GAAG,SAAS,UAAU,YAAU,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,MAAM,CAAC;AAAA,CAAI,EAAE,CAAC;AAC9H,SAAO,QAAQ,MAAM,YAAU,OAAO,WAAW,MAAM,IAAI,IAAI;AACjE;AAEA,IAAI,gBAAgB,YAAY,KAAK,QAAQ,KAAK,CAAC,CAAC,GAAG;AACrD,OAAK,EAAE,KAAK,UAAQ,QAAQ,OAAO,MAAM,IAAI,MAAM,QAAQ,KAAK,IAAI,CAAC,CAAC;AACxE;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  checkDeployedApp
3
- } from "../chunk-PABZALSD.js";
3
+ } from "../chunk-LBMFQLBS.js";
4
4
  import "../chunk-EI27JMS6.js";
5
5
  import "../chunk-RN4WPTBH.js";
6
6
  export {
@@ -33,8 +33,9 @@ export interface ConformanceOptions {
33
33
  operatorKey?: string;
34
34
  /** Id or exact name of the workspace the turns run in: the app's canary or smoke workspace, never a customer's. */
35
35
  workspace?: string;
36
- /** `digest` hashes a fresh nonce on the workspace computer; `file` has the computer save a file the app serves back. */
37
- computer?: ComputerProof;
36
+ /** `digest` hashes a fresh nonce on the workspace computer; `file` has the computer save a file the app serves back;
37
+ * `none` runs the plain turn only, for a check that asks exactly once (a post-serve first ask). */
38
+ computer?: ComputerProof | 'none';
38
39
  /** The computer turn's model. The plain turn keeps the app's own model, so the served model is still checked once. */
39
40
  computerModel?: string;
40
41
  /** Where the `file` proof is saved, relative to the workspace root. */
@@ -31,7 +31,7 @@ import type { AppToolHandlers } from '../tools/index.js';
31
31
  import type { KvLike } from '../web/index.js';
32
32
  export { ensureCloudflareWorkflowInstance, type CloudflareWorkflowBindingLike, type CloudflareWorkflowInstanceLike, type EnsureCloudflareWorkflowInstanceResult, } from './workflow-instance.js';
33
33
  export { runDetachedTurnWorkflowTick, SANDBOX_TRANSIENT_TICK_POLICY, type DetachedTurnTransientPolicy, type CloudflareWorkflowEventLike, type CloudflareWorkflowSleepDuration, type CloudflareWorkflowStepLike, type DetachedTurnDriveOutcome, type DetachedTurnDriveState, type DetachedTurnTerminalResult, type DetachedTurnWorkflowIdentity, type DetachedTurnWorkflowTickOptions, } from './detached-turn-workflow.js';
34
- export { runNativeCompletionWorkflow, type NativeCompletionWorkflowOptions, type NativeCompletionWorkflowPayload, } from './native-completion-workflow.js';
34
+ export { runNativeCompletionWorkflow, type NativeCompletionWorkflowOptions, type NativeCompletionWorkflowPayload, type NativeCompletionWorkflowResult, type NativeCompletionTranscriptReference, } from './native-completion-workflow.js';
35
35
  export * from './native-completion-store.js';
36
36
  export * from './native-completion-owner.js';
37
37
  export { renderCloudflareHeadersFile, type CloudflareHeadersRule, } from './headers.js';