@ixo/editor 5.10.1 → 5.11.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/lib/flowCompiler/resolveRefs.ts","../src/core/lib/flowAgent/store.ts","../src/core/lib/flowAgent/utils.ts","../src/core/lib/flowAgent/policy.ts","../src/core/lib/flowAgent/commands.ts","../src/core/lib/flowAgent/context.ts","../src/core/lib/flowAgent/lease.ts","../src/core/lib/flowAgent/state.ts","../src/core/lib/flowAgent/orchestrator.ts","../src/core/lib/flowAgent/service.ts"],"sourcesContent":["import { isRuntimeRef } from '../../types/baseUcan';\n\n/**\n * Context passed to resolveRuntimeRefs when resolving inputs for a triggered\n * listener block. The runtime constructs this from a PendingInvocation when\n * the assignee invokes the listener.\n *\n * - `payload`: the frozen event payload, used to resolve `trigger.payload.*` refs\n * - `refSnapshots`: frozen `nodeId.output.*` values captured at queue time,\n * used to resolve those refs against the moment of emission rather than\n * current state. See docs/events-and-triggers-plan.md §3.5.1 for the\n * Sally → Mike scenario this fixes.\n */\nexport interface TriggerResolutionContext {\n payload: Record<string, unknown>;\n refSnapshots: Record<string, unknown>;\n}\n\n/**\n * Resolve runtime references in an nb (caveats) object.\n *\n * At compile time, `{ \"$ref\": \"nodeId.output.fieldPath\" }` values are serialized\n * as-is into the block's `inputs` JSON string. At execution time, this function\n * replaces them with actual output values from upstream nodes.\n *\n * Two ref namespaces are supported:\n * - `nodeId.output.fieldPath` — looked up via `getNodeOutput`. When a\n * `triggerContext` is provided AND `refSnapshots[ref]` exists, the\n * snapshot is preferred over the live lookup. This is the load-bearing\n * fix for the lag-time scenario where multiple pending invocations are\n * queued and the source block re-runs before the assignee acts on them.\n * - `trigger.payload.fieldPath` — looked up in `triggerContext.payload`.\n * Only valid when `triggerContext` is provided (i.e. resolving inputs\n * for a triggered listener invocation). Compile-time validation in\n * compiler.ts guarantees these only appear on `block.event`-triggered\n * blocks.\n *\n * @param nb - The caveats object (may contain nested RuntimeRef values)\n * @param getNodeOutput - Lookup function for upstream node outputs\n * @param triggerContext - Optional, present only for triggered listener invocations\n * @returns A new object with all $ref values resolved\n */\nexport function resolveRuntimeRefs(\n nb: Record<string, unknown>,\n getNodeOutput: (nodeId: string) => Record<string, unknown> | undefined,\n triggerContext?: TriggerResolutionContext\n): Record<string, unknown> {\n return resolveValue(nb, getNodeOutput, triggerContext) as Record<string, unknown>;\n}\n\nfunction resolveValue(value: unknown, getNodeOutput: (nodeId: string) => Record<string, unknown> | undefined, triggerContext?: TriggerResolutionContext): unknown {\n if (isRuntimeRef(value)) {\n return resolveRef(value.$ref, getNodeOutput, triggerContext);\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => resolveValue(item, getNodeOutput, triggerContext));\n }\n\n if (typeof value === 'object' && value !== null) {\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n result[key] = resolveValue(val, getNodeOutput, triggerContext);\n }\n return result;\n }\n\n return value;\n}\n\n/**\n * Resolve a single $ref string.\n *\n * Supported forms:\n * - \"trigger.payload.fieldPath\" — looked up in triggerContext.payload\n * - \"nodeId.output.fieldPath\" — looked up in triggerContext.refSnapshots first\n * (if present), falling back to getNodeOutput. Snapshot preference is\n * what makes the Sally → Mike scenario produce frozen values per pending\n * invocation.\n */\nfunction resolveRef(ref: string, getNodeOutput: (nodeId: string) => Record<string, unknown> | undefined, triggerContext?: TriggerResolutionContext): unknown {\n // trigger.payload.* — only valid when a triggerContext is provided\n if (ref.startsWith('trigger.payload.')) {\n if (!triggerContext) {\n throw new Error(`Trigger ref \"${ref}\" used outside of a listener invocation context. trigger.payload.* refs are only valid on block.event-triggered blocks.`);\n }\n const fieldPath = ref.slice('trigger.payload.'.length);\n return getNestedValue(triggerContext.payload, fieldPath);\n }\n\n // nodeId.output.fieldPath — prefer the snapshot if we're inside a trigger context\n if (triggerContext && Object.prototype.hasOwnProperty.call(triggerContext.refSnapshots, ref)) {\n return triggerContext.refSnapshots[ref];\n }\n\n // Parse \"nodeId.output.fieldPath\"\n const outputIndex = ref.indexOf('.output.');\n if (outputIndex === -1) {\n throw new Error(`Invalid runtime reference \"${ref}\". Expected format: \"nodeId.output.fieldPath\" or \"trigger.payload.fieldPath\"`);\n }\n\n const nodeId = ref.slice(0, outputIndex);\n const fieldPath = ref.slice(outputIndex + '.output.'.length);\n\n const output = getNodeOutput(nodeId);\n if (!output) {\n return undefined;\n }\n\n // Traverse the field path (supports dot notation)\n return getNestedValue(output, fieldPath);\n}\n\nfunction getNestedValue(obj: Record<string, unknown>, path: string): unknown {\n const parts = path.split('.');\n let current: unknown = obj;\n\n for (const part of parts) {\n if (current == null || typeof current !== 'object') {\n return undefined;\n }\n current = (current as Record<string, unknown>)[part];\n }\n\n return current;\n}\n","import * as Y from 'yjs';\nimport type { Doc } from 'yjs';\nimport type { FlowAgentCommand, FlowAgentLedgerEvent, FlowAgentLedgerEventType, FlowAgentMaps } from '../../types/flowAgent';\nimport { createIntentHash, stableStringify } from './utils';\n\nexport const FLOW_AGENT_OUTBOX_KEY = 'agentOutbox';\nexport const FLOW_AGENT_LEASES_KEY = 'agentLeases';\nexport const FLOW_AGENT_AUDIT_SCOPE = '__flow_agent__';\n\nexport function getFlowAgentMaps(yDoc: Doc): FlowAgentMaps {\n return {\n outbox: yDoc.getMap<FlowAgentCommand>(FLOW_AGENT_OUTBOX_KEY),\n leases: yDoc.getMap(FLOW_AGENT_LEASES_KEY),\n };\n}\n\nexport function computeAgentCommandId(params: { flowId: string; nodeId: string; type: string; payload: Record<string, unknown> }): string {\n const intentHash = createIntentHash(params);\n return `${params.flowId}:${params.nodeId}:${intentHash}`;\n}\n\nexport function queueAgentCommand(yDoc: Doc, command: FlowAgentCommand): { command: FlowAgentCommand; created: boolean } {\n const { outbox } = getFlowAgentMaps(yDoc);\n const existing = outbox.get(command.id);\n if (existing) return { command: existing, created: false };\n outbox.set(command.id, command);\n appendAgentLedgerEvent(yDoc, {\n type: 'agent.command',\n flowId: command.flowId,\n nodeId: command.nodeId,\n commandId: command.id,\n actorDid: command.actorDid,\n timestamp: command.createdAt,\n details: {\n commandType: command.type,\n status: command.status,\n idempotencyKey: command.idempotencyKey,\n reason: command.reason,\n },\n });\n return { command, created: true };\n}\n\nexport function readQueuedAgentCommands(yDoc: Doc): FlowAgentCommand[] {\n const { outbox } = getFlowAgentMaps(yDoc);\n const commands: FlowAgentCommand[] = [];\n outbox.forEach((command) => {\n if (command.status === 'queued' || command.status === 'leased' || command.status === 'running') {\n commands.push(command);\n }\n });\n commands.sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id));\n return commands;\n}\n\nexport function updateAgentCommand(yDoc: Doc, commandId: string, patch: Partial<FlowAgentCommand>): FlowAgentCommand | null {\n const { outbox } = getFlowAgentMaps(yDoc);\n const current = outbox.get(commandId);\n if (!current) return null;\n const next = { ...current, ...patch };\n outbox.set(commandId, next);\n return next;\n}\n\nexport function appendAgentLedgerEvent(\n yDoc: Doc,\n event: Omit<FlowAgentLedgerEvent, 'id'> & {\n id?: string;\n }\n): FlowAgentLedgerEvent {\n const auditMap = yDoc.getMap<Y.Array<unknown>>('auditTrail');\n let arr = auditMap.get(FLOW_AGENT_AUDIT_SCOPE);\n if (!arr) {\n arr = new Y.Array<unknown>();\n auditMap.set(FLOW_AGENT_AUDIT_SCOPE, arr);\n }\n\n const fullEvent: FlowAgentLedgerEvent = {\n id: event.id || `${event.type}:${event.commandId || event.nodeId || 'flow'}:${createIntentHash(event.details)}:${event.timestamp}`,\n type: event.type,\n flowId: event.flowId,\n actorDid: event.actorDid,\n timestamp: event.timestamp,\n details: JSON.parse(stableStringify(event.details)) as Record<string, unknown>,\n };\n\n if (event.nodeId) fullEvent.nodeId = event.nodeId;\n if (event.commandId) fullEvent.commandId = event.commandId;\n\n arr.push([\n {\n id: fullEvent.id,\n type: fullEvent.type,\n details: fullEvent,\n meta: {\n timestamp: new Date(fullEvent.timestamp).toISOString(),\n userId: fullEvent.actorDid,\n editable: false,\n },\n },\n ]);\n\n return fullEvent;\n}\n\nexport function readAgentLedgerEvents(yDoc: Doc, eventType?: FlowAgentLedgerEventType): FlowAgentLedgerEvent[] {\n const auditMap = yDoc.getMap<Y.Array<unknown>>('auditTrail');\n const arr = auditMap.get(FLOW_AGENT_AUDIT_SCOPE);\n if (!arr) return [];\n const events: FlowAgentLedgerEvent[] = [];\n arr.forEach((value) => {\n if (!value || typeof value !== 'object') return;\n const entry = value as { type?: string; details?: FlowAgentLedgerEvent };\n if (!entry.details) return;\n if (eventType && entry.details.type !== eventType) return;\n events.push(entry.details);\n });\n events.sort((a, b) => a.timestamp - b.timestamp || a.id.localeCompare(b.id));\n return events;\n}\n","import type { Block } from '@blocknote/core';\nimport type { UcanCapability } from '../../types/ucan';\n\nexport function stableStringify(value: unknown): string {\n if (value === undefined) return 'null';\n if (value === null || typeof value !== 'object') {\n return JSON.stringify(value);\n }\n\n if (Array.isArray(value)) {\n return `[${value.map((item) => stableStringify(item)).join(',')}]`;\n }\n\n const entries = Object.entries(value as Record<string, unknown>).sort(([a], [b]) => a.localeCompare(b));\n return `{${entries.map(([key, val]) => `${JSON.stringify(key)}:${stableStringify(val)}`).join(',')}}`;\n}\n\nexport function fnv1a32(input: string): string {\n let hash = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return (hash >>> 0).toString(16).padStart(8, '0');\n}\n\nexport function createIntentHash(intent: Record<string, unknown>): string {\n return fnv1a32(stableStringify(intent));\n}\n\nexport function parseJsonProp<T>(value: unknown, fallback: T): T {\n if (value == null || value === '') return fallback;\n if (typeof value === 'object') return value as T;\n if (typeof value !== 'string') return fallback;\n try {\n const parsed = JSON.parse(value);\n return parsed as T;\n } catch {\n return fallback;\n }\n}\n\nexport function getBlockActionType(block: unknown): string | undefined {\n const props = (block as { props?: Record<string, unknown> })?.props;\n const actionType = props?.actionType;\n return typeof actionType === 'string' && actionType.length > 0 ? actionType : undefined;\n}\n\nexport function getBlockTitle(block: unknown): string | undefined {\n const props = (block as { props?: Record<string, unknown> })?.props;\n const title = props?.title;\n return typeof title === 'string' && title.length > 0 ? title : undefined;\n}\n\nexport function getBlockType(block: unknown): string {\n const type = (block as { type?: string })?.type;\n return typeof type === 'string' && type.length > 0 ? type : 'block';\n}\n\nexport function getBlockProps(block: unknown): Record<string, unknown> {\n return ((block as { props?: Record<string, unknown> })?.props || {}) as Record<string, unknown>;\n}\n\nexport function getBlockId(block: unknown): string | undefined {\n const id = (block as { id?: string })?.id;\n return typeof id === 'string' && id.length > 0 ? id : undefined;\n}\n\nexport function getAssigneeDid(block: unknown): string | undefined {\n const props = getBlockProps(block);\n const assignment = parseJsonProp<Record<string, any>>(props.assignment, {});\n const did = assignment?.assignedActor?.did;\n return typeof did === 'string' && did.length > 0 ? did : undefined;\n}\n\nexport function getDueAt(block: unknown): number | undefined {\n const props = getBlockProps(block);\n const ttlAbsoluteDueDate = props.ttlAbsoluteDueDate;\n if (typeof ttlAbsoluteDueDate !== 'string' || ttlAbsoluteDueDate.length === 0) return undefined;\n const parsed = new Date(ttlAbsoluteDueDate).getTime();\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\nexport function normalizeBlocks(blocks: unknown[]): Block[] {\n return blocks.filter((block) => typeof getBlockId(block) === 'string') as Block[];\n}\n\nexport function capabilityForCommand(can: string, flowUri: string, nodeId: string): UcanCapability {\n return {\n can,\n with: `${flowUri}:${nodeId}`,\n };\n}\n","import type { FlowAgentCommandType, FlowAgentPolicyDecision } from '../../types/flowAgent';\nimport type { StoredDelegation, UcanCapability } from '../../types/ucan';\nimport type { UcanDelegationStore } from '../ucanDelegationStore';\nimport { capabilityForCommand } from './utils';\n\nconst COMMAND_CAPABILITIES: Record<FlowAgentCommandType, string> = {\n diagnose_blocker: 'flow/observe',\n assign_actor: 'flow/node/assign',\n notify_actor: 'flow/notify',\n execute_action: 'flow/node/execute',\n validate_external_state: 'flow/mutation/execute',\n submit_claim: 'flow/claim/submit',\n watch_udid: 'flow/observe',\n archive_flow: 'flow/archive',\n propose_config_change: 'flow/config/propose',\n};\n\nexport function requiredCapabilityForCommand(type: FlowAgentCommandType, flowUri: string, nodeId: string): UcanCapability {\n return capabilityForCommand(COMMAND_CAPABILITIES[type], flowUri, nodeId);\n}\n\nexport function isCapabilityMatch(granted: UcanCapability, required: UcanCapability): boolean {\n return canMatches(granted.can, required.can) && resourceMatches(granted.with, required.with);\n}\n\nexport function canMatches(granted: string, required: string): boolean {\n if (granted === '*' || granted === required) return true;\n if (granted.endsWith('/*')) {\n const prefix = granted.slice(0, -1);\n return required.startsWith(prefix);\n }\n return false;\n}\n\nexport function resourceMatches(granted: string, required: string): boolean {\n if (granted === '*' || granted === required) return true;\n if (granted.endsWith('*')) {\n const prefix = granted.slice(0, -1);\n return required.startsWith(prefix);\n }\n return false;\n}\n\nexport interface EvaluateFlowAgentPolicyParams {\n actorDid: string;\n commandType: FlowAgentCommandType;\n flowUri: string;\n nodeId: string;\n delegationStore?: UcanDelegationStore;\n delegations?: StoredDelegation[];\n now?: number;\n}\n\nexport function evaluateFlowAgentPolicy({\n actorDid,\n commandType,\n flowUri,\n nodeId,\n delegationStore,\n delegations,\n now = Date.now(),\n}: EvaluateFlowAgentPolicyParams): FlowAgentPolicyDecision {\n const required = requiredCapabilityForCommand(commandType, flowUri, nodeId);\n const candidates = delegations || delegationStore?.getByAudience(actorDid) || [];\n\n for (const delegation of candidates) {\n if (delegation.audienceDid !== actorDid) continue;\n if (delegation.expiration != null && delegation.expiration <= now) continue;\n if (!delegation.capabilities.some((capability) => isCapabilityMatch(capability, required))) continue;\n\n return {\n allowed: true,\n reason: 'Allowed by UCAN delegation',\n capability: required,\n proofCids: [delegation.cid, ...delegation.proofCids],\n };\n }\n\n return {\n allowed: false,\n reason: `Actor ${actorDid} lacks ${required.can} on ${required.with}`,\n capability: required,\n proofCids: [],\n };\n}\n","import type { FlowAgentActor, FlowAgentCommand, FlowAgentCommandType } from '../../types/flowAgent';\nimport type { UcanCapability } from '../../types/ucan';\nimport { computeAgentCommandId } from './store';\nimport { requiredCapabilityForCommand } from './policy';\nimport { createIntentHash } from './utils';\n\nexport interface CreateAgentCommandParams {\n type: FlowAgentCommandType;\n flowId: string;\n flowUri: string;\n nodeId: string;\n actor: FlowAgentActor;\n reason: string;\n payload?: Record<string, unknown>;\n now?: number;\n}\n\nexport function createAgentCommand({ type, flowId, flowUri, nodeId, actor, reason, payload = {}, now = Date.now() }: CreateAgentCommandParams): FlowAgentCommand {\n const capability: UcanCapability = requiredCapabilityForCommand(type, flowUri, nodeId);\n const id = computeAgentCommandId({ flowId, nodeId, type, payload });\n return {\n id,\n type,\n flowId,\n flowUri,\n nodeId,\n actorDid: actor.did,\n status: 'queued',\n capability,\n idempotencyKey: `${id}:${createIntentHash({ capability, payload })}`,\n createdAt: now,\n updatedAt: now,\n reason,\n payload,\n };\n}\n\nexport function validateAgentCommand(command: FlowAgentCommand): { valid: boolean; error?: string } {\n if (!command.id) return { valid: false, error: 'Command id is required' };\n if (!command.flowId) return { valid: false, error: 'flowId is required' };\n if (!command.flowUri) return { valid: false, error: 'flowUri is required' };\n if (!command.nodeId) return { valid: false, error: 'nodeId is required' };\n if (!command.actorDid) return { valid: false, error: 'actorDid is required' };\n if (!command.capability?.can || !command.capability?.with) return { valid: false, error: 'capability is required' };\n if (!command.idempotencyKey) return { valid: false, error: 'idempotencyKey is required' };\n\n if (isExternalMutation(command.type) && !command.payload.validator) {\n return {\n valid: false,\n error: `${command.type} requires payload.validator for post-action read-back validation`,\n };\n }\n\n if (command.type === 'propose_config_change' && !command.payload.proposal) {\n return { valid: false, error: 'Config changes must be expressed as payload.proposal' };\n }\n\n return { valid: true };\n}\n\nexport function isExternalMutation(type: FlowAgentCommandType): boolean {\n return type === 'validate_external_state';\n}\n","import type { FlowAgentActor, FlowAgentContext } from '../../types/flowAgent';\nimport type { IxoEditorType } from '../../types/editor';\nimport type { Doc } from 'yjs';\n\nexport interface BuildFlowAgentContextParams {\n yDoc: Doc;\n flowId: string;\n flowUri?: string;\n actor: FlowAgentActor;\n blocks?: unknown[];\n editor?: IxoEditorType;\n now?: () => number;\n}\n\n/**\n * Builds the host-facing runtime context expected by the Flow Agent.\n *\n * Headless hosts own Matrix login, room joins, and Y.Doc sync. Once a host has\n * a live room document and an agent identity, this helper gives it the stable\n * context shape to pass into `tickFlowAgent` or `FlowAgentService`.\n */\nexport function buildFlowAgentContext({ yDoc, flowId, flowUri = `ixo:flow:${flowId}`, actor, blocks, editor, now }: BuildFlowAgentContextParams): FlowAgentContext {\n return {\n yDoc,\n flowId,\n flowUri,\n actor,\n ...(blocks ? { blocks } : {}),\n ...(editor ? { editor } : {}),\n ...(now ? { now } : {}),\n };\n}\n","import type { Map as YMap } from 'yjs';\nimport type { FlowAgentLease } from '../../types/flowAgent';\n\nexport const DEFAULT_FLOW_AGENT_LEASE_TTL_MS = 60_000;\n\nexport interface AcquireFlowAgentLeaseParams {\n leases: YMap<FlowAgentLease>;\n commandId: string;\n nodeId: string;\n actorDid: string;\n now?: number;\n ttlMs?: number;\n}\n\nexport function acquireFlowAgentLease({\n leases,\n commandId,\n nodeId,\n actorDid,\n now = Date.now(),\n ttlMs = DEFAULT_FLOW_AGENT_LEASE_TTL_MS,\n}: AcquireFlowAgentLeaseParams): FlowAgentLease | null {\n const current = leases.get(commandId);\n if (current && current.expiresAt > now && current.actorDid !== actorDid) {\n return null;\n }\n\n const nextEpoch = current ? current.epoch + 1 : 1;\n const lease: FlowAgentLease = {\n id: `${commandId}:lease:${nextEpoch}`,\n commandId,\n nodeId,\n actorDid,\n acquiredAt: now,\n expiresAt: now + ttlMs,\n epoch: nextEpoch,\n };\n\n leases.set(commandId, lease);\n return lease;\n}\n\nexport function validateFlowAgentLease(leases: YMap<FlowAgentLease>, lease: FlowAgentLease, now = Date.now()): boolean {\n const current = leases.get(lease.commandId);\n return !!current && current.actorDid === lease.actorDid && current.epoch === lease.epoch && current.expiresAt > now;\n}\n\nexport function releaseFlowAgentLease(leases: YMap<FlowAgentLease>, lease: FlowAgentLease): boolean {\n const current = leases.get(lease.commandId);\n if (!current || current.actorDid !== lease.actorDid || current.epoch !== lease.epoch) return false;\n leases.delete(lease.commandId);\n return true;\n}\n\nexport function cleanupExpiredFlowAgentLeases(leases: YMap<FlowAgentLease>, now = Date.now()): FlowAgentLease[] {\n const expired: FlowAgentLease[] = [];\n leases.forEach((lease, commandId) => {\n if (lease.expiresAt <= now) {\n expired.push(lease);\n leases.delete(commandId);\n }\n });\n return expired;\n}\n","import type { FlowNodeRuntimeState } from '../../types/authorization';\nimport type { FlowAgentBlockerCause, FlowAgentNodeSnapshot, FlowAgentPublicNodeState } from '../../types/flowAgent';\nimport { getAssigneeDid, getBlockActionType, getBlockId, getBlockTitle, getBlockType, getDueAt, getBlockProps, parseJsonProp } from './utils';\n\ninterface ConditionConfig {\n enabled?: boolean;\n conditions?: Array<Record<string, unknown>>;\n}\n\nexport interface ClassifyNodeStateInput {\n block: unknown;\n runtime: FlowNodeRuntimeState;\n now: number;\n pendingInvocationCount?: number;\n}\n\nexport function classifyBlockerCause(block: unknown, runtime: FlowNodeRuntimeState): FlowAgentBlockerCause | undefined {\n const props = getBlockProps(block);\n if (runtime.error?.code === 'missing_ucan') return 'missing_ucan';\n if (runtime.error?.code === 'validation_mismatch') return 'validation_mismatch';\n if (runtime.error?.code === 'external_confirmation_pending') return 'external_confirmation_pending';\n if (runtime.error) return 'service_error';\n\n const conditions = parseJsonProp<ConditionConfig>(props.conditions, {});\n if (conditions.enabled && Array.isArray(conditions.conditions) && conditions.conditions.length > 0) {\n return 'failed_upstream';\n }\n\n const inputs = parseJsonProp<Record<string, unknown>>(props.inputs, {});\n const requiredInputs = parseJsonProp<string[]>(props.requiredInputs, []);\n if (requiredInputs.some((key) => inputs[key] == null || inputs[key] === '')) {\n return 'missing_input';\n }\n\n return undefined;\n}\n\nexport function classifyNodeState({ block, runtime, now, pendingInvocationCount = 0 }: ClassifyNodeStateInput): FlowAgentPublicNodeState {\n if (runtime.state === 'completed' || runtime.state === 'cancelled') return 'Done';\n if (runtime.state === 'failed' || runtime.error) return 'Blocked';\n\n const dueAt = getDueAt(block);\n if (dueAt != null && dueAt <= now) return 'Overdue';\n\n if (pendingInvocationCount > 0) return 'Pending';\n return 'Pending';\n}\n\nexport function snapshotNode(block: unknown, runtime: FlowNodeRuntimeState, now: number, pendingInvocationCount = 0): FlowAgentNodeSnapshot {\n const nodeId = getBlockId(block);\n if (!nodeId) {\n throw new Error('Cannot snapshot a block without an id');\n }\n\n const publicState = classifyNodeState({ block, runtime, now, pendingInvocationCount });\n const dueAt = getDueAt(block);\n const assigneeDid = getAssigneeDid(block);\n\n const snapshot: FlowAgentNodeSnapshot = {\n nodeId,\n blockType: getBlockType(block),\n runtime,\n publicState,\n pendingInvocationCount,\n };\n\n const actionType = getBlockActionType(block);\n if (actionType) snapshot.actionType = actionType;\n\n const title = getBlockTitle(block);\n if (title) snapshot.title = title;\n\n if (publicState === 'Blocked') {\n snapshot.blockerCause = classifyBlockerCause(block, runtime) || 'unknown';\n }\n\n if (assigneeDid) snapshot.assigneeDid = assigneeDid;\n if (dueAt != null) snapshot.dueAt = dueAt;\n\n return snapshot;\n}\n","import type { Doc } from 'yjs';\nimport type {\n FlowAgentActor,\n FlowAgentCommand,\n FlowAgentCommandResult,\n FlowAgentContext,\n FlowAgentExecutor,\n FlowAgentNodeSnapshot,\n FlowAgentTickResult,\n} from '../../types/flowAgent';\nimport type { StoredDelegation } from '../../types/ucan';\nimport type { UcanDelegationStore } from '../ucanDelegationStore';\nimport { readPendingInvocations } from '../flowEngine/triggers';\nimport { createAgentCommand, validateAgentCommand } from './commands';\nimport { acquireFlowAgentLease, releaseFlowAgentLease, validateFlowAgentLease } from './lease';\nimport { evaluateFlowAgentPolicy } from './policy';\nimport { appendAgentLedgerEvent, getFlowAgentMaps, queueAgentCommand, readQueuedAgentCommands, updateAgentCommand } from './store';\nimport { getAssigneeDid, getBlockActionType, getBlockId, getBlockProps, parseJsonProp } from './utils';\nimport { snapshotNode } from './state';\n\nexport interface FlowAgentOrchestratorOptions {\n delegationStore?: UcanDelegationStore;\n delegations?: StoredDelegation[];\n candidateActors?: FlowAgentActor[];\n executor?: FlowAgentExecutor;\n leaseTtlMs?: number;\n archiveWhenDone?: boolean;\n}\n\ninterface InputsValidation {\n valid: boolean;\n reason?: string;\n}\n\nfunction getBlocks(context: FlowAgentContext): unknown[] {\n return context.blocks || context.editor?.document || [];\n}\n\nfunction getRuntime(yDoc: Doc, nodeId: string): Record<string, any> {\n const runtime = yDoc.getMap<Record<string, any>>('runtime');\n const value = runtime.get(nodeId);\n return value && typeof value === 'object' ? value : {};\n}\n\nfunction validateInputs(block: unknown): InputsValidation {\n const props = getBlockProps(block);\n const inputs = parseJsonProp<Record<string, unknown>>(props.inputs, {});\n const requiredInputs = parseJsonProp<string[]>(props.requiredInputs, []);\n const missing = requiredInputs.filter((key) => inputs[key] == null || inputs[key] === '');\n if (missing.length > 0) {\n return { valid: false, reason: `Missing required inputs: ${missing.join(', ')}` };\n }\n return { valid: true };\n}\n\nfunction chooseActor(block: unknown, options: FlowAgentOrchestratorOptions): FlowAgentActor | undefined {\n const props = getBlockProps(block);\n const actionType = getBlockActionType(block);\n const requiredSkill = typeof props.requiredSkill === 'string' ? props.requiredSkill : actionType;\n if (!options.candidateActors || options.candidateActors.length === 0) return undefined;\n if (!requiredSkill) return options.candidateActors[0];\n return options.candidateActors.find((actor) => actor.skills?.includes(requiredSkill)) || options.candidateActors[0];\n}\n\nfunction canQueueCommand(type: FlowAgentCommand['type'], nodeId: string, context: FlowAgentContext, options: FlowAgentOrchestratorOptions): boolean {\n return evaluateFlowAgentPolicy({\n actorDid: context.actor.did,\n commandType: type,\n flowUri: context.flowUri,\n nodeId,\n delegationStore: options.delegationStore,\n delegations: options.delegations,\n now: context.now?.() || Date.now(),\n }).allowed;\n}\n\nfunction queueIfAuthorized(\n context: FlowAgentContext,\n options: FlowAgentOrchestratorOptions,\n type: FlowAgentCommand['type'],\n nodeId: string,\n reason: string,\n payload: Record<string, unknown>\n): FlowAgentCommand | null {\n const now = context.now?.() || Date.now();\n const policy = evaluateFlowAgentPolicy({\n actorDid: context.actor.did,\n commandType: type,\n flowUri: context.flowUri,\n nodeId,\n delegationStore: options.delegationStore,\n delegations: options.delegations,\n now,\n });\n\n appendAgentLedgerEvent(context.yDoc, {\n type: 'agent.decision',\n flowId: context.flowId,\n nodeId,\n actorDid: context.actor.did,\n timestamp: now,\n details: {\n commandType: type,\n allowed: policy.allowed,\n reason: policy.reason,\n capability: policy.capability,\n },\n });\n\n if (!policy.allowed) return null;\n\n const command = createAgentCommand({\n type,\n flowId: context.flowId,\n flowUri: context.flowUri,\n nodeId,\n actor: context.actor,\n reason,\n payload,\n now,\n });\n const validation = validateAgentCommand(command);\n if (!validation.valid) {\n appendAgentLedgerEvent(context.yDoc, {\n type: 'agent.validation',\n flowId: context.flowId,\n nodeId,\n commandId: command.id,\n actorDid: context.actor.did,\n timestamp: now,\n details: { valid: false, error: validation.error },\n });\n return null;\n }\n return queueAgentCommand(context.yDoc, command).created ? command : null;\n}\n\nfunction planForSnapshot(context: FlowAgentContext, options: FlowAgentOrchestratorOptions, block: unknown, snapshot: FlowAgentNodeSnapshot): FlowAgentCommand[] {\n const queued: FlowAgentCommand[] = [];\n const actionType = getBlockActionType(block);\n\n if (snapshot.publicState === 'Done') {\n const runtime = snapshot.runtime as Record<string, any>;\n if (actionType === 'qi/claim.submit' && runtime.output?.claimId && !runtime.output?.udid) {\n const command = queueIfAuthorized(context, options, 'watch_udid', snapshot.nodeId, 'Claim submitted but UDID is not yet observed', {\n claimId: runtime.output.claimId,\n timeoutMs: 86_400_000,\n });\n if (command) queued.push(command);\n }\n return queued;\n }\n\n if (snapshot.publicState === 'Overdue') {\n const command = queueIfAuthorized(context, options, 'notify_actor', snapshot.nodeId, 'Action node is overdue', {\n assigneeDid: snapshot.assigneeDid,\n dueAt: snapshot.dueAt,\n severity: 'overdue',\n });\n if (command) queued.push(command);\n return queued;\n }\n\n if (snapshot.publicState === 'Blocked') {\n const command = queueIfAuthorized(context, options, 'diagnose_blocker', snapshot.nodeId, 'Action node is blocked and requires diagnosis', {\n cause: snapshot.blockerCause || 'unknown',\n error: snapshot.runtime.error,\n });\n if (command) queued.push(command);\n return queued;\n }\n\n const assigneeDid = getAssigneeDid(block);\n if (!assigneeDid) {\n const actor = chooseActor(block, options);\n const command = queueIfAuthorized(context, options, 'assign_actor', snapshot.nodeId, 'Action node has no assigned actor', {\n targetActorDid: actor?.did,\n targetMatrixUserId: actor?.matrixUserId,\n requiredActionType: actionType,\n });\n if (command) queued.push(command);\n return queued;\n }\n\n const inputValidation = validateInputs(block);\n if (!inputValidation.valid) {\n const command = queueIfAuthorized(context, options, 'diagnose_blocker', snapshot.nodeId, inputValidation.reason || 'Action node inputs are not ready', {\n cause: 'missing_input',\n });\n if (command) queued.push(command);\n return queued;\n }\n\n if (actionType === 'qi/claim.submit') {\n const command = queueIfAuthorized(context, options, 'submit_claim', snapshot.nodeId, 'Claim action is pending and agent is authorized to submit', {\n actionType,\n });\n if (command) queued.push(command);\n return queued;\n }\n\n if (actionType && canQueueCommand('execute_action', snapshot.nodeId, context, options)) {\n const command = queueIfAuthorized(context, options, 'execute_action', snapshot.nodeId, 'Action node is pending and executable', {\n actionType,\n });\n if (command) queued.push(command);\n return queued;\n }\n\n const notifyCommand = queueIfAuthorized(context, options, 'notify_actor', snapshot.nodeId, 'Action node is pending but the Flow Agent cannot execute it', {\n assigneeDid,\n requiredActionType: actionType,\n severity: 'attention',\n });\n if (notifyCommand) queued.push(notifyCommand);\n return queued;\n}\n\nexport function planRalphLoopCommands(\n context: FlowAgentContext,\n options: FlowAgentOrchestratorOptions = {}\n): { snapshots: FlowAgentNodeSnapshot[]; queuedCommands: FlowAgentCommand[]; flowDone: boolean } {\n const now = context.now?.() || Date.now();\n const blocks = getBlocks(context);\n const snapshots: FlowAgentNodeSnapshot[] = [];\n const queuedCommands: FlowAgentCommand[] = [];\n\n for (const block of blocks) {\n const nodeId = getBlockId(block);\n if (!nodeId) continue;\n const pendingInvocationCount = readPendingInvocations(context.yDoc, nodeId).length;\n const snapshot = snapshotNode(block, getRuntime(context.yDoc, nodeId), now, pendingInvocationCount);\n snapshots.push(snapshot);\n queuedCommands.push(...planForSnapshot(context, options, block, snapshot));\n }\n\n const flowDone = snapshots.length > 0 && snapshots.every((snapshot) => snapshot.publicState === 'Done');\n if (flowDone && options.archiveWhenDone !== false) {\n const archiveCommand = queueIfAuthorized(context, options, 'archive_flow', context.flowId, 'All Ralph loop action nodes are done', {\n restartIfRepeats: true,\n });\n if (archiveCommand) queuedCommands.push(archiveCommand);\n }\n\n return { snapshots, queuedCommands, flowDone };\n}\n\nasync function callExecutor(command: FlowAgentCommand, context: FlowAgentContext, executor: FlowAgentExecutor): Promise<FlowAgentCommandResult> {\n switch (command.type) {\n case 'execute_action':\n return executor.executeAction ? executor.executeAction(command, context) : { commandId: command.id, success: false, error: 'No executeAction handler configured' };\n case 'assign_actor':\n return executor.assignActor ? executor.assignActor(command, context) : { commandId: command.id, success: false, error: 'No assignActor handler configured' };\n case 'notify_actor':\n return executor.notifyActor ? executor.notifyActor(command, context) : { commandId: command.id, success: false, error: 'No notifyActor handler configured' };\n case 'validate_external_state':\n return executor.validateExternalState\n ? executor.validateExternalState(command, context)\n : { commandId: command.id, success: false, error: 'No validateExternalState handler configured' };\n case 'submit_claim':\n return executor.submitClaim ? executor.submitClaim(command, context) : { commandId: command.id, success: false, error: 'No submitClaim handler configured' };\n case 'watch_udid':\n return executor.watchUdid ? executor.watchUdid(command, context) : { commandId: command.id, success: false, error: 'No watchUdid handler configured' };\n case 'archive_flow':\n return executor.archiveFlow ? executor.archiveFlow(command, context) : { commandId: command.id, success: false, error: 'No archiveFlow handler configured' };\n case 'propose_config_change':\n return executor.proposeConfigChange\n ? executor.proposeConfigChange(command, context)\n : { commandId: command.id, success: false, error: 'No proposeConfigChange handler configured' };\n case 'diagnose_blocker':\n return executor.diagnoseBlocker ? executor.diagnoseBlocker(command, context) : { commandId: command.id, success: false, error: 'No diagnoseBlocker handler configured' };\n }\n}\n\nexport async function executeQueuedAgentCommands(context: FlowAgentContext, options: FlowAgentOrchestratorOptions = {}): Promise<FlowAgentCommandResult[]> {\n const executor = options.executor;\n if (!executor) return [];\n\n const now = context.now?.() || Date.now();\n const { leases } = getFlowAgentMaps(context.yDoc);\n const results: FlowAgentCommandResult[] = [];\n\n for (const command of readQueuedAgentCommands(context.yDoc)) {\n const validation = validateAgentCommand(command);\n if (!validation.valid) {\n updateAgentCommand(context.yDoc, command.id, { status: 'failed', error: validation.error, updatedAt: now });\n results.push({ commandId: command.id, success: false, error: validation.error });\n continue;\n }\n\n const policy = evaluateFlowAgentPolicy({\n actorDid: context.actor.did,\n commandType: command.type,\n flowUri: context.flowUri,\n nodeId: command.nodeId,\n delegationStore: options.delegationStore,\n delegations: options.delegations,\n now,\n });\n\n if (!policy.allowed) {\n updateAgentCommand(context.yDoc, command.id, { status: 'skipped', error: policy.reason, updatedAt: now });\n results.push({ commandId: command.id, success: false, error: policy.reason });\n continue;\n }\n\n const lease = acquireFlowAgentLease({\n leases,\n commandId: command.id,\n nodeId: command.nodeId,\n actorDid: context.actor.did,\n now,\n ttlMs: options.leaseTtlMs,\n });\n\n if (!lease) {\n continue;\n }\n\n updateAgentCommand(context.yDoc, command.id, { status: 'running', lease, updatedAt: now });\n\n try {\n const result = await callExecutor({ ...command, lease, status: 'running' }, context, executor);\n if (!validateFlowAgentLease(leases, lease, context.now?.() || Date.now())) {\n const leaseError = 'Lease expired or was superseded before command commit';\n updateAgentCommand(context.yDoc, command.id, { status: 'failed', error: leaseError, updatedAt: context.now?.() || Date.now() });\n results.push({ commandId: command.id, success: false, error: leaseError });\n continue;\n }\n\n updateAgentCommand(context.yDoc, command.id, {\n status: result.success ? 'confirmed' : 'failed',\n error: result.error,\n updatedAt: context.now?.() || Date.now(),\n });\n\n appendAgentLedgerEvent(context.yDoc, {\n type: result.success ? 'agent.validation' : 'agent.escalation',\n flowId: context.flowId,\n nodeId: command.nodeId,\n commandId: command.id,\n actorDid: context.actor.did,\n timestamp: context.now?.() || Date.now(),\n details: {\n success: result.success,\n confirmed: result.confirmed,\n output: result.output,\n error: result.error,\n },\n });\n\n results.push(result);\n } finally {\n releaseFlowAgentLease(leases, lease);\n }\n }\n\n return results;\n}\n\nexport async function tickFlowAgent(context: FlowAgentContext, options: FlowAgentOrchestratorOptions = {}): Promise<FlowAgentTickResult> {\n const plan = planRalphLoopCommands(context, options);\n const executedCommands = await executeQueuedAgentCommands(context, options);\n return {\n flowDone: plan.flowDone,\n snapshots: plan.snapshots,\n queuedCommands: plan.queuedCommands,\n executedCommands,\n };\n}\n","import type { FlowAgentContext, FlowAgentTickResult } from '../../types/flowAgent';\nimport type { FlowAgentOrchestratorOptions } from './orchestrator';\nimport { tickFlowAgent } from './orchestrator';\n\nexport interface FlowAgentServiceOptions extends FlowAgentOrchestratorOptions {\n intervalMs?: number;\n onTick?: (result: FlowAgentTickResult) => void | Promise<void>;\n onError?: (error: unknown) => void;\n}\n\n/**\n * Headless-service adapter boundary.\n *\n * Host applications own Matrix login, room joins, and Y.Doc sync. Once they\n * have a live Y.Doc/editor snapshot, this service provides the deterministic\n * Ralph-loop tick and command execution cycle.\n */\nexport class FlowAgentService {\n private timer: ReturnType<typeof setInterval> | null = null;\n private running = false;\n\n constructor(\n private readonly context: FlowAgentContext,\n private readonly options: FlowAgentServiceOptions = {}\n ) {}\n\n async tick(): Promise<FlowAgentTickResult> {\n if (this.running) {\n return {\n flowDone: false,\n snapshots: [],\n queuedCommands: [],\n executedCommands: [],\n };\n }\n\n this.running = true;\n try {\n const result = await tickFlowAgent(this.context, this.options);\n await this.options.onTick?.(result);\n return result;\n } catch (error) {\n this.options.onError?.(error);\n throw error;\n } finally {\n this.running = false;\n }\n }\n\n start(): void {\n if (this.timer) return;\n const intervalMs = this.options.intervalMs || 30_000;\n this.timer = setInterval(() => {\n this.tick().catch((error) => {\n this.options.onError?.(error);\n });\n }, intervalMs);\n }\n\n stop(): void {\n if (!this.timer) return;\n clearInterval(this.timer);\n this.timer = null;\n }\n}\n"],"mappings":";;;;;;AA0CO,SAAS,mBACd,IACA,eACA,gBACyB;AACzB,SAAO,aAAa,IAAI,eAAe,cAAc;AACvD;AAEA,SAAS,aAAa,OAAgB,eAAwE,gBAAoD;AAChK,MAAI,aAAa,KAAK,GAAG;AACvB,WAAO,WAAW,MAAM,MAAM,eAAe,cAAc;AAAA,EAC7D;AAEA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,MAAM,IAAI,CAAC,SAAS,aAAa,MAAM,eAAe,cAAc,CAAC;AAAA,EAC9E;AAEA,MAAI,OAAO,UAAU,YAAY,UAAU,MAAM;AAC/C,UAAM,SAAkC,CAAC;AACzC,eAAW,CAAC,KAAK,GAAG,KAAK,OAAO,QAAQ,KAAK,GAAG;AAC9C,aAAO,GAAG,IAAI,aAAa,KAAK,eAAe,cAAc;AAAA,IAC/D;AACA,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAYA,SAAS,WAAW,KAAa,eAAwE,gBAAoD;AAE3J,MAAI,IAAI,WAAW,kBAAkB,GAAG;AACtC,QAAI,CAAC,gBAAgB;AACnB,YAAM,IAAI,MAAM,gBAAgB,GAAG,yHAAyH;AAAA,IAC9J;AACA,UAAMA,aAAY,IAAI,MAAM,mBAAmB,MAAM;AACrD,WAAO,eAAe,eAAe,SAASA,UAAS;AAAA,EACzD;AAGA,MAAI,kBAAkB,OAAO,UAAU,eAAe,KAAK,eAAe,cAAc,GAAG,GAAG;AAC5F,WAAO,eAAe,aAAa,GAAG;AAAA,EACxC;AAGA,QAAM,cAAc,IAAI,QAAQ,UAAU;AAC1C,MAAI,gBAAgB,IAAI;AACtB,UAAM,IAAI,MAAM,8BAA8B,GAAG,8EAA8E;AAAA,EACjI;AAEA,QAAM,SAAS,IAAI,MA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AFiB;AACA;AALnB,SAAQ,QAA+C;AACvD,SAAQ,UAAU;AAAA,EAKf;AAAA,EAEH,MAAM,OAAqC;AACzC,QAAI,KAAK,SAAS;AAChB,aAAO;AAAA,QACL,UAAU;AAAA,QACV,WAAW,CAAC;AAAA,QACZ,gBAAgB,CAAC;AAAA,QACjB,kBAAkB,CAAC;AAAA,MACrB;AAAA,IACF;AAEA,SAAK,UAAU;AACf,QAAI;AACF,YAAM,SAAS,MAAM,cAAc,KAAK,SAAS,KAAK,OAAO;AAC7D,YAAM,KAAK,QAAQ,SAAS,MAAM;AAClC,aAAO;AAAA,IACT,SAAS,OAAO;AACd,WAAK,QAAQ,UAAU,KAAK;AAC5B,YAAM;AAAA,IACR,UAAE;AACA,WAAK,UAAU;AAAA,IACjB;AAAA,EACF;AAAA,EAEA,QAAc;AACZ,QAAI,KAAK,MAAO;AAChB,UAAM,aAAa,KAAK,QAAQ,cAAc;AAC9C,SAAK,QAAQ,YAAY,MAAM;AAC7B,WAAK,KAAK,EAAE,MAAM,CAAC,UAAU;AAC3B,aAAK,QAAQ,UAAU,KAAK;AAAA,MAC9B,CAAC;AAAA,IACH,GAAG,UAAU;AAAA,EACf;AAAA,EAEA,OAAa;AACX,QAAI,CAAC,KAAK,MAAO;AACjB,kBAAc,KAAK,KAAK;AACxB,SAAK,QAAQ;AAAA,EACf;AACF;","names":["fieldPath"]}
@@ -5831,11 +5831,15 @@ function clearRuntimeForTemplateClone(yDoc) {
5831
5831
  const runtime = yDoc.getMap("runtime");
5832
5832
  const invocations = yDoc.getMap("invocations");
5833
5833
  const pendingInvocations = yDoc.getMap("pendingInvocations");
5834
+ const agentOutbox = yDoc.getMap("agentOutbox");
5835
+ const agentLeases = yDoc.getMap("agentLeases");
5834
5836
  const auditTrail = yDoc.getMap("auditTrail");
5835
5837
  yDoc.transact(() => {
5836
5838
  runtime.forEach((_, key) => runtime.delete(key));
5837
5839
  invocations.forEach((_, key) => invocations.delete(key));
5838
5840
  pendingInvocations.forEach((_, key) => pendingInvocations.delete(key));
5841
+ agentOutbox.forEach((_, key) => agentOutbox.delete(key));
5842
+ agentLeases.forEach((_, key) => agentLeases.delete(key));
5839
5843
  auditTrail.forEach((_, key) => auditTrail.delete(key));
5840
5844
  });
5841
5845
  }
@@ -7642,4 +7646,4 @@ export {
7642
7646
  readFlow,
7643
7647
  setupFlowFromBaseUcan
7644
7648
  };
7645
- //# sourceMappingURL=chunk-DQCYLHDD.mjs.map
7649
+ //# sourceMappingURL=chunk-GCR6VY7O.mjs.map