@tangle-network/agent-app 0.60.131 → 0.60.132

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.
@@ -599,7 +599,13 @@ function createIdentityBoundWorkspaceKeyManager(options) {
599
599
  if (active) {
600
600
  const key = await options.crypto.decrypt(active.row.keyEncrypted);
601
601
  if (!key.trim()) throw new Error("workspace child key secret is empty");
602
- return { key, usage: active.usage, refreshed: false };
602
+ if (Date.parse(active.usage.expiresAt) > now().getTime()) return { key, usage: active.usage, refreshed: false };
603
+ await options.store.markRevocationPending({
604
+ id: active.row.id,
605
+ error: "active child key expired while it was read",
606
+ nextAttemptAt: now(),
607
+ incrementAttempts: false
608
+ });
603
609
  }
604
610
  const finalCleanup = await retryPendingRevocationsUnlocked(identity, identity);
605
611
  if (finalCleanup.pending > 0) throw new Error("a previous workspace child-key cleanup is pending; issuance is blocked until it completes");
@@ -787,4 +793,4 @@ export {
787
793
  createPlatformBalanceManager,
788
794
  createWorkspaceKeyManager
789
795
  };
790
- //# sourceMappingURL=chunk-LJDMPYGA.js.map
796
+ //# sourceMappingURL=chunk-YJHE73TF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/billing/crypto-probe.ts","../src/billing/identity-bound.ts","../src/billing/index.ts"],"sourcesContent":["import type { KeyCrypto } from './index'\n\n/** Prove the at-rest crypto seam before a remote key is minted. */\nexport async function assertWorkspaceKeyCryptoUsable(crypto: KeyCrypto): Promise<void> {\n const probe = 'agent-app:key-manager:crypto-probe'\n let roundTripped: string\n try {\n roundTripped = await crypto.decrypt(await crypto.encrypt(probe))\n } catch (error) {\n throw new Error(\n 'Key encryption is misconfigured: the crypto seam threw before minting. ' +\n 'Validate FIELD_ENCRYPTION_KEY (64-char hex) at startup. No platform key was minted.',\n { cause: error },\n )\n }\n if (roundTripped !== probe) {\n throw new Error(\n 'Key encryption is misconfigured: encrypt/decrypt round-trip did not preserve the plaintext. ' +\n 'No platform key was minted.',\n )\n }\n}\n","import { assertWorkspaceKeyCryptoUsable } from './crypto-probe'\nimport type { KeyCrypto, KeyProvisioner } from './index'\n\n/** Lifecycle state for a durable delegated key row. */\nexport type WorkspaceKeyStatus =\n | 'legacy'\n | 'provisioning'\n | 'active'\n | 'revocation_pending'\n | 'revoked'\n | 'orphaned'\n\n/** Product partition used by the key store and remote provisioner. */\nexport type WorkspaceKeyProduct = string\n\n/** The identity fields that bind a child key to its paying owner and source. */\nexport interface WorkspaceKeyIdentity {\n workspaceId: string\n ownerUserId: string\n platformUserId: string\n sourceKeyId?: string | null\n /** A non-secret digest of the source credential. */\n sourceKeyFingerprint: string\n}\n\n/** A product/workspace/owner lookup scope. */\nexport interface DurableWorkspaceKeyScope {\n workspaceId: string\n ownerUserId: string\n product: WorkspaceKeyProduct\n}\n\n/** A persisted child-key row owned by this manager. */\nexport interface DurableWorkspaceKeyRecord {\n id: string\n workspaceId: string\n ownerUserId: string\n product: WorkspaceKeyProduct\n platformUserId: string\n sourceKeyId: string | null\n sourceKeyFingerprint: string\n /** The persisted name used to recover a remote create after a crash. Null only for pre-name rows. */\n name: string | null\n /** The persisted retry identity for the remote create. Absent on legacy rows without a persisted create identity. */\n idempotencyKey?: string | null\n keyId: string\n keyEncrypted: string\n budgetUsd: number\n expiresAt: Date\n status: WorkspaceKeyStatus\n revocationAttempts: number\n nextRevocationAt: Date | null\n lastRevocationError: string | null\n createdAt: Date\n}\n\n/** A row that has been written before its remote child key exists. */\nexport interface DurableWorkspaceKeyProvisioningRecord extends DurableWorkspaceKeyRecord {\n status: 'provisioning'\n}\n\ntype DurableWorkspaceKeyCreateResult = Awaited<ReturnType<KeyProvisioner['createKey']>> & {\n budgetUsd?: number | null\n budgetRemaining?: number\n expiresAt?: string | null\n}\n\n/** The exact request identity that must be reused when recovering a create. */\nexport interface DurableWorkspaceKeyCreateInput {\n name: string\n product: string\n budgetUsd: number\n expiresAt: string\n /** Stable across process restarts for one persisted provisioning row. */\n idempotencyKey: string\n}\n\n/** The remote operations required by the durable manager. */\nexport interface DurableWorkspaceKeyProvisioner {\n /** True only when replay returns the original child for the persisted request identity. */\n supportsIdempotentCreate?: true\n /** Create one child key. Non-idempotent providers recover through stable-name discovery only. */\n createKey(input: DurableWorkspaceKeyCreateInput): Promise<DurableWorkspaceKeyCreateResult>\n getKey(id: string): Promise<{\n budgetUsd?: number | null\n budgetSpent?: number\n expiresAt?: string | null\n }>\n revokeKey: KeyProvisioner['revokeKey']\n /** Find remote keys for a specific persisted provisioning attempt. */\n findCreatedKeys(input: {\n name: string\n product: string\n sourceKeyId?: string | null\n }): Promise<Array<{ id: string }>>\n}\n\n/** Optional compare-and-set lifecycle writes for stores that support fencing. */\nexport interface DurableWorkspaceKeyConditionalWrites {\n /** Return false when the row was no longer provisioning. */\n markProvisioningRemote(input: { id: string; keyId: string }): Promise<boolean>\n /** Return false when the row was no longer provisioning. */\n markActive(input: {\n id: string\n keyId: string\n keyEncrypted: string\n expiresAt: Date\n budgetUsd: number\n }): Promise<boolean>\n}\n\n/** Persistence operations for identity-bound key lifecycle state. */\nexport interface DurableWorkspaceKeyStore {\n /** Return the active row for this exact product scope. */\n getActive(scope: DurableWorkspaceKeyScope): Promise<DurableWorkspaceKeyRecord | null>\n /** Return every unfinished provisioning row for this exact product scope. */\n listProvisioning(scope: DurableWorkspaceKeyScope): Promise<DurableWorkspaceKeyProvisioningRecord[]>\n /** Insert before the remote create so a crashed create can be recovered. */\n insertProvisioning(record: DurableWorkspaceKeyProvisioningRecord): Promise<void>\n /** Save the remote id while the row remains in provisioning state. */\n markProvisioningRemote(input: { id: string; keyId: string }): Promise<void>\n /** Promote a fully encrypted row to active state. */\n markActive(input: {\n id: string\n keyId: string\n keyEncrypted: string\n expiresAt: Date\n budgetUsd: number\n }): Promise<void>\n /**\n * Optional fenced writes. The manager uses false to compensate a stale\n * creator. Stores without this field retain the pre-fence behavior.\n */\n conditionalWrites?: DurableWorkspaceKeyConditionalWrites\n /** Keep a failed cleanup visible and schedule a later retry. Terminal rows are immutable. */\n markRevocationPending(input: {\n id: string\n error?: string | null\n nextAttemptAt: Date\n incrementAttempts: boolean\n }): Promise<void>\n /** Mark a remote key as revoked. Missing remote keys count as revoked. */\n markRevoked(id: string, now: Date): Promise<void>\n /** Mark a provisioning row terminal when no remote key remains to clean. */\n markOrphaned(id: string, error: string): Promise<void>\n /** Query due cleanup rows. The implementation should filter by the supplied scope. */\n listPendingRevocations(input: {\n product: WorkspaceKeyProduct\n workspaceId?: string\n ownerUserId?: string\n now: Date\n limit: number\n /** Include rows scheduled for a later retry when checking before issuance. */\n includeFuture?: boolean\n }): Promise<DurableWorkspaceKeyRecord[]>\n /** Acquire a cross-process lease for one product/workspace/owner scope. */\n acquireLease(scope: string, operationId: string, now: Date, leaseMs: number): Promise<boolean>\n /** Renew an acquired lease before its expiry. */\n renewLease(scope: string, operationId: string, now: Date, leaseMs: number): Promise<boolean>\n /** Release an acquired lease. */\n releaseLease(scope: string, operationId: string): Promise<void>\n}\n\n/** Live budget information for a child key. */\nexport interface WorkspaceKeyUsage {\n keyId: string\n budgetUsd: number\n budgetSpent: number\n budgetRemaining: number\n expiresAt: string\n exhausted: boolean\n}\n\n/** The decrypted key plus the usage snapshot used to issue it. */\nexport interface WorkspaceRuntimeKey {\n key: string\n usage: WorkspaceKeyUsage\n /** True when this call minted a new remote key. */\n refreshed: boolean\n}\n\n/** Identity-bound durable key manager API. */\nexport interface DurableWorkspaceKeyManager {\n /** Reuse a matching active key or reconcile and mint one under a lease. */\n ensureKey(identity: WorkspaceKeyIdentity, options?: { budgetUsd?: number }): Promise<WorkspaceRuntimeKey>\n /** Read usage without returning the child secret. */\n getUsage(identity: WorkspaceKeyIdentity): Promise<WorkspaceKeyUsage | null>\n /**\n * Retry due cleanup rows. A supplied owner/workspace limits the retry to its\n * scope. Empty provisioning rows also require the full identity so a retry\n * can use the original source binding safely.\n */\n retryPendingRevocations(\n scope?: Pick<WorkspaceKeyIdentity, 'ownerUserId' | 'workspaceId'>,\n identity?: WorkspaceKeyIdentity,\n ): Promise<number>\n}\n\n/** Configuration for {@link createIdentityBoundWorkspaceKeyManager}. */\nexport interface DurableWorkspaceKeyManagerOptions {\n store: DurableWorkspaceKeyStore\n provisioner: DurableWorkspaceKeyProvisioner\n /**\n * Control-plane client for historical get/revoke/list operations. Use this\n * when the source credential can rotate or disappear. It never mints keys.\n */\n recoveryProvisioner?: Pick<DurableWorkspaceKeyProvisioner, 'getKey' | 'revokeKey' | 'findCreatedKeys'>\n crypto: KeyCrypto\n /** Product partition. Products must use separate values. */\n product: WorkspaceKeyProduct\n defaultBudgetUsd: number\n now?: () => Date\n /** Local lifetime used when the remote response omits an expiry. */\n keyLifetimeMs?: number\n /** Lease lifetime for remote operations. */\n leaseMs?: number\n /** Maximum time to wait for another issuer to release the scope lease. */\n leaseWaitMs?: number\n /** Poll delay while waiting for a scope lease. */\n leasePollMs?: number\n /** Renewal interval. It must be shorter than `leaseMs`. */\n leaseRenewIntervalMs?: number\n /** Initial delay for a failed remote revoke. */\n revocationRetryBaseMs?: number\n /** Maximum delay for a failed remote revoke. */\n revocationRetryMaxMs?: number\n /** Stable remote name. The operation id makes the default crash-safe. */\n nameForIdentity?: (identity: WorkspaceKeyIdentity, operationId: string) => string\n /** Resolve names for rows written before `name` became durable. Null blocks issuance safely. */\n legacyNameForRecord?: (record: DurableWorkspaceKeyRecord) => string | null | undefined\n /** Recognize a missing remote key without depending on a provider SDK. */\n isRemoteMissing?: (error: unknown) => boolean\n}\n\nconst DEFAULT_KEY_LIFETIME_MS = 55 * 60_000\nconst DEFAULT_LEASE_MS = 60_000\nconst DEFAULT_LEASE_WAIT_MS = 15_000\nconst DEFAULT_LEASE_POLL_MS = 50\nconst DEFAULT_LEASE_RENEW_INTERVAL_MS = Math.floor(DEFAULT_LEASE_MS / 3)\nconst DEFAULT_REVOCATION_RETRY_BASE_MS = 2_000\nconst DEFAULT_REVOCATION_RETRY_MAX_MS = 60_000\nconst PENDING_REVOCATION_BATCH_SIZE = 20\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction operationId(): string {\n return globalThis.crypto.randomUUID()\n}\n\nfunction requirePositive(value: number, label: string): number {\n if (!Number.isFinite(value) || value <= 0) throw new Error(`${label} must be a positive finite number`)\n return value\n}\n\nfunction requireNonNegative(value: number, label: string): number {\n if (!Number.isFinite(value) || value < 0) throw new Error(`${label} must be a non-negative finite number`)\n return value\n}\n\nfunction normalizeIdentity(identity: WorkspaceKeyIdentity): WorkspaceKeyIdentity {\n const workspaceId = identity.workspaceId.trim()\n const ownerUserId = identity.ownerUserId.trim()\n const platformUserId = identity.platformUserId.trim()\n const sourceKeyFingerprint = identity.sourceKeyFingerprint.trim()\n const sourceKeyId = identity.sourceKeyId?.trim() || null\n if (!workspaceId || !ownerUserId || !platformUserId || !sourceKeyFingerprint) {\n throw new Error('workspace child key identity is incomplete')\n }\n return { workspaceId, ownerUserId, platformUserId, sourceKeyId, sourceKeyFingerprint }\n}\n\nfunction scopeFor(identity: Pick<WorkspaceKeyIdentity, 'workspaceId' | 'ownerUserId'>, product: string): DurableWorkspaceKeyScope {\n return { workspaceId: identity.workspaceId, ownerUserId: identity.ownerUserId, product }\n}\n\nfunction scopeKey(scope: DurableWorkspaceKeyScope): string {\n return JSON.stringify([scope.product, scope.workspaceId, scope.ownerUserId])\n}\n\nfunction safeNamePart(value: string): string {\n const normalized = value.replace(/[^A-Za-z0-9._-]/g, '-').replace(/-+/g, '-')\n return normalized.slice(0, 80) || 'unknown'\n}\n\nfunction defaultKeyName(identity: WorkspaceKeyIdentity, product: string, operationId: string): string {\n return `agent-app:${safeNamePart(product)}:${safeNamePart(identity.workspaceId)}:${safeNamePart(identity.platformUserId)}:${operationId}`\n}\n\nfunction sourceKeyId(identity: WorkspaceKeyIdentity): string | null {\n return identity.sourceKeyId?.trim() || null\n}\n\nfunction sameIdentity(row: DurableWorkspaceKeyRecord, identity: WorkspaceKeyIdentity, product: string): boolean {\n return row.workspaceId === identity.workspaceId\n && row.ownerUserId === identity.ownerUserId\n && row.product === product\n && row.platformUserId === identity.platformUserId\n && row.sourceKeyId === sourceKeyId(identity)\n && row.sourceKeyFingerprint === identity.sourceKeyFingerprint\n}\n\nfunction sameRowIdentity(a: DurableWorkspaceKeyRecord, b: DurableWorkspaceKeyRecord): boolean {\n return a.workspaceId === b.workspaceId\n && a.ownerUserId === b.ownerUserId\n && a.product === b.product\n && a.platformUserId === b.platformUserId\n && a.sourceKeyId === b.sourceKeyId\n && a.sourceKeyFingerprint === b.sourceKeyFingerprint\n}\n\nfunction errorMessage(error: unknown, fallback: string): string {\n return (error instanceof Error ? error.message : fallback)\n .replace(/Bearer\\s+[^\\s,;]+/gi, 'Bearer [redacted]')\n .replace(/((?:authorization|api[-_ ]?key|token|secret|password)\\s*[:=]\\s*)(?!Bearer\\b)[^\\s,;]+/gi, '$1[redacted]')\n .slice(0, 240)\n}\n\nfunction isProvisioningId(value: string): boolean {\n return value.startsWith('provisioning:')\n}\n\nasync function markProvisioningRemote(\n store: DurableWorkspaceKeyStore,\n input: { id: string; keyId: string },\n): Promise<boolean> {\n if (store.conditionalWrites) return store.conditionalWrites.markProvisioningRemote(input)\n await store.markProvisioningRemote(input)\n return true\n}\n\nasync function markActive(\n store: DurableWorkspaceKeyStore,\n input: {\n id: string\n keyId: string\n keyEncrypted: string\n expiresAt: Date\n budgetUsd: number\n },\n): Promise<boolean> {\n if (store.conditionalWrites) return store.conditionalWrites.markActive(input)\n await store.markActive(input)\n return true\n}\n\nfunction usageFromRemote(\n row: DurableWorkspaceKeyRecord,\n remote: Awaited<ReturnType<DurableWorkspaceKeyProvisioner['getKey']>>,\n now: Date,\n): WorkspaceKeyUsage {\n const budgetUsd = remote.budgetUsd ?? row.budgetUsd\n const budgetSpent = remote.budgetSpent ?? 0\n if (!Number.isFinite(budgetUsd) || budgetUsd < 0) throw new Error('workspace child key budget is malformed')\n if (!Number.isFinite(budgetSpent) || budgetSpent < 0) throw new Error('workspace child key usage is malformed')\n const expiresAt = remote.expiresAt ?? row.expiresAt.toISOString()\n const expiryMs = Date.parse(expiresAt)\n if (!Number.isFinite(expiryMs)) throw new Error('workspace child key expiry is malformed')\n const budgetRemaining = Math.max(0, budgetUsd - budgetSpent)\n return {\n keyId: row.keyId,\n budgetUsd,\n budgetSpent,\n budgetRemaining,\n expiresAt,\n exhausted: budgetRemaining <= 0 || expiryMs <= now.getTime(),\n }\n}\n\nfunction defaultRemoteMissing(error: unknown): boolean {\n const value = error as { status?: unknown; code?: unknown } | null\n return value?.status === 404 || value?.code === 'not_found'\n}\n\n/**\n * Create a product-neutral manager for child-key issuance and cleanup.\n *\n * The provisioner must already be authenticated for the current source\n * credential. The manager persists only the source id and its non-secret\n * fingerprint, then refuses to reuse a row from another identity.\n */\nexport function createIdentityBoundWorkspaceKeyManager(\n options: DurableWorkspaceKeyManagerOptions,\n): DurableWorkspaceKeyManager {\n const product = options.product.trim()\n if (!product) throw new Error('workspace child key product is required')\n const defaultBudgetUsd = requirePositive(options.defaultBudgetUsd, 'defaultBudgetUsd')\n const keyLifetimeMs = requirePositive(options.keyLifetimeMs ?? DEFAULT_KEY_LIFETIME_MS, 'keyLifetimeMs')\n const leaseMs = requirePositive(options.leaseMs ?? DEFAULT_LEASE_MS, 'leaseMs')\n const leaseWaitMs = requireNonNegative(options.leaseWaitMs ?? DEFAULT_LEASE_WAIT_MS, 'leaseWaitMs')\n const leasePollMs = requirePositive(options.leasePollMs ?? DEFAULT_LEASE_POLL_MS, 'leasePollMs')\n const leaseRenewIntervalMs = requirePositive(\n options.leaseRenewIntervalMs ?? Math.min(DEFAULT_LEASE_RENEW_INTERVAL_MS, Math.floor(leaseMs / 3)),\n 'leaseRenewIntervalMs',\n )\n if (leaseRenewIntervalMs >= leaseMs) throw new Error('leaseRenewIntervalMs must be shorter than leaseMs')\n const revocationRetryBaseMs = requirePositive(\n options.revocationRetryBaseMs ?? DEFAULT_REVOCATION_RETRY_BASE_MS,\n 'revocationRetryBaseMs',\n )\n const revocationRetryMaxMs = requirePositive(\n options.revocationRetryMaxMs ?? DEFAULT_REVOCATION_RETRY_MAX_MS,\n 'revocationRetryMaxMs',\n )\n if (revocationRetryMaxMs < revocationRetryBaseMs) throw new Error('revocationRetryMaxMs must cover the base delay')\n\n const now = options.now ?? (() => new Date())\n const isRemoteMissing = options.isRemoteMissing ?? defaultRemoteMissing\n const recoveryProvisioner = options.recoveryProvisioner ?? options.provisioner\n const localLocks = new Map<string, Promise<void>>()\n\n async function withLocalLock<T>(scope: string, work: () => Promise<T>): Promise<T> {\n const previous = localLocks.get(scope) ?? Promise.resolve()\n let release!: () => void\n const current = new Promise<void>((resolve) => { release = resolve })\n localLocks.set(scope, current)\n await previous\n try {\n return await work()\n } finally {\n release()\n if (localLocks.get(scope) === current) localLocks.delete(scope)\n }\n }\n\n async function withDurableLease<T>(\n scope: string,\n work: () => Promise<T>,\n onLeaseLost?: () => Promise<void>,\n ): Promise<T> {\n const leaseOperationId = operationId()\n const startedAt = Date.now()\n let acquired = false\n while (!acquired && Date.now() - startedAt <= leaseWaitMs) {\n acquired = await options.store.acquireLease(scope, leaseOperationId, now(), leaseMs)\n if (!acquired) await sleep(leasePollMs)\n }\n if (!acquired) throw new Error('workspace child-key issuance is busy; retry the request')\n\n let stopped = false\n let leaseLost: Error | null = null\n let leaseTimer: ReturnType<typeof setTimeout> | undefined\n let renewalPromise: Promise<void> | undefined\n const scheduleRenewal = () => {\n if (stopped || leaseLost) return\n leaseTimer = setTimeout(() => {\n leaseTimer = undefined\n const renewal = (async () => {\n try {\n if (!await options.store.renewLease(scope, leaseOperationId, now(), leaseMs)) {\n leaseLost = new Error('workspace child-key lease was lost during reconciliation')\n return\n }\n scheduleRenewal()\n } catch (error) {\n leaseLost = error instanceof Error ? error : new Error('workspace child-key lease renewal failed')\n }\n })()\n renewalPromise = renewal\n void renewal.finally(() => {\n if (renewalPromise === renewal) renewalPromise = undefined\n }).catch(() => undefined)\n }, leaseRenewIntervalMs)\n }\n scheduleRenewal()\n\n let workError: unknown\n let leaseLossCleanupError: unknown\n try {\n const result = await work()\n if (leaseLost) throw leaseLost\n return result\n } catch (error) {\n workError = error\n throw error\n } finally {\n stopped = true\n if (leaseTimer) clearTimeout(leaseTimer)\n if (renewalPromise) await renewalPromise\n if (leaseLost && onLeaseLost) {\n try {\n await onLeaseLost()\n } catch (error) {\n leaseLossCleanupError = error\n }\n }\n try {\n await options.store.releaseLease(scope, leaseOperationId)\n } catch (error) {\n if (workError === undefined) throw error\n }\n if (workError === undefined && leaseLossCleanupError) {\n throw new Error('workspace child-key lease was lost and cleanup failed', { cause: leaseLossCleanupError })\n }\n if (workError === undefined && leaseLost) throw leaseLost\n }\n }\n\n function retryDelay(attempts: number): number {\n return Math.min(revocationRetryMaxMs, revocationRetryBaseMs * 2 ** Math.min(Math.max(attempts - 1, 0), 5))\n }\n\n async function markPending(id: string, error: unknown, incrementAttempts: boolean): Promise<void> {\n const delay = incrementAttempts ? retryDelay(1) : 0\n await options.store.markRevocationPending({\n id,\n error: errorMessage(error, 'remote key cleanup failed'),\n nextAttemptAt: new Date(now().getTime() + delay),\n incrementAttempts,\n })\n }\n\n async function revokePending(row: DurableWorkspaceKeyRecord, identity?: WorkspaceKeyIdentity): Promise<boolean> {\n if (!row.keyId || isProvisioningId(row.keyId)) return cleanupProvisioning(row, identity)\n const active = await options.store.getActive({\n workspaceId: row.workspaceId,\n ownerUserId: row.ownerUserId,\n product: row.product,\n })\n if (active && active.id !== row.id && active.keyId === row.keyId) {\n await options.store.markRevoked(row.id, now())\n return true\n }\n try {\n await recoveryProvisioner.revokeKey(row.keyId)\n await options.store.markRevoked(row.id, now())\n return true\n } catch (error) {\n if (isRemoteMissing(error)) {\n await options.store.markRevoked(row.id, now())\n return true\n }\n await options.store.markRevocationPending({\n id: row.id,\n error: errorMessage(error, 'remote key revocation failed'),\n nextAttemptAt: new Date(now().getTime() + retryDelay(row.revocationAttempts + 1)),\n incrementAttempts: true,\n })\n return false\n }\n }\n\n async function provisioningCandidates(row: DurableWorkspaceKeyRecord): Promise<{\n name: string\n candidates: Array<{ id: string }>\n } | null> {\n if (row.keyId && !isProvisioningId(row.keyId)) {\n return { name: row.name?.trim() ?? '', candidates: [{ id: row.keyId }] }\n }\n const name = row.name?.trim() || options.legacyNameForRecord?.(row)?.trim()\n if (!name) return null\n return {\n name,\n candidates: await recoveryProvisioner.findCreatedKeys({\n name,\n product: row.product,\n sourceKeyId: row.sourceKeyId,\n }),\n }\n }\n\n async function probeProvisioning(\n row: DurableWorkspaceKeyRecord,\n identity: WorkspaceKeyIdentity | undefined,\n name: string,\n ): Promise<Array<{ id: string }> | null> {\n const idempotencyKey = row.idempotencyKey?.trim()\n if (!identity || !sameIdentity(row, identity, product)\n || !options.provisioner.supportsIdempotentCreate || !idempotencyKey) return []\n try {\n const created = await options.provisioner.createKey({\n name,\n product: row.product,\n budgetUsd: row.budgetUsd,\n expiresAt: row.expiresAt.toISOString(),\n idempotencyKey,\n })\n const remoteId = created.id?.trim()\n if (remoteId) return [{ id: remoteId }]\n } catch (error) {\n await options.store.markRevocationPending({\n id: row.id,\n error: errorMessage(error, 'remote provisioning recovery failed'),\n nextAttemptAt: new Date(now().getTime() + retryDelay(row.revocationAttempts + 1)),\n incrementAttempts: true,\n })\n return null\n }\n return (await provisioningCandidates({ ...row, name, keyId: `provisioning:${idempotencyKey}` }))?.candidates ?? []\n }\n\n async function cleanupProvisioning(row: DurableWorkspaceKeyRecord, identity?: WorkspaceKeyIdentity): Promise<boolean> {\n const resolved = await provisioningCandidates(row)\n if (!resolved) {\n await options.store.markRevocationPending({\n id: row.id,\n error: 'provisioning row has no recoverable remote name; migrate the row or configure legacyNameForRecord',\n nextAttemptAt: now(),\n incrementAttempts: false,\n })\n return false\n }\n let { name, candidates } = resolved\n if (candidates.length === 0) {\n const probed = await probeProvisioning(row, identity, name)\n if (probed === null) return false\n candidates = probed\n }\n\n const scope = { workspaceId: row.workspaceId, ownerUserId: row.ownerUserId, product: row.product }\n const active = await options.store.getActive(scope)\n const activeMatches = active && (identity ? sameIdentity(active, identity, product) : sameRowIdentity(active, row))\n const activeKeyId = activeMatches ? active.keyId : null\n const toRevoke = candidates\n .map((candidate) => candidate.id.trim())\n .filter((candidateId) => candidateId && candidateId !== activeKeyId)\n\n for (const keyId of toRevoke) {\n try {\n await recoveryProvisioner.revokeKey(keyId)\n } catch (error) {\n if (isRemoteMissing(error)) continue\n await options.store.markRevocationPending({\n id: row.id,\n error: errorMessage(error, 'remote provisioning cleanup failed'),\n nextAttemptAt: new Date(now().getTime() + retryDelay(row.revocationAttempts + 1)),\n incrementAttempts: true,\n })\n return false\n }\n }\n\n if (candidates.length > 0) {\n await options.store.markRevoked(row.id, now())\n } else {\n await options.store.markRevocationPending({\n id: row.id,\n error: 'no remote child matched the durable provisioning record; retrying crash recovery',\n nextAttemptAt: new Date(now().getTime() + retryDelay(row.revocationAttempts + 1)),\n incrementAttempts: true,\n })\n return false\n }\n return true\n }\n\n async function reconcileProvisioning(identity: WorkspaceKeyIdentity): Promise<void> {\n const scope = scopeFor(identity, product)\n const rows = await options.store.listProvisioning(scope)\n for (const row of rows) {\n if (!(await cleanupProvisioning(row, identity))) {\n throw new Error('a previous workspace child-key cleanup is pending; issuance is blocked until it completes')\n }\n }\n }\n\n async function retryPendingRevocationsUnlocked(\n scopeFilter?: Pick<WorkspaceKeyIdentity, 'ownerUserId' | 'workspaceId'>,\n activeIdentity?: WorkspaceKeyIdentity,\n ): Promise<{ completed: number; pending: number }> {\n const rows = await options.store.listPendingRevocations({\n product,\n workspaceId: scopeFilter?.workspaceId,\n ownerUserId: scopeFilter?.ownerUserId,\n now: now(),\n limit: PENDING_REVOCATION_BATCH_SIZE,\n })\n let completed = 0\n let pending = 0\n for (const row of rows) {\n if (row.product !== product) continue\n if (scopeFilter && (row.workspaceId !== scopeFilter.workspaceId || row.ownerUserId !== scopeFilter.ownerUserId)) continue\n if (await revokePending(row, activeIdentity)) completed += 1\n else pending += 1\n }\n return { completed, pending }\n }\n\n async function assertNoPendingRevocations(identity: WorkspaceKeyIdentity): Promise<void> {\n const rows = await options.store.listPendingRevocations({\n product,\n workspaceId: identity.workspaceId,\n ownerUserId: identity.ownerUserId,\n now: now(),\n limit: PENDING_REVOCATION_BATCH_SIZE,\n includeFuture: true,\n })\n if (rows.some((row) => row.product === product\n && row.workspaceId === identity.workspaceId\n && row.ownerUserId === identity.ownerUserId)) {\n throw new Error('a previous workspace child-key cleanup is pending; issuance is blocked until it completes')\n }\n }\n\n async function retryPendingRevocations(\n scopeInput?: Pick<WorkspaceKeyIdentity, 'ownerUserId' | 'workspaceId'>,\n identityInput?: WorkspaceKeyIdentity,\n ): Promise<number> {\n const identity = identityInput ? normalizeIdentity(identityInput) : undefined\n if (identity && scopeInput\n && (identity.workspaceId !== scopeInput.workspaceId || identity.ownerUserId !== scopeInput.ownerUserId)) {\n throw new Error('workspace child key retry identity does not match its scope')\n }\n if (scopeInput) {\n const workspaceId = scopeInput.workspaceId.trim()\n const ownerUserId = scopeInput.ownerUserId.trim()\n if (!workspaceId || !ownerUserId) throw new Error('workspace child key retry scope is incomplete')\n const scope = scopeKey({ workspaceId, ownerUserId, product })\n return withLocalLock(scope, () => withDurableLease(scope, async () => (\n await retryPendingRevocationsUnlocked({ workspaceId, ownerUserId }, identity)).completed))\n }\n\n if (identity) {\n const scope = scopeKey(scopeFor(identity, product))\n return withLocalLock(scope, () => withDurableLease(scope, async () => (\n await retryPendingRevocationsUnlocked({ workspaceId: identity.workspaceId, ownerUserId: identity.ownerUserId }, identity)).completed))\n }\n\n const rows = await options.store.listPendingRevocations({ product, now: now(), limit: PENDING_REVOCATION_BATCH_SIZE })\n let completed = 0\n const scopes = new Set<string>()\n for (const row of rows) {\n if (row.product !== product) continue\n const scope = scopeKey({ workspaceId: row.workspaceId, ownerUserId: row.ownerUserId, product })\n if (scopes.has(scope)) continue\n scopes.add(scope)\n completed += await withLocalLock(scope, () => withDurableLease(scope, async () => (await retryPendingRevocationsUnlocked({\n workspaceId: row.workspaceId,\n ownerUserId: row.ownerUserId,\n })).completed))\n }\n return completed\n }\n\n async function readActive(identity: WorkspaceKeyIdentity): Promise<{ row: DurableWorkspaceKeyRecord; usage: WorkspaceKeyUsage } | null> {\n const row = await options.store.getActive(scopeFor(identity, product))\n if (!row) return null\n if (!sameIdentity(row, identity, product)) {\n await options.store.markRevocationPending({\n id: row.id,\n error: 'active child key identity does not match the authenticated owner and source',\n nextAttemptAt: now(),\n incrementAttempts: false,\n })\n return null\n }\n\n let remote: Awaited<ReturnType<DurableWorkspaceKeyProvisioner['getKey']>>\n try {\n remote = await recoveryProvisioner.getKey(row.keyId)\n } catch (error) {\n if (isRemoteMissing(error)) {\n await options.store.markRevoked(row.id, now())\n return null\n }\n throw error\n }\n const usage = usageFromRemote(row, remote, now())\n if (usage.exhausted) {\n await options.store.markRevocationPending({\n id: row.id,\n error: 'active child key is expired or exhausted',\n nextAttemptAt: now(),\n incrementAttempts: false,\n })\n return null\n }\n return { row, usage }\n }\n\n async function mint(\n identity: WorkspaceKeyIdentity,\n budgetUsd: number,\n onRemoteKey?: (row: DurableWorkspaceKeyProvisioningRecord, remoteId: string) => void,\n ): Promise<WorkspaceRuntimeKey> {\n await assertWorkspaceKeyCryptoUsable(options.crypto)\n const mintOperationId = operationId()\n const createdAt = now()\n const expiresAt = new Date(createdAt.getTime() + keyLifetimeMs)\n const name = (options.nameForIdentity?.(identity, mintOperationId) ?? defaultKeyName(identity, product, mintOperationId)).trim()\n if (!name) throw new Error('workspace child key remote name is required')\n const rowId = operationId()\n const idempotencyKey = `workspace-key:${rowId}`\n const provisioningRow: DurableWorkspaceKeyProvisioningRecord = {\n id: rowId,\n workspaceId: identity.workspaceId,\n ownerUserId: identity.ownerUserId,\n product,\n platformUserId: identity.platformUserId,\n sourceKeyId: sourceKeyId(identity),\n sourceKeyFingerprint: identity.sourceKeyFingerprint,\n name,\n idempotencyKey,\n keyId: `provisioning:${mintOperationId}`,\n keyEncrypted: '',\n budgetUsd,\n expiresAt,\n status: 'provisioning',\n revocationAttempts: 0,\n nextRevocationAt: null,\n lastRevocationError: null,\n createdAt,\n }\n await options.store.insertProvisioning(provisioningRow)\n\n let created: Awaited<ReturnType<DurableWorkspaceKeyProvisioner['createKey']>>\n try {\n created = await options.provisioner.createKey({\n name,\n product,\n budgetUsd,\n expiresAt: expiresAt.toISOString(),\n idempotencyKey,\n })\n } catch (error) {\n // Keep cleanup running even when the state write fails. The remote\n // request may have committed before its response failed.\n try {\n await markPending(rowId, error, false)\n } catch {\n // cleanupProvisioning below can still find the remote name.\n }\n try {\n await cleanupProvisioning({ ...provisioningRow, status: 'revocation_pending' }, identity)\n } catch (cleanupError) {\n throw new Error('remote create failed and its cleanup could not be completed', { cause: cleanupError })\n }\n throw error\n }\n\n const remoteId = created.id?.trim() ?? ''\n const secret = created.key?.trim() ?? ''\n if (!remoteId || !secret) {\n if (remoteId) {\n try {\n await markProvisioningRemote(options.store, { id: rowId, keyId: remoteId })\n } catch {\n // revokePending uses the returned id even when this state write fails.\n }\n }\n try {\n await markPending(rowId, new Error('remote create returned no usable child key'), false)\n } catch {\n // Always attempt remote cleanup below.\n }\n const pendingRow = { ...provisioningRow, keyId: remoteId || provisioningRow.keyId, status: 'revocation_pending' as const }\n await revokePending(pendingRow, identity)\n throw new Error('remote create returned no usable child key')\n }\n\n let cleanupRow = provisioningRow\n onRemoteKey?.(cleanupRow, remoteId)\n\n async function retainRetiredCreatorCleanup(): Promise<void> {\n // A retired row cannot hold another pending transition. Persist the\n // returned child separately before revocation so a failed revoke survives restart.\n const retainedRow = { ...provisioningRow, id: operationId(), keyId: remoteId }\n try {\n await options.store.insertProvisioning(retainedRow)\n } catch (cause) {\n throw new Error('returned child cleanup record could not be persisted', { cause })\n }\n cleanupRow = retainedRow\n onRemoteKey?.(cleanupRow, remoteId)\n }\n\n try {\n const recorded = await markProvisioningRemote(options.store, { id: rowId, keyId: remoteId })\n if (!recorded) {\n await retainRetiredCreatorCleanup()\n throw new Error('workspace child-key provisioning row was retired before the remote id was recorded')\n }\n const keyEncrypted = await options.crypto.encrypt(secret)\n const remoteExpiresAt = created.expiresAt?.trim()\n const activeExpiresAt = remoteExpiresAt ? new Date(remoteExpiresAt) : expiresAt\n if (!Number.isFinite(activeExpiresAt.getTime())) throw new Error('remote child key expiry is malformed')\n const activeBudgetUsd = created.budgetUsd ?? budgetUsd\n if (!Number.isFinite(activeBudgetUsd) || activeBudgetUsd < 0) throw new Error('remote child key budget is malformed')\n const activated = await markActive(options.store, {\n id: rowId,\n keyId: remoteId,\n keyEncrypted,\n expiresAt: activeExpiresAt,\n budgetUsd: activeBudgetUsd,\n })\n if (!activated) {\n await retainRetiredCreatorCleanup()\n throw new Error('workspace child-key provisioning row was retired before activation')\n }\n } catch (error) {\n // A persistence failure must not strand the already-created remote key.\n try {\n await markPending(cleanupRow.id, error, false)\n } catch {\n // revokePending below still has the remote id and attempts cleanup.\n }\n await revokePending({ ...cleanupRow, keyId: remoteId, status: 'revocation_pending' }, identity)\n throw error\n }\n\n const row = await options.store.getActive(scopeFor(identity, product))\n if (!row || row.keyId !== remoteId || !sameIdentity(row, identity, product)) {\n const error = new Error('workspace child key was not persisted as active')\n try {\n await options.store.markRevocationPending({\n id: rowId,\n error: error.message,\n nextAttemptAt: now(),\n incrementAttempts: false,\n })\n } catch {\n // The remote id is still available for the cleanup attempt below.\n }\n await revokePending({ ...provisioningRow, keyId: remoteId, status: 'revocation_pending' }, identity)\n throw error\n }\n const usage = usageFromRemote(row, {\n budgetUsd: created.budgetUsd,\n budgetSpent: 0,\n expiresAt: created.expiresAt ?? expiresAt.toISOString(),\n }, now())\n return { key: secret, usage, refreshed: true }\n }\n\n async function ensureKey(identityInput: WorkspaceKeyIdentity, keyOptions?: { budgetUsd?: number }): Promise<WorkspaceRuntimeKey> {\n const identity = normalizeIdentity(identityInput)\n const budgetUsd = keyOptions?.budgetUsd ?? defaultBudgetUsd\n requirePositive(budgetUsd, 'budgetUsd')\n const scope = scopeKey(scopeFor(identity, product))\n let mintedRemote: { row: DurableWorkspaceKeyProvisioningRecord; remoteId: string } | null = null\n return withLocalLock(scope, () => withDurableLease(scope, async () => {\n const initialCleanup = await retryPendingRevocationsUnlocked(identity, identity)\n if (initialCleanup.pending > 0) throw new Error('a previous workspace child-key cleanup is pending; issuance is blocked until it completes')\n await reconcileProvisioning(identity)\n const active = await readActive(identity)\n if (active) {\n const key = await options.crypto.decrypt(active.row.keyEncrypted)\n if (!key.trim()) throw new Error('workspace child key secret is empty')\n // The decrypt is awaited after the expiry check; a key that expired meanwhile is never handed out.\n if (Date.parse(active.usage.expiresAt) > now().getTime()) return { key, usage: active.usage, refreshed: false }\n await options.store.markRevocationPending({\n id: active.row.id,\n error: 'active child key expired while it was read',\n nextAttemptAt: now(),\n incrementAttempts: false,\n })\n }\n const finalCleanup = await retryPendingRevocationsUnlocked(identity, identity)\n if (finalCleanup.pending > 0) throw new Error('a previous workspace child-key cleanup is pending; issuance is blocked until it completes')\n await assertNoPendingRevocations(identity)\n return mint(identity, budgetUsd, (row, remoteId) => {\n mintedRemote = { row, remoteId }\n })\n }, async () => {\n const remote = mintedRemote\n if (!remote) return\n const cleaned = await revokePending({\n ...remote.row,\n keyId: remote.remoteId,\n status: 'revocation_pending',\n }, identity)\n if (!cleaned) throw new Error('lease-loss child-key cleanup is pending')\n }))\n }\n\n async function getUsage(identityInput: WorkspaceKeyIdentity): Promise<WorkspaceKeyUsage | null> {\n const identity = normalizeIdentity(identityInput)\n const scope = scopeKey(scopeFor(identity, product))\n return withLocalLock(scope, () => withDurableLease(scope, async () => {\n const active = await readActive(identity)\n return active?.usage ?? null\n }))\n }\n\n return { ensureKey, getUsage, retryPendingRevocations }\n}\n","import { assertWorkspaceKeyCryptoUsable } from './crypto-probe'\n\n/**\n * Per-workspace budget-capped model keys — app-owned billing, metered on Tangle.\n *\n * Each workspace (the paying entity) runs the agent on its OWN child API key\n * minted from the platform parent key. The child carries a hard USD budget the\n * Tangle Router enforces AT THE KEY — model spend can't exceed the allowance,\n * zero app-side accounting. The app charges its own subscription (e.g. 5× the\n * allowance) and re-provisions each period. Child budgets are IMMUTABLE on the\n * platform, so a new budget = a fresh key + revoke the prior (rotate).\n *\n * The mint / rotate / rollover / usage LOGIC is generic and lives here.\n * Persistence (which D1 table), secret encryption, and key provisioning are\n * SEAMS each product supplies — so this module imports no DB and no key-mgmt\n * SDK (structural contracts only, like `../tangle`). The `@tangle-network/tcloud`\n * SDK is the provisioner a product passes in; it is not a dependency here.\n */\n\n/** The key-provisioning operations the key manager needs. Wire it from the\n * platform via {@link createTcloudKeyProvisioner} rather than casting. */\nexport interface KeyProvisioner {\n createKey(input: { name: string; product: string; budgetUsd: number; expiresAt: string }): Promise<{ id?: string; key?: string }>\n revokeKey(keyId: string): Promise<unknown>\n getKey(keyId: string): Promise<{ budgetUsd?: number; budgetSpent?: number; expiresAt?: string | null }>\n}\n\n/**\n * The subset of the `@tangle-network/tcloud` `TCloudClient` the provisioner uses\n * — declared with METHOD syntax so the real client (whose `product` is a narrow\n * union and whose budgets are `number | null`) is assignable bivariantly. The\n * real SDK client satisfies this; pass it straight in.\n */\nexport interface TcloudKeyClient {\n createKey(opts: {\n name: string\n product?: string\n budgetUsd?: number\n expiresAt?: string\n parentKeyId?: string\n allowedModels?: string[]\n rpmLimit?: number\n }): Promise<{ id: string; key: string }>\n getKey(id: string): Promise<{ budgetUsd?: number | null; budgetSpent?: number; expiresAt?: string | null }>\n revokeKey(id: string): Promise<unknown>\n}\n\n/**\n * Adapt the tcloud SDK client to {@link KeyProvisioner} — the typed seam that\n * replaces the `as unknown as KeyProvisioner` cast every consumer otherwise\n * repeats. The platform already exposes child-key minting (parent→child key,\n * per-key USD budget, expiry); this maps its shapes (`product` union,\n * `number | null` budgets) onto the manager's contract (`null → undefined`).\n */\nexport function createTcloudKeyProvisioner(client: TcloudKeyClient): KeyProvisioner {\n return {\n createKey: async (input) => {\n const created = await client.createKey(input)\n return { id: created.id, key: created.key }\n },\n revokeKey: (keyId) => client.revokeKey(keyId),\n getKey: async (keyId) => {\n const info = await client.getKey(keyId)\n return {\n budgetUsd: info.budgetUsd ?? undefined,\n budgetSpent: info.budgetSpent ?? undefined,\n expiresAt: info.expiresAt ?? null,\n }\n },\n }\n}\n\n/** A stored child-key record (the app's row, shape-normalized). */\nexport interface WorkspaceKeyRecord {\n /** App row id (opaque). */\n id: string\n keyId: string\n /** The encrypted secret — decrypted via {@link KeyCrypto.decrypt}. */\n keyEncrypted: string\n budgetUsd: number\n expiresAt: Date | null\n}\n\n/** Persistence seam — the product implements this against its own D1 table. */\nexport interface WorkspaceKeyStore {\n /** Most-recent active key for the workspace, or null. */\n getActive(workspaceId: string): Promise<WorkspaceKeyRecord | null>\n /** All active keys (to revoke priors on rotate). */\n listActive(workspaceId: string): Promise<Array<{ id: string; keyId: string }>>\n /** Persist a freshly minted active key. */\n insert(record: { workspaceId: string; keyId: string; keyEncrypted: string; budgetUsd: number; expiresAt: Date }): Promise<void>\n /** Mark a prior row revoked. */\n markRevoked(id: string, now: Date): Promise<void>\n}\n\n/** Secret encryption seam (the app's at-rest crypto). */\nexport interface KeyCrypto {\n encrypt(secret: string): Promise<string>\n decrypt(encrypted: string): Promise<string>\n}\n\n/** Define configuration options for managing workspace keys including provisioning, storage, and cryptography */\nexport interface WorkspaceKeyManagerOptions {\n provisioner: KeyProvisioner\n store: WorkspaceKeyStore\n crypto: KeyCrypto\n /** Default monthly allowance (USD) when a call doesn't specify one. */\n defaultBudgetUsd: number\n /** Injectable clock. Default `() => new Date()`. */\n now?: () => Date\n /** tcloud product the key is scoped to. Default `'router'`. */\n product?: string\n}\n\n/** Describe usage and budget details for a workspace model key including expiration and exhaustion status */\nexport interface WorkspaceModelKeyUsage {\n keyId: string\n budgetUsd: number\n budgetSpent: number\n budgetRemaining: number\n expiresAt: string | null\n exhausted: boolean\n}\n\n/** Manage workspace keys by ensuring, rotating, and tracking usage of active child-key secrets */\nexport interface WorkspaceKeyManager {\n /** The workspace's active child-key secret, provisioning one if absent/expired. */\n ensureKey(workspaceId: string, opts?: { budgetUsd?: number }): Promise<string>\n /** Mint a fresh key + revoke priors (period renewal / top-up). `rollover`\n * carries the prior key's unused budget into the new one, bounded by\n * `rolloverCapUsd`. Returns the new secret. */\n rotateKey(workspaceId: string, opts?: { budgetUsd?: number; rollover?: boolean; rolloverCapUsd?: number }): Promise<string>\n /** Live budget usage for the active key (drives the \"$X of $Y used\" panel). */\n getUsage(workspaceId: string): Promise<WorkspaceModelKeyUsage | null>\n}\n\n/** Period end = first day of next month, midnight UTC. Keys expire at the period\n * boundary so a forgotten rotation fails closed rather than running free. */\nfunction nextPeriodEnd(now: Date): Date {\n return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1, 0, 0, 0, 0))\n}\n\n// ---------------------------------------------------------------------------\n// Shared-platform-balance billing\n//\n// A DIFFERENT model from the per-workspace child-key manager above: here every\n// user runs against a SHARED platform balance (id.tangle.tools), keyed by the\n// user's platform identity. The app owns no key minting — it reads the balance,\n// gates a billable turn, and deducts spend through the platform billing API.\n// Plan limits, the platform transport, and identity resolution are SEAMS the\n// product supplies; this module imports no DB and no HTTP client.\n// ---------------------------------------------------------------------------\n\n/** A user's resolved platform identity (from the app's SSO account store). */\nexport interface PlatformIdentity {\n platformUserId: string\n /** The user's per-user platform API key (reads), or null when unlinked. */\n apiKey: string | null\n}\n\n/** Spendable balance for a platform user. */\nexport interface PlatformBalanceInfo {\n balance: number\n lifetimeSpent: number\n}\n\n/** Per-product spend aggregate. */\nexport interface PlatformProductUsage {\n product: string | null\n totalSpent: number\n count: number\n}\n\n/** Plan limits — a PARAMETER per product (dollar allowance, concurrency,\n * overage policy). Never baked into the framework. */\nexport interface PlanLimit {\n monthlyBalanceUsd: number\n concurrency: number\n overageAllowed: boolean\n}\n\n/**\n * The platform billing transport — the product wires these to id.tangle.tools\n * (or any balance backend). Reads authenticate as the user (their `apiKey`);\n * the deduct write is a service-token call naming the target user. This module\n * never touches HTTP — it only sequences these calls.\n */\nexport interface PlatformBillingClient<Plan extends string> {\n /** Resolve the user's platform identity, or null when there is no SSO account. */\n resolveIdentity(userId: string): Promise<PlatformIdentity | null>\n /** Subscription plan for the user (via their platform key). */\n getPlan(apiKey: string): Promise<Plan>\n /** Spendable balance for the user (via their platform key). */\n getBalance(apiKey: string): Promise<PlatformBalanceInfo>\n /** Per-product usage rows for the user (via their platform key). */\n getUsageByProduct(apiKey: string): Promise<PlatformProductUsage[]>\n /** Deduct spend against the user's balance (service-token write). */\n deduct(input: { platformUserId: string; amountUsd: number; type: string; description: string; referenceId: string }): Promise<void>\n}\n\n/** Define shared billing state including user ID, plan, balances, concurrency, and overage permission */\nexport interface SharedBillingState<Plan extends string> {\n /** Platform user id, or null when the user has no Tangle SSO account. */\n platformUserId: string | null\n plan: Plan\n monthlyBalanceUsd: number\n remainingBalanceUsd: number\n lifetimeSpentUsd: number\n concurrency: number\n overageAllowed: boolean\n}\n\n/** Define configuration options for managing platform balance based on billing plans */\nexport interface PlatformBalanceManagerOptions<Plan extends string> {\n client: PlatformBillingClient<Plan>\n /** Plan → limits map (the product's pricing). */\n planLimits: Record<Plan, PlanLimit>\n /** The plan an unlinked / outage user falls to (fails CLOSED). */\n freePlan: Plan\n /** The product slug to attribute usage to (for `getProductUsage`). */\n productSlug: string\n}\n\n/** Manage user plans and balances including state retrieval, billing authorization, deduction, and usage tracking */\nexport interface PlatformBalanceManager<Plan extends string> {\n /** Resolve the user's plan + balance. Unlinked or platform-outage users fail\n * CLOSED: free plan, zero remaining balance — a billable run is never started\n * against an unknown balance. */\n getState(userId: string): Promise<SharedBillingState<Plan>>\n /** Gate a billable turn: allowed when the plan permits overage or remaining\n * balance is positive. Returns the state so the caller deducts against it. */\n canStartBillableTurn(userId: string): Promise<{ allowed: boolean; state: SharedBillingState<Plan> }>\n /** Deduct `amountUsd` against the user's platform balance. Throws when the\n * user is not platform-linked. */\n deduct(userId: string, params: { amountUsd: number; type: string; description: string; referenceId: string }): Promise<void>\n /** This product's spend for the user (drives a usage panel). */\n getProductUsage(userId: string): Promise<{ spentUsd: number; transactionCount: number }>\n}\n\n/** Create a platform balance manager to handle user plan limits and state based on provided options */\nexport function createPlatformBalanceManager<Plan extends string>(\n opts: PlatformBalanceManagerOptions<Plan>,\n): PlatformBalanceManager<Plan> {\n const { client, planLimits, freePlan, productSlug } = opts\n\n const getState: PlatformBalanceManager<Plan>['getState'] = async (userId) => {\n const identity = await client.resolveIdentity(userId)\n // No SSO account, or linked without a platform key: unlinked free tier with\n // zero balance. Reads require the user's key — never call them empty.\n if (!identity || !identity.apiKey) {\n const limits = planLimits[freePlan]\n return {\n platformUserId: identity?.platformUserId ?? null,\n plan: freePlan,\n monthlyBalanceUsd: limits.monthlyBalanceUsd,\n remainingBalanceUsd: 0,\n lifetimeSpentUsd: 0,\n concurrency: limits.concurrency,\n overageAllowed: limits.overageAllowed,\n }\n }\n const [plan, balance] = await Promise.all([client.getPlan(identity.apiKey), client.getBalance(identity.apiKey)])\n const limits = planLimits[plan]\n return {\n platformUserId: identity.platformUserId,\n plan,\n monthlyBalanceUsd: limits.monthlyBalanceUsd,\n remainingBalanceUsd: balance.balance,\n lifetimeSpentUsd: balance.lifetimeSpent,\n concurrency: limits.concurrency,\n overageAllowed: limits.overageAllowed,\n }\n }\n\n const canStartBillableTurn: PlatformBalanceManager<Plan>['canStartBillableTurn'] = async (userId) => {\n const state = await getState(userId)\n if (!state.platformUserId) return { allowed: false, state }\n const allowed = state.overageAllowed || state.remainingBalanceUsd > 0\n return { allowed, state }\n }\n\n const deduct: PlatformBalanceManager<Plan>['deduct'] = async (userId, params) => {\n const identity = await client.resolveIdentity(userId)\n if (!identity) throw new Error('Shared billing requires a platform-linked user')\n await client.deduct({\n platformUserId: identity.platformUserId,\n amountUsd: params.amountUsd,\n type: params.type,\n description: params.description,\n referenceId: params.referenceId,\n })\n }\n\n const getProductUsage: PlatformBalanceManager<Plan>['getProductUsage'] = async (userId) => {\n const identity = await client.resolveIdentity(userId)\n if (!identity?.apiKey) return { spentUsd: 0, transactionCount: 0 }\n const rows = await client.getUsageByProduct(identity.apiKey)\n const product = rows.find((row) => row.product === productSlug)\n return { spentUsd: product?.totalSpent ?? 0, transactionCount: product?.count ?? 0 }\n }\n\n return { getState, canStartBillableTurn, deduct, getProductUsage }\n}\n\n/** Create a workspace key manager that handles key provisioning and budget tracking */\nexport function createWorkspaceKeyManager(opts: WorkspaceKeyManagerOptions): WorkspaceKeyManager {\n const clock = opts.now ?? (() => new Date())\n const product = opts.product ?? 'router'\n\n const getUsage: WorkspaceKeyManager['getUsage'] = async (workspaceId) => {\n const active = await opts.store.getActive(workspaceId)\n if (!active) return null\n const info = await opts.provisioner.getKey(active.keyId)\n const budgetUsd = info.budgetUsd ?? active.budgetUsd\n const budgetSpent = info.budgetSpent ?? 0\n const budgetRemaining = Math.max(0, budgetUsd - budgetSpent)\n return {\n keyId: active.keyId,\n budgetUsd,\n budgetSpent,\n budgetRemaining,\n expiresAt: info.expiresAt ?? (active.expiresAt ? active.expiresAt.toISOString() : null),\n exhausted: budgetRemaining <= 0,\n }\n }\n\n const rotateKey: WorkspaceKeyManager['rotateKey'] = async (workspaceId, ropts) => {\n const now = clock()\n const allowance = ropts?.budgetUsd ?? opts.defaultBudgetUsd\n\n let budgetUsd = allowance\n if (ropts?.rollover) {\n const prior = await getUsage(workspaceId).catch(() => null)\n budgetUsd = allowance + (prior?.budgetRemaining ?? 0)\n if (ropts.rolloverCapUsd != null) budgetUsd = Math.min(budgetUsd, ropts.rolloverCapUsd)\n }\n\n // Prove the at-rest crypto seam is usable BEFORE spending a platform mint.\n // The `KeyCrypto` impl may close over an env-resolved key (createFieldCrypto)\n // that is empty/invalid and only throws at encrypt time — after the mint —\n // orphaning the child key. A round-trip probe makes a misconfigured consumer\n // fail loud with ZERO platform spend.\n await assertWorkspaceKeyCryptoUsable(opts.crypto)\n\n const expiresAt = nextPeriodEnd(now)\n const created = await opts.provisioner.createKey({ name: `ws:${workspaceId}`, product, budgetUsd, expiresAt: expiresAt.toISOString() })\n if (!created.key || !created.id) throw new Error('tcloud createKey returned no key')\n const mintedKeyId = created.id\n\n // Past this point the platform has minted a budget-bearing child key. ANY\n // failure before the row is persisted (encrypt, insert) MUST revoke the\n // just-minted key, else it leaks as a zombie holding parent-key headroom —\n // a missing/invalid encryption key would otherwise burn the child budget\n // per mint attempt until the parent can no longer mint (fleet-wide outage).\n let keyEncrypted: string\n let priors: Array<{ id: string; keyId: string }>\n try {\n keyEncrypted = await opts.crypto.encrypt(created.key)\n priors = await opts.store.listActive(workspaceId)\n await opts.store.insert({ workspaceId, keyId: mintedKeyId, keyEncrypted, budgetUsd, expiresAt })\n } catch (err) {\n // Best-effort revoke of the orphan. A revoke failure must NOT mask the\n // original cause — log it loudly and rethrow the original error.\n try {\n await opts.provisioner.revokeKey(mintedKeyId)\n } catch (revokeErr) {\n console.error(\n `[workspace-key-manager] FAILED to revoke orphaned child key ${mintedKeyId} ` +\n `for workspace ${workspaceId} after a post-mint failure — it now leaks parent-key budget. ` +\n `Revoke error:`,\n revokeErr,\n )\n }\n throw err\n }\n\n for (const p of priors) {\n await opts.store.markRevoked(p.id, now)\n // Best-effort upstream revoke — the row is already revoked and an expired\n // key fails closed regardless, so a transient error is non-fatal.\n try {\n await opts.provisioner.revokeKey(p.keyId)\n } catch {\n /* non-fatal */\n }\n }\n return created.key\n }\n\n const ensureKey: WorkspaceKeyManager['ensureKey'] = async (workspaceId, eopts) => {\n const now = clock()\n const active = await opts.store.getActive(workspaceId)\n if (active && (!active.expiresAt || active.expiresAt.getTime() > now.getTime())) {\n return opts.crypto.decrypt(active.keyEncrypted)\n }\n // An expired child can no longer spend, yet the platform keeps its budget\n // reserved on the parent until it is revoked. Revoke it BEFORE minting the\n // renewal: minting first needs a second child's budget of headroom, so a\n // fully reserved parent could never renew and the expired key would hold\n // its reservation forever. Best-effort: on failure the row stays active and\n // rotateKey retries the revoke after its mint.\n if (active) {\n try {\n await opts.provisioner.revokeKey(active.keyId)\n await opts.store.markRevoked(active.id, now)\n } catch {\n /* rotateKey revokes remaining priors after the mint */\n }\n }\n return rotateKey(workspaceId, { budgetUsd: eopts?.budgetUsd })\n }\n\n return { ensureKey, rotateKey, getUsage }\n}\n\nexport {\n createIdentityBoundWorkspaceKeyManager,\n type DurableWorkspaceKeyManager,\n type DurableWorkspaceKeyManagerOptions,\n type DurableWorkspaceKeyCreateInput,\n type DurableWorkspaceKeyConditionalWrites,\n type DurableWorkspaceKeyProvisioner,\n type DurableWorkspaceKeyProvisioningRecord,\n type DurableWorkspaceKeyRecord,\n type DurableWorkspaceKeyScope,\n type DurableWorkspaceKeyStore,\n type WorkspaceKeyIdentity,\n type WorkspaceKeyProduct,\n type WorkspaceKeyStatus,\n type WorkspaceKeyUsage,\n type WorkspaceRuntimeKey,\n} from './identity-bound'\n"],"mappings":";AAGA,eAAsB,+BAA+B,QAAkC;AACrF,QAAM,QAAQ;AACd,MAAI;AACJ,MAAI;AACF,mBAAe,MAAM,OAAO,QAAQ,MAAM,OAAO,QAAQ,KAAK,CAAC;AAAA,EACjE,SAAS,OAAO;AACd,UAAM,IAAI;AAAA,MACR;AAAA,MAEA,EAAE,OAAO,MAAM;AAAA,IACjB;AAAA,EACF;AACA,MAAI,iBAAiB,OAAO;AAC1B,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACF;;;ACqNA,IAAM,0BAA0B,KAAK;AACrC,IAAM,mBAAmB;AACzB,IAAM,wBAAwB;AAC9B,IAAM,wBAAwB;AAC9B,IAAM,kCAAkC,KAAK,MAAM,mBAAmB,CAAC;AACvE,IAAM,mCAAmC;AACzC,IAAM,kCAAkC;AACxC,IAAM,gCAAgC;AAEtC,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;AAEA,SAAS,cAAsB;AAC7B,SAAO,WAAW,OAAO,WAAW;AACtC;AAEA,SAAS,gBAA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K,MAAM,OAAO,EAAE,aAAa,OAAO,aAAa,cAAc,WAAW,UAAU,CAAC;AAAA,IACjG,SAAS,KAAK;AAGZ,UAAI;AACF,cAAM,KAAK,YAAY,UAAU,WAAW;AAAA,MAC9C,SAAS,WAAW;AAClB,gBAAQ;AAAA,UACN,+DAA+D,WAAW,kBACvD,WAAW;AAAA,UAE9B;AAAA,QACF;AAAA,MACF;AACA,YAAM;AAAA,IACR;AAEA,eAAW,KAAK,QAAQ;AACtB,YAAM,KAAK,MAAM,YAAY,EAAE,IAAI,GAAG;AAGtC,UAAI;AACF,cAAM,KAAK,YAAY,UAAU,EAAE,KAAK;AAAA,MAC1C,QAAQ;AAAA,MAER;AAAA,IACF;AACA,WAAO,QAAQ;AAAA,EACjB;AAEA,QAAM,YAA8C,OAAO,aAAa,UAAU;AAChF,UAAM,MAAM,MAAM;AAClB,UAAM,SAAS,MAAM,KAAK,MAAM,UAAU,WAAW;AACrD,QAAI,WAAW,CAAC,OAAO,aAAa,OAAO,UAAU,QAAQ,IAAI,IAAI,QAAQ,IAAI;AAC/E,aAAO,KAAK,OAAO,QAAQ,OAAO,YAAY;AAAA,IAChD;AAOA,QAAI,QAAQ;AACV,UAAI;AACF,cAAM,KAAK,YAAY,UAAU,OAAO,KAAK;AAC7C,cAAM,KAAK,MAAM,YAAY,OAAO,IAAI,GAAG;AAAA,MAC7C,QAAQ;AAAA,MAER;AAAA,IACF;AACA,WAAO,UAAU,aAAa,EAAE,WAAW,OAAO,UAAU,CAAC;AAAA,EAC/D;AAEA,SAAO,EAAE,WAAW,WAAW,SAAS;AAC1C;","names":["sourceKeyId","operationId","limits"]}
@@ -59,10 +59,10 @@ function readChatPage(c) {
59
59
  const after = (e) => anchor === null || (anchor.compareDocumentPosition(e) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0;
60
60
  const full = region?.innerText ?? "";
61
61
  let text = full;
62
- const composerText = composer && region?.contains(composer) ? composer.innerText.trim() : "";
63
- if (composerText) {
64
- const at = text.lastIndexOf(composerText);
65
- if (at >= 0) text = text.slice(0, at) + text.slice(at + composerText.length);
62
+ const composerText2 = composer && region?.contains(composer) ? composer.innerText.trim() : "";
63
+ if (composerText2) {
64
+ const at = text.lastIndexOf(composerText2);
65
+ if (at >= 0) text = text.slice(0, at) + text.slice(at + composerText2.length);
66
66
  }
67
67
  let lines = text.split("\n").map((l) => l.trim()).filter(Boolean);
68
68
  if (anchor && c.promptHead) {
@@ -147,6 +147,12 @@ async function settleText(read, wait = (ms) => new Promise((resolve) => setTimeo
147
147
  await wait(500);
148
148
  }
149
149
  }
150
+ async function composerText(box) {
151
+ return box.evaluate((el) => {
152
+ const field = el;
153
+ return typeof field.value === "string" ? field.value : field.innerText ?? el.textContent ?? "";
154
+ });
155
+ }
150
156
 
151
157
  // src/journeys/journey.ts
152
158
  var DESKTOP = { width: 1440, height: 900 };
@@ -324,7 +330,7 @@ var Journey = class {
324
330
  const line = lines[i];
325
331
  if (line) await box.pressSequentially(line, { delay: attempt === 0 ? delay : 0, timeout: 3e4 + line.length * (delay + 60) });
326
332
  }
327
- const text = (await box.innerText().catch(() => "")).replace(/\s+/g, " ").trim();
333
+ const text = (await composerText(box).catch(() => "")).replace(/\s+/g, " ").trim();
328
334
  if (text.includes(want)) return;
329
335
  await sleep(1e3);
330
336
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/journeys/journey.ts","../../src/journeys/page-reading.ts","../../src/journeys/send.ts"],"sourcesContent":["/**\n * One recorded journey through a running agent app: signed-in recorded\n * contexts, chapters, a person's pacing, desktop and phone screenshots,\n * measured chat turns, and a `finish()` that turns the recording into files\n * that are safe to copy off the host.\n *\n * const j = await startJourney('core-path') // reads journeys.config.mjs\n * const page = await j.open('founder', 'member') // recorded, already signed in\n * await j.step('Founder opens the workspace', () => page.goto('/app'), page)\n * await j.shot('home', page) // home-desktop.png + home-phone.png\n * const turn = await j.sendNew(page, 'Research …', { from: `/app/${ws}/chat/new` })\n * await j.finish() // mp4s, srt, highlights, scrubbed trace, timings\n *\n * Output, all safe to copy (finish() refuses otherwise):\n * <outDir>/<id>/video/<label>-full.mp4 <label>-highlights.mp4 <label>.srt <label>-trace.zip\n * <outDir>/<id>/<name>-desktop.png <name>-phone.png timings.json chapters.json turns/*.md\n * Raw webm and unscrubbed traces stay in <stateDir>/raw on the host.\n */\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { hostname } from 'node:os'\nimport { join } from 'node:path'\nimport type { Browser, BrowserContext, Locator, Page } from 'playwright'\nimport { loadJourneysConfig, resolveJourneysConfig, threadRouteIn, type JourneysConfig, type ResolvedJourneysConfig, type ThreadRoute } from './config.js'\nimport { promptHead, readChatPage } from './page-reading.js'\nimport { scoreTurn, turnLooksActive, TurnEvidence, type TranscriptSnapshot, type TurnOutcome } from './score.js'\nimport { assertNoSecrets, scrubTrace } from './scrub.js'\nimport { clickUntilSubmitted, createSubmissionTracker, settleText } from './send.js'\nimport { secretNeedles, storageStateFor } from './session.js'\nimport { postProcessVideo, type Chapter } from './video.js'\n\nexport const DESKTOP = { width: 1440, height: 900 }\nexport const PHONE = { width: 390, height: 844 }\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))\nconst secs = (ms: number) => Math.round(ms / 100) / 10\n\n/** A visible pointer so a viewer can follow clicks in a headless recording. Hidden for screenshots. */\nconst CURSOR_SCRIPT = `(() => {\n const install = () => {\n if (document.getElementById('__journey_cursor') || !document.body) return\n const dot = document.createElement('div')\n dot.id = '__journey_cursor'\n dot.setAttribute('aria-hidden', 'true')\n Object.assign(dot.style, { position: 'fixed', zIndex: '2147483647', width: '24px', height: '24px',\n margin: '-12px 0 0 -12px', borderRadius: '50%', background: 'rgba(255,72,48,.28)',\n border: '2px solid rgba(255,72,48,.95)', pointerEvents: 'none', left: (window.__jx ?? -100) + 'px',\n top: (window.__jy ?? -100) + 'px', transition: 'transform .12s ease-out' })\n document.body.appendChild(dot)\n }\n addEventListener('mousemove', (e) => { window.__jx = e.clientX; window.__jy = e.clientY\n const d = document.getElementById('__journey_cursor'); if (d) { d.style.left = e.clientX + 'px'; d.style.top = e.clientY + 'px' } }, true)\n addEventListener('mousedown', () => { const d = document.getElementById('__journey_cursor'); if (d) d.style.transform = 'scale(.55)' }, true)\n addEventListener('mouseup', () => { const d = document.getElementById('__journey_cursor'); if (d) d.style.transform = 'scale(1)' }, true)\n // After hydration, so the framework never meets a node it did not render.\n addEventListener('load', () => setTimeout(install, 1500))\n setInterval(install, 2000)\n})()`\n\ninterface Recorded {\n label: string\n identity: string\n context: BrowserContext\n page: Page\n t0: number\n rawDir: string\n}\n\nexport interface TurnRecord {\n label: string\n prompt: string\n threadId: string | null\n sentAt: string\n /** Seconds from the Send press. */\n firstProgressS: number | null\n firstProgressText: string | null\n firstTextS: number | null\n /** Seconds from Send to the first failure evidence on the page, if any appeared. */\n firstFailureS: number | null\n completeS: number | null\n outcome: TurnOutcome\n /** Plain words for what went wrong, or null for a completed turn. */\n error: string | null\n /** Every piece of failure evidence the turn added. */\n failures: string[]\n /** Where evidence was read: after the turn's own prompt, or the whole transcript when the page did not show the prompt. */\n evidenceScope: 'after-prompt' | 'whole-transcript' | null\n replyChars: number\n /** Distinct status lines the transcript showed, with when they appeared. */\n stages: { s: number; text: string }[]\n /** Seconds from Send at which the journey pressed Stop, if it did. */\n stopPressedS: number | null\n replyFile: string | null\n}\n\nexport interface StepRecord {\n caption: string\n label: string | null\n startS: number\n durationS: number\n ok: boolean\n error?: string\n}\n\nexport interface SendOptions {\n caption?: string\n timeoutMs?: number\n /** Keystroke delay for the prompt. */\n delay?: number\n /** Press Stop at first text, or this many seconds after Send. */\n stopAfter?: 'first-text' | number\n}\n\n/** What the page shows right now, read in one evaluate. */\ninterface PageReading extends TranscriptSnapshot {\n status: string[]\n assistantChars: number\n transcriptChars: number\n stopVisible: boolean\n}\n\nexport class Journey {\n readonly outDir: string\n readonly rawDir: string\n readonly chapters: Chapter[] = []\n readonly steps: StepRecord[] = []\n readonly turns: TurnRecord[] = []\n private recorded: Recorded[] = []\n private phones = new Map<string, BrowserContext>()\n private readonly startedAt = Date.now()\n\n constructor(readonly id: string, readonly config: ResolvedJourneysConfig, readonly browser: Browser, private readonly opts: { cursor: boolean }) {\n this.outDir = join(config.outDir, id)\n this.rawDir = join(config.stateDir, 'raw', `${id}-${new Date().toISOString().replace(/[:.]/g, '-')}`)\n mkdirSync(join(this.outDir, 'video'), { recursive: true })\n mkdirSync(join(this.outDir, 'turns'), { recursive: true })\n mkdirSync(this.rawDir, { recursive: true, mode: 0o700 })\n }\n\n /**\n * A recorded, traced 1440x900 context. A config identity starts signed in\n * from the cached session (no login form is ever recorded); `'anon'` starts\n * signed out, for public pages. Open at most two per journey.\n */\n async open(label: string, identity: string, opts: { fresh?: boolean } = {}): Promise<Page> {\n if (this.recorded.some((r) => r.label === label)) throw new Error(`a context labelled ${label} is already open`)\n if (!/^[a-z0-9][a-z0-9-]{0,30}$/.test(label)) throw new Error('context label: lowercase letters, digits and dashes')\n const storageState = identity === 'anon' ? undefined : (await storageStateFor(this.config, identity, opts)).path\n const rawDir = join(this.rawDir, label)\n const context = await this.browser.newContext({\n baseURL: this.config.baseUrl,\n storageState,\n viewport: DESKTOP,\n recordVideo: { dir: rawDir, size: DESKTOP },\n locale: 'en-US',\n timezoneId: 'America/Denver',\n })\n context.setDefaultTimeout(20_000)\n context.setDefaultNavigationTimeout(60_000)\n if (this.opts.cursor) await context.addInitScript(CURSOR_SCRIPT)\n if (process.env.JOURNEY_DEBUG_CLOCK === '1') {\n // Wall-clock seconds since recording start on every frame, for calibrating captions.\n await context.addInitScript((t0: number) => {\n setInterval(() => {\n let d = document.getElementById('__journey_clock')\n if (!d && document.body) {\n d = document.createElement('div')\n d.id = '__journey_clock'\n Object.assign(d.style, { position: 'fixed', left: '50%', top: '0', zIndex: '2147483647', font: 'bold 20px monospace', background: '#ff0', color: '#000', padding: '2px 6px', pointerEvents: 'none' })\n document.body.appendChild(d)\n }\n if (d) d.textContent = ((Date.now() - t0) / 1000).toFixed(1)\n }, 100)\n }, Date.now())\n }\n await context.tracing.start({ screenshots: true, snapshots: true, title: `${this.id} ${label}` })\n const page = await context.newPage()\n this.recorded.push({ label, identity, context, page, t0: Date.now(), rawDir })\n return page\n }\n\n private recordedFor(page?: Page): Recorded {\n const r = page ? this.recorded.find((x) => x.page === page) : this.recorded[0]\n if (!r) throw new Error('no recorded context for that page; call open() first')\n return r\n }\n\n /** A chapter at this instant: one plain line, shown in the caption bar and the .srt. */\n mark(caption: string, page?: Page): void {\n const label = page ? this.recordedFor(page).label : null\n this.chapters.push({ at: Date.now(), caption, label, kind: 'step' })\n console.log(`[${secs(Date.now() - this.startedAt).toFixed(1)}s] ${label ? `${label}: ` : ''}${caption}`)\n }\n\n /** A timed step with its own chapter. A failure is recorded, captioned, then rethrown. */\n async step<T>(caption: string, work: () => Promise<T>, page?: Page): Promise<T> {\n this.mark(caption, page)\n const start = Date.now()\n const entry: StepRecord = { caption, label: page ? this.recordedFor(page).label : null, startS: secs(start - this.startedAt), durationS: 0, ok: true }\n this.steps.push(entry)\n try {\n return await work()\n } catch (error) {\n entry.ok = false\n entry.error = String((error as Error)?.message ?? error).slice(0, 400)\n this.mark(`Step failed: ${caption}`, page)\n throw error\n } finally {\n entry.durationS = secs(Date.now() - start)\n }\n }\n\n /** A waiting span: real speed in the full video, sped up and labelled in the highlights. */\n async wait<T>(caption: string, work: () => Promise<T>, page?: Page): Promise<T> {\n const label = page ? this.recordedFor(page).label : null\n const chapter: Chapter = { at: Date.now(), caption, label, kind: 'wait', until: Date.now() }\n this.chapters.push(chapter)\n console.log(`[${secs(Date.now() - this.startedAt).toFixed(1)}s] ${label ? `${label}: ` : ''}(wait) ${caption}`)\n try {\n return await work()\n } finally {\n chapter.until = Date.now()\n }\n }\n\n pause(ms = 700): Promise<void> {\n return sleep(ms)\n }\n\n /** Move the visible pointer there, pause, click, pause. */\n async click(target: Locator, opts: { pauseAfter?: number } = {}): Promise<void> {\n await target.scrollIntoViewIfNeeded()\n const box = await target.boundingBox()\n if (box) await target.page().mouse.move(box.x + box.width / 2, box.y + box.height / 2, { steps: 14 })\n await sleep(250)\n await target.click()\n await sleep(opts.pauseAfter ?? 600)\n }\n\n /** Type at a readable pace into an input or textarea. */\n async type(target: Locator, text: string, opts: { delay?: number } = {}): Promise<void> {\n await this.click(target, { pauseAfter: 200 })\n const delay = opts.delay ?? 28\n await target.pressSequentially(text, { delay, timeout: 30_000 + text.length * (delay + 60) })\n await sleep(400)\n }\n\n /** The composer's message input. */\n composerInput(page: Page): Locator {\n return page.locator(this.config.chat.composer).getByRole('textbox', { name: this.config.chat.inputName })\n }\n\n private composerButton(page: Page, name: string): Locator {\n return page.locator(this.config.chat.composer).getByRole('button', { name, exact: true })\n }\n\n /**\n * Type into the chat composer at a readable pace. A line break is typed as\n * Shift+Enter, because Enter sends. Retries fast when hydration dropped\n * keystrokes. Never `fill()` a rich-text composer.\n */\n async typePrompt(page: Page, prompt: string, opts: { delay?: number } = {}): Promise<void> {\n const box = this.composerInput(page)\n await box.waitFor({ state: 'visible', timeout: 30_000 })\n await sleep(1_200)\n const delay = opts.delay ?? (prompt.length > 400 ? 8 : 22)\n const want = prompt.replace(/\\s+/g, ' ').trim().slice(0, 80)\n for (let attempt = 0; attempt < 4; attempt += 1) {\n await this.click(box, { pauseAfter: 150 })\n await box.press('ControlOrMeta+a')\n await box.press('Backspace')\n const lines = prompt.split('\\n')\n for (let i = 0; i < lines.length; i += 1) {\n if (i > 0) await box.press('Shift+Enter')\n // Sized by length: a loaded host types slower than the context's 20 s default allows.\n const line = lines[i]!\n if (line) await box.pressSequentially(line, { delay: attempt === 0 ? delay : 0, timeout: 30_000 + line.length * (delay + 60) })\n }\n const text = (await box.innerText().catch(() => '')).replace(/\\s+/g, ' ').trim()\n if (text.includes(want)) return\n await sleep(1_000)\n }\n throw new Error('the composer never held the prompt')\n }\n\n /**\n * Which parts of the chat contract this page shows, without sending\n * anything. Run it on a second app before trusting turn timings there.\n */\n async checkChatContract(page: Page): Promise<Record<'transcript' | 'composer' | 'input' | 'send', boolean>> {\n const visible = (l: Locator) => l.first().isVisible().catch(() => false)\n return {\n transcript: await visible(page.locator(this.config.chat.transcript)),\n composer: await visible(page.locator(this.config.chat.composer)),\n input: await visible(this.composerInput(page)),\n send: await visible(this.composerButton(page, this.config.chat.sendName)),\n }\n }\n\n /**\n * Desktop screenshot of the recorded page, then the same URL in a phone\n * context (390x844, same identity). Look at both before judging the screen.\n */\n async shot(name: string, page?: Page, opts: { phone?: boolean; fullPage?: boolean; phoneUrl?: string } = {}): Promise<{ desktop: string; phone?: string }> {\n const r = this.recordedFor(page)\n const slug = name.replace(/[^a-z0-9-]+/gi, '-').toLowerCase()\n const desktop = join(this.outDir, `${slug}-desktop.png`)\n const cursor = (display: string) => r.page.evaluate((d) => { const c = document.getElementById('__journey_cursor'); if (c) c.style.display = d }, display).catch(() => {})\n await cursor('none')\n await r.page.screenshot({ path: desktop, fullPage: opts.fullPage ?? false })\n await cursor('')\n if (opts.phone === false) return { desktop }\n const phonePath = join(this.outDir, `${slug}-phone.png`)\n let ctx = this.phones.get(r.identity)\n if (!ctx) {\n const storageState = r.identity === 'anon' ? undefined : (await storageStateFor(this.config, r.identity)).path\n ctx = await this.browser.newContext({ baseURL: this.config.baseUrl, storageState, viewport: PHONE, deviceScaleFactor: 2, isMobile: true, hasTouch: true, locale: 'en-US', timezoneId: 'America/Denver' })\n this.phones.set(r.identity, ctx)\n }\n const phone = await ctx.newPage()\n try {\n await phone.goto(opts.phoneUrl ?? r.page.url(), { waitUntil: 'load' })\n await phone.waitForLoadState('networkidle', { timeout: 8_000 }).catch(() => {})\n await sleep(1_500)\n await phone.screenshot({ path: phonePath, fullPage: opts.fullPage ?? false })\n } finally {\n await phone.close()\n }\n return { desktop, phone: phonePath }\n }\n\n private budgetTurn(): void {\n if (this.turns.length >= this.config.maxTurns) {\n throw new Error(`this journey already sent ${this.turns.length} chat turns, its budget (maxTurns ${this.config.maxTurns})`)\n }\n }\n\n /**\n * Start a new thread: open `from` when given, type the prompt, press Send\n * like a person (again only while the page has not submitted; never deletes\n * a duplicate), wait for the thread, then measure the turn.\n */\n async sendNew(page: Page, prompt: string, opts: SendOptions & { from?: string } = {}): Promise<TurnRecord> {\n this.budgetTurn()\n if (opts.from && !page.url().startsWith(new URL(opts.from, this.config.baseUrl).href)) await page.goto(opts.from)\n await this.typePrompt(page, prompt, { delay: opts.delay })\n const send = this.composerButton(page, this.config.chat.sendName)\n await send.waitFor({ state: 'visible' })\n const box = await send.boundingBox()\n if (box) await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2, { steps: 14 })\n await sleep(400)\n const before = await this.read(page, prompt)\n const evidence = new TurnEvidence(this.patterns(), prompt)\n evidence.begin(before)\n const tracker = createSubmissionTracker(page.url(), this.config.chat.sendPaths)\n const count = (request: { method(): string; url(): string }) => tracker.observe(request.method(), request.url())\n page.on('request', count)\n this.mark(opts.caption ?? `Sends: \"${oneLine(prompt, 90)}\"`, page)\n const sentAt = Date.now()\n const onThread = () => threadRouteIn(page.url(), this.config) !== null\n try {\n await clickUntilSubmitted({\n landed: () => tracker.count > 0 || onThread(),\n ready: () => send.click({ trial: true, timeout: 5_000 }),\n click: () => send.click({ timeout: 5_000 }),\n wait: () => page.waitForRequest((r) => tracker.matches(r.method(), r.url()), { timeout: 1_000 }).then(() => undefined).catch(() => undefined),\n attempts: 15,\n })\n if (this.config.chat.threadPath) await page.waitForURL((url) => threadRouteIn(url.href, this.config) !== null, { timeout: 45_000 })\n } catch (error) {\n return this.notSent(page, prompt, sentAt, String((error as Error).message).slice(0, 300))\n } finally {\n page.off('request', count)\n }\n if (tracker.count > 1) console.warn(`the composer submitted ${tracker.count} times; a duplicate thread may exist (left in place)`)\n return this.measureTurn(page, prompt, sentAt, evidence, before, 0, opts)\n }\n\n /** A follow-up in the open thread: type, one Send press, measure. */\n async sendInThread(page: Page, prompt: string, opts: SendOptions = {}): Promise<TurnRecord> {\n this.budgetTurn()\n await this.typePrompt(page, prompt, { delay: opts.delay })\n const send = this.composerButton(page, this.config.chat.sendName)\n const before = await this.read(page, prompt)\n const evidence = new TurnEvidence(this.patterns(), prompt)\n evidence.begin(before)\n const tracker = createSubmissionTracker(page.url(), this.config.chat.sendPaths)\n const posted = page.waitForRequest((r) => tracker.matches(r.method(), r.url()), { timeout: 30_000 })\n this.mark(opts.caption ?? `Follows up: \"${oneLine(prompt, 90)}\"`, page)\n const sentAt = Date.now()\n await this.click(send, { pauseAfter: 0 })\n const sent = await posted.then(() => true).catch(() => false)\n if (!sent) return this.notSent(page, prompt, sentAt, 'no chat request within 30 s of pressing Send')\n return this.measureTurn(page, prompt, sentAt, evidence, before, Math.max(0, before.assistantChars), opts)\n }\n\n private patterns() {\n return { failure: this.config.chat.failureText, stopped: this.config.chat.stoppedText }\n }\n\n private blankTurn(page: Page, prompt: string, sentAt: number): TurnRecord {\n return {\n label: this.recordedFor(page).label, prompt, threadId: threadRouteIn(page.url(), this.config)?.threadId ?? null,\n sentAt: new Date(sentAt).toISOString(), firstProgressS: null, firstProgressText: null, firstTextS: null, firstFailureS: null, completeS: null,\n outcome: 'timeout', error: null, failures: [], evidenceScope: null, replyChars: 0, stages: [], stopPressedS: null, replyFile: null,\n }\n }\n\n private notSent(page: Page, prompt: string, sentAt: number, why: string): TurnRecord {\n const t = { ...this.blankTurn(page, prompt, sentAt), ...scoreTurn({ notSent: why, timedOut: false, evidence: { failures: [], stopped: [], retryAppeared: false }, replyChars: 0, stopPressed: false }) }\n this.turns.push(t)\n this.mark(`Turn not sent: ${oneLine(why, 90)}`, page)\n return t\n }\n\n /** One read of the transcript, composer and failure marks; with a prompt, the evidence that follows it. */\n private async read(page: Page, prompt: string | null = null): Promise<PageReading> {\n const c = this.config.chat\n const { assistant, ...reading } = await page.evaluate(readChatPage, {\n transcript: c.transcript, status: c.status, failureNodes: c.failureNodes, retrySource: c.retryName.source, retryFlags: c.retryName.flags,\n assistant: c.assistant, composer: c.composer, stopName: c.stopName, promptHead: prompt === null ? null : promptHead(prompt),\n })\n return { ...reading, assistantChars: assistant }\n }\n\n private async runningTurns(page: Page, route: ThreadRoute | null): Promise<string[] | null> {\n if (!route || !this.config.chat.runningTurns) return null\n const res = await page.request.get(this.config.chat.runningTurns(route))\n if (!res.ok()) throw new Error(`running turns answered ${res.status()}`)\n const body = (await res.json()) as { running?: unknown }\n if (!Array.isArray(body.running)) throw new Error('running turns returned no `running` array')\n return body.running.map(String)\n }\n\n /**\n * Time to first visible progress (a new status line or reply text), first\n * reply text, and the turn's end, polled every 300 ms. Failure evidence is\n * read after the turn's own prompt when the page shows it. The turn has ended\n * when, for two reads in a row, {@link turnLooksActive} is false and, where\n * the app lists running turns, the server lists none. Status lines already\n * on the page before Send are not progress. The outcome comes from\n * {@link scoreTurn}.\n */\n private async measureTurn(page: Page, prompt: string, sentAt: number, evidence: TurnEvidence, before: PageReading, baselineChars: number, opts: SendOptions): Promise<TurnRecord> {\n const t = this.blankTurn(page, prompt, sentAt)\n this.turns.push(t)\n const route = threadRouteIn(page.url(), this.config)\n t.threadId = route?.threadId ?? null\n const timeoutMs = opts.timeoutMs ?? 15 * 60_000\n const since = () => secs(Date.now() - sentAt)\n const standingStatus = new Set(before.status)\n // Without an assistant selector, reply text is transcript growth from the\n // first read after Send (the person's own message is on the page by then).\n let growthBase: number | null = null\n let growth = 0\n let sawActive = false\n let quiet = 0\n let lastServerCheck = 0\n let serverRunning: string[] | null = null\n let lastStage = ''\n let lastStatus = ''\n let statusChangedAt = Date.now()\n let finished = false\n await this.wait('Waiting for the agent', async () => {\n while (Date.now() - sentAt < timeoutMs) {\n const s = await this.read(page, prompt).catch(() => null)\n if (s) {\n t.evidenceScope = s.anchored ? 'after-prompt' : 'whole-transcript'\n const shown = evidence.observe(s)\n if (shown.length) {\n t.firstFailureS ??= since()\n this.mark(`Failure shown after ${since()} s: ${oneLine(shown[0]!, 90)}`, page)\n }\n const status = s.status.filter((line) => !standingStatus.has(line))\n growthBase ??= s.transcriptChars\n const chars = s.assistantChars >= 0 ? s.assistantChars - baselineChars : s.transcriptChars - growthBase - status.join(' ').length\n growth = Math.max(growth, chars)\n const stage = status.join(' | ').replace(/\\b\\d+(\\.\\d+)?\\s?s\\b/g, '').trim()\n if (stage && stage !== lastStage) {\n t.stages.push({ s: since(), text: status.join(' | ').slice(0, 160) })\n lastStage = stage\n }\n // Raw text, timers included: a ticking \"Preparing your workspace… 31s\" is changing.\n if (status.join(' | ') !== lastStatus) {\n lastStatus = status.join(' | ')\n statusChangedAt = Date.now()\n }\n if (t.firstProgressS === null && (status.length || chars > 0)) {\n t.firstProgressS = since()\n t.firstProgressText = status[0] ?? 'reply text'\n this.mark(`First visible progress after ${t.firstProgressS} s: ${oneLine(t.firstProgressText, 70)}`, page)\n }\n if (t.firstTextS === null && chars > 0) {\n t.firstTextS = since()\n this.mark(`First text after ${t.firstTextS} s`, page)\n }\n const stopDue = opts.stopAfter === 'first-text' ? t.firstTextS !== null : typeof opts.stopAfter === 'number' && since() >= opts.stopAfter\n if (t.stopPressedS === null && stopDue && s.stopVisible) {\n t.stopPressedS = since()\n this.mark(`Presses Stop after ${t.stopPressedS} s`, page)\n await this.click(this.composerButton(page, this.config.chat.stopName), { pauseAfter: 200 }).catch((e) => console.warn(`Stop press failed: ${e}`))\n }\n if (status.length > 0) sawActive = true\n const active = turnLooksActive({ stopVisible: s.stopVisible, statusLines: status.length, msSinceStatusChanged: Date.now() - statusChangedAt })\n quiet = active ? 0 : quiet + 1\n }\n if (route && this.config.chat.runningTurns && Date.now() - lastServerCheck > 2_000) {\n lastServerCheck = Date.now()\n // A failed read never implies the turn ended.\n serverRunning = await this.runningTurns(page, route).catch(() => serverRunning)\n if (serverRunning?.length) sawActive = true\n }\n const started = sawActive || t.firstTextS !== null || Date.now() - sentAt > 45_000\n const serverDone = !this.config.chat.runningTurns || !route || serverRunning?.length === 0\n if (started && quiet >= 2 && serverDone) {\n finished = true\n return\n }\n await sleep(300)\n }\n }, page)\n t.completeS = finished ? since() : null\n // Render lag only: the turn has ended, so wait for the transcript to stop changing before judging it.\n await settleText(() => this.read(page, prompt).then((r) => `${r.transcriptChars}:${r.failureNodes.length}:${r.retryButtons}`))\n const last = await this.read(page, prompt)\n t.evidenceScope = last.anchored ? 'after-prompt' : 'whole-transcript'\n evidence.observe(last)\n const finalText = this.config.chat.assistant ? await this.replyText(page) : ''\n t.replyChars = this.config.chat.assistant ? Math.max(0, finalText.length - baselineChars) : Math.max(0, growth)\n Object.assign(t, scoreTurn({ timedOut: !finished, evidence: evidence.added(), replyChars: t.replyChars, stopPressed: t.stopPressedS !== null }))\n const n = this.turns.length\n t.replyFile = join('turns', `${String(n).padStart(2, '0')}-${t.label}.md`)\n const reply = this.config.chat.assistant ? finalText.slice(baselineChars).trim() : '(this app configures no assistant selector; read the reply in the video or the trace)'\n const failures = t.failures.length ? `\\n\\n## Failure evidence\\n\\n${t.failures.map((f) => `- ${f}`).join('\\n')}` : ''\n writeFileSync(join(this.outDir, t.replyFile), `# Turn ${n} (${t.label})\\n\\n## Prompt\\n\\n${prompt}\\n\\n## Reply (${t.outcome})\\n\\n${reply}${failures}\\n`)\n this.mark(\n t.outcome === 'completed'\n ? `Turn complete after ${t.completeS} s (${t.replyChars} chars)`\n : `Turn ${t.outcome.toUpperCase()} after ${t.completeS ?? since()} s${t.error ? `: ${oneLine(t.error, 80)}` : ''}`,\n page,\n )\n return t\n }\n\n private async replyText(page: Page): Promise<string> {\n const sel = this.config.chat.assistant\n if (!sel) return ''\n return settleText(async () => (await page.locator(sel).allInnerTexts()).join('\\n').trim())\n }\n\n /**\n * Close everything, then per context: a captioned full .mp4, a highlights cut\n * (at most 178 s, long waits sped up and labelled), an .srt and a scrubbed\n * trace.zip; plus timings.json and chapters.json. Refuses (throws) when any\n * output file still holds a password or cookie value.\n */\n async finish(opts: { speedup2x?: boolean } = {}): Promise<{ outDir: string; files: string[] }> {\n for (const ctx of this.phones.values()) await ctx.close().catch(() => {})\n const files: string[] = []\n // Stop every recording first, so one context's video does not run on through another's processing.\n const stopped: { r: Recorded; rawTrace: string; webm: string | null; endedAt: number }[] = []\n for (const r of this.recorded) {\n const endedAt = Date.now()\n const rawTrace = join(r.rawDir, 'trace.raw.zip')\n await r.context.tracing.stop({ path: rawTrace }).catch((e) => console.warn(`tracing.stop failed for ${r.label}: ${e}`))\n const video = r.page.video()\n await r.context.close()\n stopped.push({ r, rawTrace, webm: video ? await video.path().catch(() => null) : null, endedAt })\n }\n const needles = secretNeedles(this.config)\n for (const { r, rawTrace, webm, endedAt } of stopped) {\n if (webm) {\n files.push(...postProcessVideo({\n webm, workDir: r.rawDir, videoDir: join(this.outDir, 'video'), label: r.label, t0: r.t0,\n wallSeconds: (endedAt - r.t0) / 1000, chapters: this.chapters.filter((c) => c.label === null || c.label === r.label),\n speedup2x: opts.speedup2x ?? false,\n }))\n }\n try {\n const clean = join(this.outDir, 'video', `${r.label}-trace.zip`)\n const result = scrubTrace(rawTrace, clean, [...needles.hard, ...needles.soft])\n console.log(`trace ${r.label}: ${result.entries} entries, ${result.dropped} sensitive bodies dropped, ${result.rewritten} rewritten`)\n files.push(clean)\n } catch (error) {\n console.warn(`trace ${r.label} not written: ${(error as Error).message}`)\n }\n }\n writeFileSync(join(this.outDir, 'chapters.json'), JSON.stringify(this.chapters.map((c) => ({ ...c, at: new Date(c.at).toISOString(), until: c.until ? new Date(c.until).toISOString() : undefined, offsetS: secs(c.at - this.startedAt) })), null, 2))\n writeFileSync(join(this.outDir, 'timings.json'), JSON.stringify({ journey: this.id, app: this.config.app, base: this.config.baseUrl, startedAt: new Date(this.startedAt).toISOString(), wallS: secs(Date.now() - this.startedAt), steps: this.steps, turns: this.turns }, null, 2))\n await this.browser.close()\n assertNoSecrets(this.outDir, needles)\n console.log(`\\n${this.id}: ${this.steps.length} steps, ${this.turns.length} turns, wall ${secs(Date.now() - this.startedAt)} s`)\n for (const t of this.turns) {\n console.log(` turn[${t.label}] ${t.outcome}: progress ${t.firstProgressS ?? '-'} s, first text ${t.firstTextS ?? '-'} s, end ${t.completeS ?? '-'} s, ${t.replyChars} chars${t.error ? ` | ${oneLine(t.error, 100)}` : ''}`)\n }\n const host = process.env.JOURNEYS_HOST_ALIAS ?? hostname()\n console.log(`output: ${this.outDir}\\ncopy it (run where you will watch it):\\n rsync -a ${host}:${this.outDir}/ \"<dest>/${this.id}/\"`)\n return { outDir: this.outDir, files }\n }\n}\n\nexport function oneLine(text: string, max: number): string {\n const s = text.replace(/\\s+/g, ' ').trim()\n return s.length > max ? `${s.slice(0, max - 1)}…` : s\n}\n\n/** Open a journey. Without `config`, reads `journeys.config.mjs` from the working directory. */\nexport async function startJourney(id: string, opts: { config?: JourneysConfig | ResolvedJourneysConfig; cursor?: boolean; headless?: boolean } = {}): Promise<Journey> {\n if (!/^[a-z0-9][a-z0-9-]{1,60}$/.test(id)) throw new Error('journey id: lowercase letters, digits and dashes')\n const config = opts.config ? resolveJourneysConfig(opts.config) : await loadJourneysConfig()\n let chromium\n try {\n chromium = (await import('playwright')).chromium\n } catch {\n throw new Error('journeys need the optional `playwright` peer: install playwright in the app that runs them')\n }\n const browser = await chromium.launch({ headless: opts.headless ?? true })\n return new Journey(id, config, browser, { cursor: opts.cursor ?? true })\n}\n","/**\n * The one read of a chat page a journey takes every 300 ms, run inside the page\n * by `page.evaluate`, so it must stay self-contained: DOM globals only, no\n * imports and no module-scope names.\n *\n * Failure evidence belongs to the turn whose prompt it follows. On 2026-10-11\n * GTM showed a live Stop as a grey notice, then, when the next message was\n * sent, re-rendered the stopped turn with its red \"You stopped this turn.\" card\n * and a Retry control, above the new message. Read from the whole transcript,\n * that card failed the follow-up, which had answered in 28.5 s. So when the\n * transcript shows the turn's own prompt, only failure marks, Retry controls\n * and lines after it count; when it does not, the whole transcript does.\n */\n\ninterface PageReadArgs {\n readonly transcript: string\n readonly status: string\n readonly failureNodes: string\n readonly retrySource: string\n readonly retryFlags: string\n readonly assistant: string | null\n readonly composer: string\n readonly stopName: string\n /** The turn's prompt as {@link promptHead} gives it; null reads the whole transcript. */\n readonly promptHead: string | null\n}\n\ninterface RawPageReading {\n /** Visible transcript lines (after the turn's prompt when `anchored`). */\n lines: string[]\n failureNodes: string[]\n retryButtons: number\n status: string[]\n /** Characters of assistant text on the page, or -1 with no assistant selector. */\n assistant: number\n transcriptChars: number\n stopVisible: boolean\n /** The turn's prompt was found, so the evidence fields hold only what follows it. */\n anchored: boolean\n}\n\n/** The text a transcript shows for a prompt: its first line, whitespace squashed, at most 48 characters. */\nexport function promptHead(prompt: string): string | null {\n const first = prompt.split('\\n').map((line) => line.replace(/\\s+/g, ' ').trim()).find(Boolean)\n return first ? first.slice(0, 48) : null\n}\n\nexport function readChatPage(c: PageReadArgs): RawPageReading {\n const squash = (s: string) => s.replace(/\\s+/g, ' ').trim()\n const clean = (e: Element) => squash(e.textContent ?? '')\n const region = document.querySelector<HTMLElement>(c.transcript)\n const composer = document.querySelector<HTMLElement>(c.composer)\n const assistantNodes = c.assistant ? Array.from(document.querySelectorAll<HTMLElement>(c.assistant)) : []\n const within = (sel: string) => (region ? Array.from(region.querySelectorAll(sel)) : [])\n\n // The last text node outside the composer and the assistant's own text that holds the prompt.\n let anchor: Node | null = null\n if (region && c.promptHead) {\n const walker = document.createTreeWalker(region, NodeFilter.SHOW_TEXT)\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n if (!squash(node.nodeValue ?? '').includes(c.promptHead)) continue\n if (composer?.contains(node) || assistantNodes.some((a) => a.contains(node))) continue\n anchor = node\n }\n }\n const after = (e: Element) => anchor === null || (anchor.compareDocumentPosition(e) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0\n\n const full = region?.innerText ?? ''\n let text = full\n const composerText = composer && region?.contains(composer) ? composer.innerText.trim() : ''\n if (composerText) {\n const at = text.lastIndexOf(composerText)\n if (at >= 0) text = text.slice(0, at) + text.slice(at + composerText.length)\n }\n let lines = text.split('\\n').map((l) => l.trim()).filter(Boolean)\n if (anchor && c.promptHead) {\n // The same rule for lines: the last one holding the prompt that is not the assistant's.\n const replyLines = new Set(assistantNodes.flatMap((a) => a.innerText.split('\\n').map(squash)))\n let last = -1\n for (let i = 0; i < lines.length; i += 1) {\n const line = squash(lines[i]!)\n if (line.includes(c.promptHead) && !replyLines.has(line)) last = i\n }\n lines = lines.slice(last + 1)\n }\n\n const status = within(c.status).map(clean).filter(Boolean)\n // textContent, not innerText: a failure's collapsed details (the code) count too.\n const failureNodes = within(c.failureNodes).filter(after).map(clean).filter(Boolean)\n const retry = new RegExp(c.retrySource, c.retryFlags)\n const retryButtons = within('button').filter((b) => after(b) && retry.test((b.getAttribute('aria-label') ?? b.textContent ?? '').trim())).length\n const assistant = c.assistant ? assistantNodes.map((e) => e.innerText).join('\\n').trim().length : -1\n const stopVisible = composer !== null && Array.from(composer.querySelectorAll('button')).some((b) =>\n (b.getAttribute('aria-label') ?? b.textContent ?? '').trim() === c.stopName && b.getClientRects().length > 0)\n return { lines, failureNodes, retryButtons, status, assistant, transcriptChars: full.trim().length, stopVisible, anchored: anchor !== null }\n}\n","/**\n * Pressing Send like a person, exactly as often as it takes and never once more.\n *\n * A new-chat composer can drop a press while its model selection is still\n * resolving, and its Send control is not disabled while that gate is shut, so\n * one press can be a silent no-op and a retry is necessary. A retry is also\n * dangerous: the press creates a thread, so a press after the page has already\n * submitted asks for a second one. Pure, so the rule is a unit test.\n */\n\n/** Paths a submission from `routePath` lands on: the route itself and its single-fetch `.data` form. */\nexport function routeSubmitPaths(routePath: string): string[] {\n const singleFetch = routePath.endsWith('/') ? `${routePath}_.data` : `${routePath}.data`\n return [routePath, singleFetch]\n}\n\nexport interface SubmissionTracker {\n /** Whether one request is a submission from the tracked page. */\n matches(method: string, url: string): boolean\n observe(method: string, url: string): void\n /** Submissions seen so far. Above zero means the turn is on its way. */\n readonly count: number\n}\n\n/**\n * Counts submissions from the page at `routeUrl`: a POST to that route (or its\n * `.data` form), or to one of `sendPaths`, on the same origin. A POST to the\n * same path on another origin is not this composer's.\n */\nexport function createSubmissionTracker(routeUrl: string, sendPaths: readonly RegExp[]): SubmissionTracker {\n if (!/^https?:\\/\\//i.test(routeUrl)) throw new Error(`createSubmissionTracker needs the page's full URL, got \"${routeUrl}\"`)\n const route = new URL(routeUrl)\n const exact = new Set(routeSubmitPaths(route.pathname))\n let count = 0\n const matches = (method: string, url: string): boolean => {\n if (method !== 'POST') return false\n let parsed: URL\n try {\n parsed = new URL(url, route.origin)\n } catch {\n return false\n }\n if (parsed.origin !== route.origin) return false\n return exact.has(parsed.pathname) || sendPaths.some((p) => p.test(parsed.pathname))\n }\n return {\n matches,\n observe(method, url) {\n if (matches(method, url)) count += 1\n },\n get count() {\n return count\n },\n }\n}\n\nexport interface SendDriveOps {\n /** True once a submission, or the navigation it causes, has been observed. */\n landed: () => boolean\n /** Wait until Send can take a press, without pressing it. */\n ready: () => Promise<void>\n click: () => Promise<void>\n /** Pause between presses, spent watching for the submission. */\n wait: () => Promise<void>\n attempts: number\n}\n\n/**\n * Press until the page submits. Each attempt waits for the control first and\n * takes its last look at `landed()` after that wait, so the press itself is the\n * only unguarded moment. A click failure is tolerated only once something has\n * landed: an accepted send tears the composer down mid-press.\n */\nexport async function clickUntilSubmitted(ops: SendDriveOps): Promise<void> {\n for (let attempt = 0; attempt < ops.attempts; attempt += 1) {\n if (ops.landed()) return\n try {\n await ops.ready()\n if (ops.landed()) return\n await ops.click()\n } catch (cause) {\n if (!ops.landed()) throw cause\n }\n if (ops.landed()) return\n await ops.wait()\n }\n if (ops.landed()) return\n throw new Error(`Send never submitted: the composer refused ${ops.attempts} presses`)\n}\n\n/**\n * Read until the value stops changing: six identical reads 500 ms apart. Every\n * caller has already seen the turn finish, so this covers render lag only.\n */\nexport async function settleText(\n read: () => Promise<string>,\n wait: (ms: number) => Promise<void> = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),\n timeoutMs = 20_000,\n): Promise<string> {\n const deadline = Date.now() + timeoutMs\n let previous: string | null = null\n let stable = 0\n for (;;) {\n const current = await read().catch(() => null)\n if (current === null) {\n stable = 0\n } else {\n stable = current === previous ? stable + 1 : 1\n previous = current\n if (stable >= 6) return current\n }\n if (Date.now() >= deadline) return previous ?? ''\n await wait(500)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,SAAS,WAAW,qBAAqB;AACzC,SAAS,gBAAgB;AACzB,SAAS,YAAY;;;ACsBd,SAAS,WAAW,QAA+B;AACxD,QAAM,QAAQ,OAAO,MAAM,IAAI,EAAE,IAAI,CAAC,SAAS,KAAK,QAAQ,QAAQ,GAAG,EAAE,KAAK,CAAC,EAAE,KAAK,OAAO;AAC7F,SAAO,QAAQ,MAAM,MAAM,GAAG,EAAE,IAAI;AACtC;AAEO,SAAS,aAAa,GAAiC;AAC5D,QAAM,SAAS,CAAC,MAAc,EAAE,QAAQ,QAAQ,GAAG,EAAE,KAAK;AAC1D,QAAM,QAAQ,CAAC,MAAe,OAAO,EAAE,eAAe,EAAE;AACxD,QAAM,SAAS,SAAS,cAA2B,EAAE,UAAU;AAC/D,QAAM,WAAW,SAAS,cAA2B,EAAE,QAAQ;AAC/D,QAAM,iBAAiB,EAAE,YAAY,MAAM,KAAK,SAAS,iBAA8B,EAAE,SAAS,CAAC,IAAI,CAAC;AACxG,QAAM,SAAS,CAAC,QAAiB,SAAS,MAAM,KAAK,OAAO,iBAAiB,GAAG,CAAC,IAAI,CAAC;AAGtF,MAAI,SAAsB;AAC1B,MAAI,UAAU,EAAE,YAAY;AAC1B,UAAM,SAAS,SAAS,iBAAiB,QAAQ,WAAW,SAAS;AACrE,aAAS,OAAO,OAAO,SAAS,GAAG,MAAM,OAAO,OAAO,SAAS,GAAG;AACjE,UAAI,CAAC,OAAO,KAAK,aAAa,EAAE,EAAE,SAAS,EAAE,UAAU,EAAG;AAC1D,UAAI,UAAU,SAAS,IAAI,KAAK,eAAe,KAAK,CAAC,MAAM,EAAE,SAAS,IAAI,CAAC,EAAG;AAC9E,eAAS;AAAA,IACX;AAAA,EACF;AACA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,GAAG;AAAA,EAC1C,QAAQ;AACN,UAAM,IAAI,MAAM,4FAA4F;AAAA,EAC9G;AACA,QAAM,UAAU,MAAM,SAAS,OAAO,EAAE,UAAU,KAAK,YAAY,KAAK,CAAC;AACzE,SAAO,IAAI,QAAQ,IAAI,QAAQ,SAAS,EAAE,QAAQ,KAAK,UAAU,KAAK,CAAC;AACzE;","names":[]}
1
+ {"version":3,"sources":["../../src/journeys/journey.ts","../../src/journeys/page-reading.ts","../../src/journeys/send.ts"],"sourcesContent":["/**\n * One recorded journey through a running agent app: signed-in recorded\n * contexts, chapters, a person's pacing, desktop and phone screenshots,\n * measured chat turns, and a `finish()` that turns the recording into files\n * that are safe to copy off the host.\n *\n * const j = await startJourney('core-path') // reads journeys.config.mjs\n * const page = await j.open('founder', 'member') // recorded, already signed in\n * await j.step('Founder opens the workspace', () => page.goto('/app'), page)\n * await j.shot('home', page) // home-desktop.png + home-phone.png\n * const turn = await j.sendNew(page, 'Research …', { from: `/app/${ws}/chat/new` })\n * await j.finish() // mp4s, srt, highlights, scrubbed trace, timings\n *\n * Output, all safe to copy (finish() refuses otherwise):\n * <outDir>/<id>/video/<label>-full.mp4 <label>-highlights.mp4 <label>.srt <label>-trace.zip\n * <outDir>/<id>/<name>-desktop.png <name>-phone.png timings.json chapters.json turns/*.md\n * Raw webm and unscrubbed traces stay in <stateDir>/raw on the host.\n */\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { hostname } from 'node:os'\nimport { join } from 'node:path'\nimport type { Browser, BrowserContext, Locator, Page } from 'playwright'\nimport { loadJourneysConfig, resolveJourneysConfig, threadRouteIn, type JourneysConfig, type ResolvedJourneysConfig, type ThreadRoute } from './config.js'\nimport { promptHead, readChatPage } from './page-reading.js'\nimport { scoreTurn, turnLooksActive, TurnEvidence, type TranscriptSnapshot, type TurnOutcome } from './score.js'\nimport { assertNoSecrets, scrubTrace } from './scrub.js'\nimport { clickUntilSubmitted, composerText, createSubmissionTracker, settleText } from './send.js'\nimport { secretNeedles, storageStateFor } from './session.js'\nimport { postProcessVideo, type Chapter } from './video.js'\n\nexport const DESKTOP = { width: 1440, height: 900 }\nexport const PHONE = { width: 390, height: 844 }\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))\nconst secs = (ms: number) => Math.round(ms / 100) / 10\n\n/** A visible pointer so a viewer can follow clicks in a headless recording. Hidden for screenshots. */\nconst CURSOR_SCRIPT = `(() => {\n const install = () => {\n if (document.getElementById('__journey_cursor') || !document.body) return\n const dot = document.createElement('div')\n dot.id = '__journey_cursor'\n dot.setAttribute('aria-hidden', 'true')\n Object.assign(dot.style, { position: 'fixed', zIndex: '2147483647', width: '24px', height: '24px',\n margin: '-12px 0 0 -12px', borderRadius: '50%', background: 'rgba(255,72,48,.28)',\n border: '2px solid rgba(255,72,48,.95)', pointerEvents: 'none', left: (window.__jx ?? -100) + 'px',\n top: (window.__jy ?? -100) + 'px', transition: 'transform .12s ease-out' })\n document.body.appendChild(dot)\n }\n addEventListener('mousemove', (e) => { window.__jx = e.clientX; window.__jy = e.clientY\n const d = document.getElementById('__journey_cursor'); if (d) { d.style.left = e.clientX + 'px'; d.style.top = e.clientY + 'px' } }, true)\n addEventListener('mousedown', () => { const d = document.getElementById('__journey_cursor'); if (d) d.style.transform = 'scale(.55)' }, true)\n addEventListener('mouseup', () => { const d = document.getElementById('__journey_cursor'); if (d) d.style.transform = 'scale(1)' }, true)\n // After hydration, so the framework never meets a node it did not render.\n addEventListener('load', () => setTimeout(install, 1500))\n setInterval(install, 2000)\n})()`\n\ninterface Recorded {\n label: string\n identity: string\n context: BrowserContext\n page: Page\n t0: number\n rawDir: string\n}\n\nexport interface TurnRecord {\n label: string\n prompt: string\n threadId: string | null\n sentAt: string\n /** Seconds from the Send press. */\n firstProgressS: number | null\n firstProgressText: string | null\n firstTextS: number | null\n /** Seconds from Send to the first failure evidence on the page, if any appeared. */\n firstFailureS: number | null\n completeS: number | null\n outcome: TurnOutcome\n /** Plain words for what went wrong, or null for a completed turn. */\n error: string | null\n /** Every piece of failure evidence the turn added. */\n failures: string[]\n /** Where evidence was read: after the turn's own prompt, or the whole transcript when the page did not show the prompt. */\n evidenceScope: 'after-prompt' | 'whole-transcript' | null\n replyChars: number\n /** Distinct status lines the transcript showed, with when they appeared. */\n stages: { s: number; text: string }[]\n /** Seconds from Send at which the journey pressed Stop, if it did. */\n stopPressedS: number | null\n replyFile: string | null\n}\n\nexport interface StepRecord {\n caption: string\n label: string | null\n startS: number\n durationS: number\n ok: boolean\n error?: string\n}\n\nexport interface SendOptions {\n caption?: string\n timeoutMs?: number\n /** Keystroke delay for the prompt. */\n delay?: number\n /** Press Stop at first text, or this many seconds after Send. */\n stopAfter?: 'first-text' | number\n}\n\n/** What the page shows right now, read in one evaluate. */\ninterface PageReading extends TranscriptSnapshot {\n status: string[]\n assistantChars: number\n transcriptChars: number\n stopVisible: boolean\n}\n\nexport class Journey {\n readonly outDir: string\n readonly rawDir: string\n readonly chapters: Chapter[] = []\n readonly steps: StepRecord[] = []\n readonly turns: TurnRecord[] = []\n private recorded: Recorded[] = []\n private phones = new Map<string, BrowserContext>()\n private readonly startedAt = Date.now()\n\n constructor(readonly id: string, readonly config: ResolvedJourneysConfig, readonly browser: Browser, private readonly opts: { cursor: boolean }) {\n this.outDir = join(config.outDir, id)\n this.rawDir = join(config.stateDir, 'raw', `${id}-${new Date().toISOString().replace(/[:.]/g, '-')}`)\n mkdirSync(join(this.outDir, 'video'), { recursive: true })\n mkdirSync(join(this.outDir, 'turns'), { recursive: true })\n mkdirSync(this.rawDir, { recursive: true, mode: 0o700 })\n }\n\n /**\n * A recorded, traced 1440x900 context. A config identity starts signed in\n * from the cached session (no login form is ever recorded); `'anon'` starts\n * signed out, for public pages. Open at most two per journey.\n */\n async open(label: string, identity: string, opts: { fresh?: boolean } = {}): Promise<Page> {\n if (this.recorded.some((r) => r.label === label)) throw new Error(`a context labelled ${label} is already open`)\n if (!/^[a-z0-9][a-z0-9-]{0,30}$/.test(label)) throw new Error('context label: lowercase letters, digits and dashes')\n const storageState = identity === 'anon' ? undefined : (await storageStateFor(this.config, identity, opts)).path\n const rawDir = join(this.rawDir, label)\n const context = await this.browser.newContext({\n baseURL: this.config.baseUrl,\n storageState,\n viewport: DESKTOP,\n recordVideo: { dir: rawDir, size: DESKTOP },\n locale: 'en-US',\n timezoneId: 'America/Denver',\n })\n context.setDefaultTimeout(20_000)\n context.setDefaultNavigationTimeout(60_000)\n if (this.opts.cursor) await context.addInitScript(CURSOR_SCRIPT)\n if (process.env.JOURNEY_DEBUG_CLOCK === '1') {\n // Wall-clock seconds since recording start on every frame, for calibrating captions.\n await context.addInitScript((t0: number) => {\n setInterval(() => {\n let d = document.getElementById('__journey_clock')\n if (!d && document.body) {\n d = document.createElement('div')\n d.id = '__journey_clock'\n Object.assign(d.style, { position: 'fixed', left: '50%', top: '0', zIndex: '2147483647', font: 'bold 20px monospace', background: '#ff0', color: '#000', padding: '2px 6px', pointerEvents: 'none' })\n document.body.appendChild(d)\n }\n if (d) d.textContent = ((Date.now() - t0) / 1000).toFixed(1)\n }, 100)\n }, Date.now())\n }\n await context.tracing.start({ screenshots: true, snapshots: true, title: `${this.id} ${label}` })\n const page = await context.newPage()\n this.recorded.push({ label, identity, context, page, t0: Date.now(), rawDir })\n return page\n }\n\n private recordedFor(page?: Page): Recorded {\n const r = page ? this.recorded.find((x) => x.page === page) : this.recorded[0]\n if (!r) throw new Error('no recorded context for that page; call open() first')\n return r\n }\n\n /** A chapter at this instant: one plain line, shown in the caption bar and the .srt. */\n mark(caption: string, page?: Page): void {\n const label = page ? this.recordedFor(page).label : null\n this.chapters.push({ at: Date.now(), caption, label, kind: 'step' })\n console.log(`[${secs(Date.now() - this.startedAt).toFixed(1)}s] ${label ? `${label}: ` : ''}${caption}`)\n }\n\n /** A timed step with its own chapter. A failure is recorded, captioned, then rethrown. */\n async step<T>(caption: string, work: () => Promise<T>, page?: Page): Promise<T> {\n this.mark(caption, page)\n const start = Date.now()\n const entry: StepRecord = { caption, label: page ? this.recordedFor(page).label : null, startS: secs(start - this.startedAt), durationS: 0, ok: true }\n this.steps.push(entry)\n try {\n return await work()\n } catch (error) {\n entry.ok = false\n entry.error = String((error as Error)?.message ?? error).slice(0, 400)\n this.mark(`Step failed: ${caption}`, page)\n throw error\n } finally {\n entry.durationS = secs(Date.now() - start)\n }\n }\n\n /** A waiting span: real speed in the full video, sped up and labelled in the highlights. */\n async wait<T>(caption: string, work: () => Promise<T>, page?: Page): Promise<T> {\n const label = page ? this.recordedFor(page).label : null\n const chapter: Chapter = { at: Date.now(), caption, label, kind: 'wait', until: Date.now() }\n this.chapters.push(chapter)\n console.log(`[${secs(Date.now() - this.startedAt).toFixed(1)}s] ${label ? `${label}: ` : ''}(wait) ${caption}`)\n try {\n return await work()\n } finally {\n chapter.until = Date.now()\n }\n }\n\n pause(ms = 700): Promise<void> {\n return sleep(ms)\n }\n\n /** Move the visible pointer there, pause, click, pause. */\n async click(target: Locator, opts: { pauseAfter?: number } = {}): Promise<void> {\n await target.scrollIntoViewIfNeeded()\n const box = await target.boundingBox()\n if (box) await target.page().mouse.move(box.x + box.width / 2, box.y + box.height / 2, { steps: 14 })\n await sleep(250)\n await target.click()\n await sleep(opts.pauseAfter ?? 600)\n }\n\n /** Type at a readable pace into an input or textarea. */\n async type(target: Locator, text: string, opts: { delay?: number } = {}): Promise<void> {\n await this.click(target, { pauseAfter: 200 })\n const delay = opts.delay ?? 28\n await target.pressSequentially(text, { delay, timeout: 30_000 + text.length * (delay + 60) })\n await sleep(400)\n }\n\n /** The composer's message input. */\n composerInput(page: Page): Locator {\n return page.locator(this.config.chat.composer).getByRole('textbox', { name: this.config.chat.inputName })\n }\n\n private composerButton(page: Page, name: string): Locator {\n return page.locator(this.config.chat.composer).getByRole('button', { name, exact: true })\n }\n\n /**\n * Type into the chat composer at a readable pace. A line break is typed as\n * Shift+Enter, because Enter sends. Retries fast when hydration dropped\n * keystrokes. Never `fill()` a rich-text composer.\n */\n async typePrompt(page: Page, prompt: string, opts: { delay?: number } = {}): Promise<void> {\n const box = this.composerInput(page)\n await box.waitFor({ state: 'visible', timeout: 30_000 })\n await sleep(1_200)\n const delay = opts.delay ?? (prompt.length > 400 ? 8 : 22)\n const want = prompt.replace(/\\s+/g, ' ').trim().slice(0, 80)\n for (let attempt = 0; attempt < 4; attempt += 1) {\n await this.click(box, { pauseAfter: 150 })\n await box.press('ControlOrMeta+a')\n await box.press('Backspace')\n const lines = prompt.split('\\n')\n for (let i = 0; i < lines.length; i += 1) {\n if (i > 0) await box.press('Shift+Enter')\n // Sized by length: a loaded host types slower than the context's 20 s default allows.\n const line = lines[i]!\n if (line) await box.pressSequentially(line, { delay: attempt === 0 ? delay : 0, timeout: 30_000 + line.length * (delay + 60) })\n }\n const text = (await composerText(box).catch(() => '')).replace(/\\s+/g, ' ').trim()\n if (text.includes(want)) return\n await sleep(1_000)\n }\n throw new Error('the composer never held the prompt')\n }\n\n /**\n * Which parts of the chat contract this page shows, without sending\n * anything. Run it on a second app before trusting turn timings there.\n */\n async checkChatContract(page: Page): Promise<Record<'transcript' | 'composer' | 'input' | 'send', boolean>> {\n const visible = (l: Locator) => l.first().isVisible().catch(() => false)\n return {\n transcript: await visible(page.locator(this.config.chat.transcript)),\n composer: await visible(page.locator(this.config.chat.composer)),\n input: await visible(this.composerInput(page)),\n send: await visible(this.composerButton(page, this.config.chat.sendName)),\n }\n }\n\n /**\n * Desktop screenshot of the recorded page, then the same URL in a phone\n * context (390x844, same identity). Look at both before judging the screen.\n */\n async shot(name: string, page?: Page, opts: { phone?: boolean; fullPage?: boolean; phoneUrl?: string } = {}): Promise<{ desktop: string; phone?: string }> {\n const r = this.recordedFor(page)\n const slug = name.replace(/[^a-z0-9-]+/gi, '-').toLowerCase()\n const desktop = join(this.outDir, `${slug}-desktop.png`)\n const cursor = (display: string) => r.page.evaluate((d) => { const c = document.getElementById('__journey_cursor'); if (c) c.style.display = d }, display).catch(() => {})\n await cursor('none')\n await r.page.screenshot({ path: desktop, fullPage: opts.fullPage ?? false })\n await cursor('')\n if (opts.phone === false) return { desktop }\n const phonePath = join(this.outDir, `${slug}-phone.png`)\n let ctx = this.phones.get(r.identity)\n if (!ctx) {\n const storageState = r.identity === 'anon' ? undefined : (await storageStateFor(this.config, r.identity)).path\n ctx = await this.browser.newContext({ baseURL: this.config.baseUrl, storageState, viewport: PHONE, deviceScaleFactor: 2, isMobile: true, hasTouch: true, locale: 'en-US', timezoneId: 'America/Denver' })\n this.phones.set(r.identity, ctx)\n }\n const phone = await ctx.newPage()\n try {\n await phone.goto(opts.phoneUrl ?? r.page.url(), { waitUntil: 'load' })\n await phone.waitForLoadState('networkidle', { timeout: 8_000 }).catch(() => {})\n await sleep(1_500)\n await phone.screenshot({ path: phonePath, fullPage: opts.fullPage ?? false })\n } finally {\n await phone.close()\n }\n return { desktop, phone: phonePath }\n }\n\n private budgetTurn(): void {\n if (this.turns.length >= this.config.maxTurns) {\n throw new Error(`this journey already sent ${this.turns.length} chat turns, its budget (maxTurns ${this.config.maxTurns})`)\n }\n }\n\n /**\n * Start a new thread: open `from` when given, type the prompt, press Send\n * like a person (again only while the page has not submitted; never deletes\n * a duplicate), wait for the thread, then measure the turn.\n */\n async sendNew(page: Page, prompt: string, opts: SendOptions & { from?: string } = {}): Promise<TurnRecord> {\n this.budgetTurn()\n if (opts.from && !page.url().startsWith(new URL(opts.from, this.config.baseUrl).href)) await page.goto(opts.from)\n await this.typePrompt(page, prompt, { delay: opts.delay })\n const send = this.composerButton(page, this.config.chat.sendName)\n await send.waitFor({ state: 'visible' })\n const box = await send.boundingBox()\n if (box) await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2, { steps: 14 })\n await sleep(400)\n const before = await this.read(page, prompt)\n const evidence = new TurnEvidence(this.patterns(), prompt)\n evidence.begin(before)\n const tracker = createSubmissionTracker(page.url(), this.config.chat.sendPaths)\n const count = (request: { method(): string; url(): string }) => tracker.observe(request.method(), request.url())\n page.on('request', count)\n this.mark(opts.caption ?? `Sends: \"${oneLine(prompt, 90)}\"`, page)\n const sentAt = Date.now()\n const onThread = () => threadRouteIn(page.url(), this.config) !== null\n try {\n await clickUntilSubmitted({\n landed: () => tracker.count > 0 || onThread(),\n ready: () => send.click({ trial: true, timeout: 5_000 }),\n click: () => send.click({ timeout: 5_000 }),\n wait: () => page.waitForRequest((r) => tracker.matches(r.method(), r.url()), { timeout: 1_000 }).then(() => undefined).catch(() => undefined),\n attempts: 15,\n })\n if (this.config.chat.threadPath) await page.waitForURL((url) => threadRouteIn(url.href, this.config) !== null, { timeout: 45_000 })\n } catch (error) {\n return this.notSent(page, prompt, sentAt, String((error as Error).message).slice(0, 300))\n } finally {\n page.off('request', count)\n }\n if (tracker.count > 1) console.warn(`the composer submitted ${tracker.count} times; a duplicate thread may exist (left in place)`)\n return this.measureTurn(page, prompt, sentAt, evidence, before, 0, opts)\n }\n\n /** A follow-up in the open thread: type, one Send press, measure. */\n async sendInThread(page: Page, prompt: string, opts: SendOptions = {}): Promise<TurnRecord> {\n this.budgetTurn()\n await this.typePrompt(page, prompt, { delay: opts.delay })\n const send = this.composerButton(page, this.config.chat.sendName)\n const before = await this.read(page, prompt)\n const evidence = new TurnEvidence(this.patterns(), prompt)\n evidence.begin(before)\n const tracker = createSubmissionTracker(page.url(), this.config.chat.sendPaths)\n const posted = page.waitForRequest((r) => tracker.matches(r.method(), r.url()), { timeout: 30_000 })\n this.mark(opts.caption ?? `Follows up: \"${oneLine(prompt, 90)}\"`, page)\n const sentAt = Date.now()\n await this.click(send, { pauseAfter: 0 })\n const sent = await posted.then(() => true).catch(() => false)\n if (!sent) return this.notSent(page, prompt, sentAt, 'no chat request within 30 s of pressing Send')\n return this.measureTurn(page, prompt, sentAt, evidence, before, Math.max(0, before.assistantChars), opts)\n }\n\n private patterns() {\n return { failure: this.config.chat.failureText, stopped: this.config.chat.stoppedText }\n }\n\n private blankTurn(page: Page, prompt: string, sentAt: number): TurnRecord {\n return {\n label: this.recordedFor(page).label, prompt, threadId: threadRouteIn(page.url(), this.config)?.threadId ?? null,\n sentAt: new Date(sentAt).toISOString(), firstProgressS: null, firstProgressText: null, firstTextS: null, firstFailureS: null, completeS: null,\n outcome: 'timeout', error: null, failures: [], evidenceScope: null, replyChars: 0, stages: [], stopPressedS: null, replyFile: null,\n }\n }\n\n private notSent(page: Page, prompt: string, sentAt: number, why: string): TurnRecord {\n const t = { ...this.blankTurn(page, prompt, sentAt), ...scoreTurn({ notSent: why, timedOut: false, evidence: { failures: [], stopped: [], retryAppeared: false }, replyChars: 0, stopPressed: false }) }\n this.turns.push(t)\n this.mark(`Turn not sent: ${oneLine(why, 90)}`, page)\n return t\n }\n\n /** One read of the transcript, composer and failure marks; with a prompt, the evidence that follows it. */\n private async read(page: Page, prompt: string | null = null): Promise<PageReading> {\n const c = this.config.chat\n const { assistant, ...reading } = await page.evaluate(readChatPage, {\n transcript: c.transcript, status: c.status, failureNodes: c.failureNodes, retrySource: c.retryName.source, retryFlags: c.retryName.flags,\n assistant: c.assistant, composer: c.composer, stopName: c.stopName, promptHead: prompt === null ? null : promptHead(prompt),\n })\n return { ...reading, assistantChars: assistant }\n }\n\n private async runningTurns(page: Page, route: ThreadRoute | null): Promise<string[] | null> {\n if (!route || !this.config.chat.runningTurns) return null\n const res = await page.request.get(this.config.chat.runningTurns(route))\n if (!res.ok()) throw new Error(`running turns answered ${res.status()}`)\n const body = (await res.json()) as { running?: unknown }\n if (!Array.isArray(body.running)) throw new Error('running turns returned no `running` array')\n return body.running.map(String)\n }\n\n /**\n * Time to first visible progress (a new status line or reply text), first\n * reply text, and the turn's end, polled every 300 ms. Failure evidence is\n * read after the turn's own prompt when the page shows it. The turn has ended\n * when, for two reads in a row, {@link turnLooksActive} is false and, where\n * the app lists running turns, the server lists none. Status lines already\n * on the page before Send are not progress. The outcome comes from\n * {@link scoreTurn}.\n */\n private async measureTurn(page: Page, prompt: string, sentAt: number, evidence: TurnEvidence, before: PageReading, baselineChars: number, opts: SendOptions): Promise<TurnRecord> {\n const t = this.blankTurn(page, prompt, sentAt)\n this.turns.push(t)\n const route = threadRouteIn(page.url(), this.config)\n t.threadId = route?.threadId ?? null\n const timeoutMs = opts.timeoutMs ?? 15 * 60_000\n const since = () => secs(Date.now() - sentAt)\n const standingStatus = new Set(before.status)\n // Without an assistant selector, reply text is transcript growth from the\n // first read after Send (the person's own message is on the page by then).\n let growthBase: number | null = null\n let growth = 0\n let sawActive = false\n let quiet = 0\n let lastServerCheck = 0\n let serverRunning: string[] | null = null\n let lastStage = ''\n let lastStatus = ''\n let statusChangedAt = Date.now()\n let finished = false\n await this.wait('Waiting for the agent', async () => {\n while (Date.now() - sentAt < timeoutMs) {\n const s = await this.read(page, prompt).catch(() => null)\n if (s) {\n t.evidenceScope = s.anchored ? 'after-prompt' : 'whole-transcript'\n const shown = evidence.observe(s)\n if (shown.length) {\n t.firstFailureS ??= since()\n this.mark(`Failure shown after ${since()} s: ${oneLine(shown[0]!, 90)}`, page)\n }\n const status = s.status.filter((line) => !standingStatus.has(line))\n growthBase ??= s.transcriptChars\n const chars = s.assistantChars >= 0 ? s.assistantChars - baselineChars : s.transcriptChars - growthBase - status.join(' ').length\n growth = Math.max(growth, chars)\n const stage = status.join(' | ').replace(/\\b\\d+(\\.\\d+)?\\s?s\\b/g, '').trim()\n if (stage && stage !== lastStage) {\n t.stages.push({ s: since(), text: status.join(' | ').slice(0, 160) })\n lastStage = stage\n }\n // Raw text, timers included: a ticking \"Preparing your workspace… 31s\" is changing.\n if (status.join(' | ') !== lastStatus) {\n lastStatus = status.join(' | ')\n statusChangedAt = Date.now()\n }\n if (t.firstProgressS === null && (status.length || chars > 0)) {\n t.firstProgressS = since()\n t.firstProgressText = status[0] ?? 'reply text'\n this.mark(`First visible progress after ${t.firstProgressS} s: ${oneLine(t.firstProgressText, 70)}`, page)\n }\n if (t.firstTextS === null && chars > 0) {\n t.firstTextS = since()\n this.mark(`First text after ${t.firstTextS} s`, page)\n }\n const stopDue = opts.stopAfter === 'first-text' ? t.firstTextS !== null : typeof opts.stopAfter === 'number' && since() >= opts.stopAfter\n if (t.stopPressedS === null && stopDue && s.stopVisible) {\n t.stopPressedS = since()\n this.mark(`Presses Stop after ${t.stopPressedS} s`, page)\n await this.click(this.composerButton(page, this.config.chat.stopName), { pauseAfter: 200 }).catch((e) => console.warn(`Stop press failed: ${e}`))\n }\n if (status.length > 0) sawActive = true\n const active = turnLooksActive({ stopVisible: s.stopVisible, statusLines: status.length, msSinceStatusChanged: Date.now() - statusChangedAt })\n quiet = active ? 0 : quiet + 1\n }\n if (route && this.config.chat.runningTurns && Date.now() - lastServerCheck > 2_000) {\n lastServerCheck = Date.now()\n // A failed read never implies the turn ended.\n serverRunning = await this.runningTurns(page, route).catch(() => serverRunning)\n if (serverRunning?.length) sawActive = true\n }\n const started = sawActive || t.firstTextS !== null || Date.now() - sentAt > 45_000\n const serverDone = !this.config.chat.runningTurns || !route || serverRunning?.length === 0\n if (started && quiet >= 2 && serverDone) {\n finished = true\n return\n }\n await sleep(300)\n }\n }, page)\n t.completeS = finished ? since() : null\n // Render lag only: the turn has ended, so wait for the transcript to stop changing before judging it.\n await settleText(() => this.read(page, prompt).then((r) => `${r.transcriptChars}:${r.failureNodes.length}:${r.retryButtons}`))\n const last = await this.read(page, prompt)\n t.evidenceScope = last.anchored ? 'after-prompt' : 'whole-transcript'\n evidence.observe(last)\n const finalText = this.config.chat.assistant ? await this.replyText(page) : ''\n t.replyChars = this.config.chat.assistant ? Math.max(0, finalText.length - baselineChars) : Math.max(0, growth)\n Object.assign(t, scoreTurn({ timedOut: !finished, evidence: evidence.added(), replyChars: t.replyChars, stopPressed: t.stopPressedS !== null }))\n const n = this.turns.length\n t.replyFile = join('turns', `${String(n).padStart(2, '0')}-${t.label}.md`)\n const reply = this.config.chat.assistant ? finalText.slice(baselineChars).trim() : '(this app configures no assistant selector; read the reply in the video or the trace)'\n const failures = t.failures.length ? `\\n\\n## Failure evidence\\n\\n${t.failures.map((f) => `- ${f}`).join('\\n')}` : ''\n writeFileSync(join(this.outDir, t.replyFile), `# Turn ${n} (${t.label})\\n\\n## Prompt\\n\\n${prompt}\\n\\n## Reply (${t.outcome})\\n\\n${reply}${failures}\\n`)\n this.mark(\n t.outcome === 'completed'\n ? `Turn complete after ${t.completeS} s (${t.replyChars} chars)`\n : `Turn ${t.outcome.toUpperCase()} after ${t.completeS ?? since()} s${t.error ? `: ${oneLine(t.error, 80)}` : ''}`,\n page,\n )\n return t\n }\n\n private async replyText(page: Page): Promise<string> {\n const sel = this.config.chat.assistant\n if (!sel) return ''\n return settleText(async () => (await page.locator(sel).allInnerTexts()).join('\\n').trim())\n }\n\n /**\n * Close everything, then per context: a captioned full .mp4, a highlights cut\n * (at most 178 s, long waits sped up and labelled), an .srt and a scrubbed\n * trace.zip; plus timings.json and chapters.json. Refuses (throws) when any\n * output file still holds a password or cookie value.\n */\n async finish(opts: { speedup2x?: boolean } = {}): Promise<{ outDir: string; files: string[] }> {\n for (const ctx of this.phones.values()) await ctx.close().catch(() => {})\n const files: string[] = []\n // Stop every recording first, so one context's video does not run on through another's processing.\n const stopped: { r: Recorded; rawTrace: string; webm: string | null; endedAt: number }[] = []\n for (const r of this.recorded) {\n const endedAt = Date.now()\n const rawTrace = join(r.rawDir, 'trace.raw.zip')\n await r.context.tracing.stop({ path: rawTrace }).catch((e) => console.warn(`tracing.stop failed for ${r.label}: ${e}`))\n const video = r.page.video()\n await r.context.close()\n stopped.push({ r, rawTrace, webm: video ? await video.path().catch(() => null) : null, endedAt })\n }\n const needles = secretNeedles(this.config)\n for (const { r, rawTrace, webm, endedAt } of stopped) {\n if (webm) {\n files.push(...postProcessVideo({\n webm, workDir: r.rawDir, videoDir: join(this.outDir, 'video'), label: r.label, t0: r.t0,\n wallSeconds: (endedAt - r.t0) / 1000, chapters: this.chapters.filter((c) => c.label === null || c.label === r.label),\n speedup2x: opts.speedup2x ?? false,\n }))\n }\n try {\n const clean = join(this.outDir, 'video', `${r.label}-trace.zip`)\n const result = scrubTrace(rawTrace, clean, [...needles.hard, ...needles.soft])\n console.log(`trace ${r.label}: ${result.entries} entries, ${result.dropped} sensitive bodies dropped, ${result.rewritten} rewritten`)\n files.push(clean)\n } catch (error) {\n console.warn(`trace ${r.label} not written: ${(error as Error).message}`)\n }\n }\n writeFileSync(join(this.outDir, 'chapters.json'), JSON.stringify(this.chapters.map((c) => ({ ...c, at: new Date(c.at).toISOString(), until: c.until ? new Date(c.until).toISOString() : undefined, offsetS: secs(c.at - this.startedAt) })), null, 2))\n writeFileSync(join(this.outDir, 'timings.json'), JSON.stringify({ journey: this.id, app: this.config.app, base: this.config.baseUrl, startedAt: new Date(this.startedAt).toISOString(), wallS: secs(Date.now() - this.startedAt), steps: this.steps, turns: this.turns }, null, 2))\n await this.browser.close()\n assertNoSecrets(this.outDir, needles)\n console.log(`\\n${this.id}: ${this.steps.length} steps, ${this.turns.length} turns, wall ${secs(Date.now() - this.startedAt)} s`)\n for (const t of this.turns) {\n console.log(` turn[${t.label}] ${t.outcome}: progress ${t.firstProgressS ?? '-'} s, first text ${t.firstTextS ?? '-'} s, end ${t.completeS ?? '-'} s, ${t.replyChars} chars${t.error ? ` | ${oneLine(t.error, 100)}` : ''}`)\n }\n const host = process.env.JOURNEYS_HOST_ALIAS ?? hostname()\n console.log(`output: ${this.outDir}\\ncopy it (run where you will watch it):\\n rsync -a ${host}:${this.outDir}/ \"<dest>/${this.id}/\"`)\n return { outDir: this.outDir, files }\n }\n}\n\nexport function oneLine(text: string, max: number): string {\n const s = text.replace(/\\s+/g, ' ').trim()\n return s.length > max ? `${s.slice(0, max - 1)}…` : s\n}\n\n/** Open a journey. Without `config`, reads `journeys.config.mjs` from the working directory. */\nexport async function startJourney(id: string, opts: { config?: JourneysConfig | ResolvedJourneysConfig; cursor?: boolean; headless?: boolean } = {}): Promise<Journey> {\n if (!/^[a-z0-9][a-z0-9-]{1,60}$/.test(id)) throw new Error('journey id: lowercase letters, digits and dashes')\n const config = opts.config ? resolveJourneysConfig(opts.config) : await loadJourneysConfig()\n let chromium\n try {\n chromium = (await import('playwright')).chromium\n } catch {\n throw new Error('journeys need the optional `playwright` peer: install playwright in the app that runs them')\n }\n const browser = await chromium.launch({ headless: opts.headless ?? true })\n return new Journey(id, config, browser, { cursor: opts.cursor ?? true })\n}\n","/**\n * The one read of a chat page a journey takes every 300 ms, run inside the page\n * by `page.evaluate`, so it must stay self-contained: DOM globals only, no\n * imports and no module-scope names.\n *\n * Failure evidence belongs to the turn whose prompt it follows. On 2026-10-11\n * GTM showed a live Stop as a grey notice, then, when the next message was\n * sent, re-rendered the stopped turn with its red \"You stopped this turn.\" card\n * and a Retry control, above the new message. Read from the whole transcript,\n * that card failed the follow-up, which had answered in 28.5 s. So when the\n * transcript shows the turn's own prompt, only failure marks, Retry controls\n * and lines after it count; when it does not, the whole transcript does.\n */\n\ninterface PageReadArgs {\n readonly transcript: string\n readonly status: string\n readonly failureNodes: string\n readonly retrySource: string\n readonly retryFlags: string\n readonly assistant: string | null\n readonly composer: string\n readonly stopName: string\n /** The turn's prompt as {@link promptHead} gives it; null reads the whole transcript. */\n readonly promptHead: string | null\n}\n\ninterface RawPageReading {\n /** Visible transcript lines (after the turn's prompt when `anchored`). */\n lines: string[]\n failureNodes: string[]\n retryButtons: number\n status: string[]\n /** Characters of assistant text on the page, or -1 with no assistant selector. */\n assistant: number\n transcriptChars: number\n stopVisible: boolean\n /** The turn's prompt was found, so the evidence fields hold only what follows it. */\n anchored: boolean\n}\n\n/** The text a transcript shows for a prompt: its first line, whitespace squashed, at most 48 characters. */\nexport function promptHead(prompt: string): string | null {\n const first = prompt.split('\\n').map((line) => line.replace(/\\s+/g, ' ').trim()).find(Boolean)\n return first ? first.slice(0, 48) : null\n}\n\nexport function readChatPage(c: PageReadArgs): RawPageReading {\n const squash = (s: string) => s.replace(/\\s+/g, ' ').trim()\n const clean = (e: Element) => squash(e.textContent ?? '')\n const region = document.querySelector<HTMLElement>(c.transcript)\n const composer = document.querySelector<HTMLElement>(c.composer)\n const assistantNodes = c.assistant ? Array.from(document.querySelectorAll<HTMLElement>(c.assistant)) : []\n const within = (sel: string) => (region ? Array.from(region.querySelectorAll(sel)) : [])\n\n // The last text node outside the composer and the assistant's own text that holds the prompt.\n let anchor: Node | null = null\n if (region && c.promptHead) {\n const walker = document.createTreeWalker(region, NodeFilter.SHOW_TEXT)\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n if (!squash(node.nodeValue ?? '').includes(c.promptHead)) continue\n if (composer?.contains(node) || assistantNodes.some((a) => a.contains(node))) continue\n anchor = node\n }\n }\n const after = (e: Element) => anchor === null || (anchor.compareDocumentPosition(e) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0\n\n const full = region?.innerText ?? ''\n let text = full\n const composerText = composer && region?.contains(composer) ? composer.innerText.trim() : ''\n if (composerText) {\n const at = text.lastIndexOf(composerText)\n if (at >= 0) text = text.slice(0, at) + text.slice(at + composerText.length)\n }\n let lines = text.split('\\n').map((l) => l.trim()).filter(Boolean)\n if (anchor && c.promptHead) {\n // The same rule for lines: the last one holding the prompt that is not the assistant's.\n const replyLines = new Set(assistantNodes.flatMap((a) => a.innerText.split('\\n').map(squash)))\n let last = -1\n for (let i = 0; i < lines.length; i += 1) {\n const line = squash(lines[i]!)\n if (line.includes(c.promptHead) && !replyLines.has(line)) last = i\n }\n lines = lines.slice(last + 1)\n }\n\n const status = within(c.status).map(clean).filter(Boolean)\n // textContent, not innerText: a failure's collapsed details (the code) count too.\n const failureNodes = within(c.failureNodes).filter(after).map(clean).filter(Boolean)\n const retry = new RegExp(c.retrySource, c.retryFlags)\n const retryButtons = within('button').filter((b) => after(b) && retry.test((b.getAttribute('aria-label') ?? b.textContent ?? '').trim())).length\n const assistant = c.assistant ? assistantNodes.map((e) => e.innerText).join('\\n').trim().length : -1\n const stopVisible = composer !== null && Array.from(composer.querySelectorAll('button')).some((b) =>\n (b.getAttribute('aria-label') ?? b.textContent ?? '').trim() === c.stopName && b.getClientRects().length > 0)\n return { lines, failureNodes, retryButtons, status, assistant, transcriptChars: full.trim().length, stopVisible, anchored: anchor !== null }\n}\n","/**\n * Pressing Send like a person, exactly as often as it takes and never once more.\n *\n * A new-chat composer can drop a press while its model selection is still\n * resolving, and its Send control is not disabled while that gate is shut, so\n * one press can be a silent no-op and a retry is necessary. A retry is also\n * dangerous: the press creates a thread, so a press after the page has already\n * submitted asks for a second one. Pure, so the rule is a unit test.\n */\n\n/** Paths a submission from `routePath` lands on: the route itself and its single-fetch `.data` form. */\nexport function routeSubmitPaths(routePath: string): string[] {\n const singleFetch = routePath.endsWith('/') ? `${routePath}_.data` : `${routePath}.data`\n return [routePath, singleFetch]\n}\n\nexport interface SubmissionTracker {\n /** Whether one request is a submission from the tracked page. */\n matches(method: string, url: string): boolean\n observe(method: string, url: string): void\n /** Submissions seen so far. Above zero means the turn is on its way. */\n readonly count: number\n}\n\n/**\n * Counts submissions from the page at `routeUrl`: a POST to that route (or its\n * `.data` form), or to one of `sendPaths`, on the same origin. A POST to the\n * same path on another origin is not this composer's.\n */\nexport function createSubmissionTracker(routeUrl: string, sendPaths: readonly RegExp[]): SubmissionTracker {\n if (!/^https?:\\/\\//i.test(routeUrl)) throw new Error(`createSubmissionTracker needs the page's full URL, got \"${routeUrl}\"`)\n const route = new URL(routeUrl)\n const exact = new Set(routeSubmitPaths(route.pathname))\n let count = 0\n const matches = (method: string, url: string): boolean => {\n if (method !== 'POST') return false\n let parsed: URL\n try {\n parsed = new URL(url, route.origin)\n } catch {\n return false\n }\n if (parsed.origin !== route.origin) return false\n return exact.has(parsed.pathname) || sendPaths.some((p) => p.test(parsed.pathname))\n }\n return {\n matches,\n observe(method, url) {\n if (matches(method, url)) count += 1\n },\n get count() {\n return count\n },\n }\n}\n\nexport interface SendDriveOps {\n /** True once a submission, or the navigation it causes, has been observed. */\n landed: () => boolean\n /** Wait until Send can take a press, without pressing it. */\n ready: () => Promise<void>\n click: () => Promise<void>\n /** Pause between presses, spent watching for the submission. */\n wait: () => Promise<void>\n attempts: number\n}\n\n/**\n * Press until the page submits. Each attempt waits for the control first and\n * takes its last look at `landed()` after that wait, so the press itself is the\n * only unguarded moment. A click failure is tolerated only once something has\n * landed: an accepted send tears the composer down mid-press.\n */\nexport async function clickUntilSubmitted(ops: SendDriveOps): Promise<void> {\n for (let attempt = 0; attempt < ops.attempts; attempt += 1) {\n if (ops.landed()) return\n try {\n await ops.ready()\n if (ops.landed()) return\n await ops.click()\n } catch (cause) {\n if (!ops.landed()) throw cause\n }\n if (ops.landed()) return\n await ops.wait()\n }\n if (ops.landed()) return\n throw new Error(`Send never submitted: the composer refused ${ops.attempts} presses`)\n}\n\n/**\n * Read until the value stops changing: six identical reads 500 ms apart. Every\n * caller has already seen the turn finish, so this covers render lag only.\n */\nexport async function settleText(\n read: () => Promise<string>,\n wait: (ms: number) => Promise<void> = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),\n timeoutMs = 20_000,\n): Promise<string> {\n const deadline = Date.now() + timeoutMs\n let previous: string | null = null\n let stable = 0\n for (;;) {\n const current = await read().catch(() => null)\n if (current === null) {\n stable = 0\n } else {\n stable = current === previous ? stable + 1 : 1\n previous = current\n if (stable >= 6) return current\n }\n if (Date.now() >= deadline) return previous ?? ''\n await wait(500)\n }\n}\n\n/**\n * The text a composer holds. A `<textarea>` or `<input>` (agent-app's own\n * ChatComposer) keeps typed text in `.value` and leaves `innerText` empty; a\n * contenteditable composer keeps it in `innerText`. Reading only `innerText`\n * failed every first chat turn on the default composer (Casework C1/C5,\n * 2026-10-12).\n */\nexport async function composerText(box: { evaluate<R>(fn: (el: Element) => R): Promise<R> }): Promise<string> {\n return box.evaluate((el) => {\n const field = el as Element & { value?: unknown; innerText?: string }\n return typeof field.value === 'string' ? field.value : (field.innerText ?? el.textContent ?? '')\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,SAAS,WAAW,qBAAqB;AACzC,SAAS,gBAAgB;AACzB,SAAS,YAAY;;;ACsBd,SAAS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A,EAC9G;AACA,QAAM,UAAU,MAAM,SAAS,OAAO,EAAE,UAAU,KAAK,YAAY,KAAK,CAAC;AACzE,SAAO,IAAI,QAAQ,IAAI,QAAQ,SAAS,EAAE,QAAQ,KAAK,UAAU,KAAK,CAAC;AACzE;","names":["composerText"]}
@@ -44,3 +44,13 @@ export declare function clickUntilSubmitted(ops: SendDriveOps): Promise<void>;
44
44
  * caller has already seen the turn finish, so this covers render lag only.
45
45
  */
46
46
  export declare function settleText(read: () => Promise<string>, wait?: (ms: number) => Promise<void>, timeoutMs?: number): Promise<string>;
47
+ /**
48
+ * The text a composer holds. A `<textarea>` or `<input>` (agent-app's own
49
+ * ChatComposer) keeps typed text in `.value` and leaves `innerText` empty; a
50
+ * contenteditable composer keeps it in `innerText`. Reading only `innerText`
51
+ * failed every first chat turn on the default composer (Casework C1/C5,
52
+ * 2026-10-12).
53
+ */
54
+ export declare function composerText(box: {
55
+ evaluate<R>(fn: (el: Element) => R): Promise<R>;
56
+ }): Promise<string>;