@dxos/compute 0.16.0 → 0.17.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.
- package/dist/lib/AiMetering.mjs +1 -0
- package/dist/lib/Hook.mjs +1 -0
- package/dist/lib/Operation.mjs +3 -3
- package/dist/lib/Process.mjs +2 -2
- package/dist/lib/Trace.mjs +1 -1
- package/dist/lib/chunk-AgentIdentity.mjs +1 -1
- package/dist/lib/chunk-AgentService.mjs.map +1 -1
- package/dist/lib/chunk-AiMetering.mjs +77 -0
- package/dist/lib/chunk-AiMetering.mjs.map +1 -0
- package/dist/lib/chunk-Cancellation.mjs +1 -1
- package/dist/lib/chunk-Hook.mjs +78 -0
- package/dist/lib/chunk-Hook.mjs.map +1 -0
- package/dist/lib/chunk-Instructions.mjs +1 -1
- package/dist/lib/chunk-Operation.mjs +169 -5
- package/dist/lib/chunk-Operation.mjs.map +1 -1
- package/dist/lib/chunk-OperationHandlerSet.mjs +1 -1
- package/dist/lib/chunk-OperationRegistry.mjs +1 -1
- package/dist/lib/chunk-OperationRegistry.mjs.map +1 -1
- package/dist/lib/chunk-Process.mjs +18 -10
- package/dist/lib/chunk-Process.mjs.map +1 -1
- package/dist/lib/chunk-Project.mjs +52 -24
- package/dist/lib/chunk-Project.mjs.map +1 -1
- package/dist/lib/chunk-Reducer.mjs +827 -0
- package/dist/lib/chunk-Reducer.mjs.map +1 -0
- package/dist/lib/chunk-Routine.mjs +1 -1
- package/dist/lib/chunk-Runnable.mjs +1 -1
- package/dist/lib/chunk-ServiceResolver.mjs +1 -1
- package/dist/lib/chunk-Skill.mjs +10 -47
- package/dist/lib/chunk-Skill.mjs.map +1 -1
- package/dist/lib/chunk-Spec.mjs +49 -0
- package/dist/lib/chunk-Spec.mjs.map +1 -0
- package/dist/lib/chunk-SpecReview.mjs +98 -0
- package/dist/lib/chunk-SpecReview.mjs.map +1 -0
- package/dist/lib/chunk-SqlService.mjs.map +1 -1
- package/dist/lib/chunk-StorageService.mjs +1 -1
- package/dist/lib/chunk-Template.mjs +2 -2
- package/dist/lib/chunk-Trace.mjs +97 -13
- package/dist/lib/chunk-Trace.mjs.map +1 -1
- package/dist/lib/chunk-Trajectory.mjs +326 -0
- package/dist/lib/chunk-Trajectory.mjs.map +1 -0
- package/dist/lib/chunk-Transcript.mjs +84 -0
- package/dist/lib/chunk-Transcript.mjs.map +1 -0
- package/dist/lib/chunk-definitions.mjs +1 -1
- package/dist/lib/errors.mjs +3 -1
- package/dist/lib/errors.mjs.map +1 -1
- package/dist/lib/index.mjs +14 -8
- package/dist/lib/testing.mjs +2 -2
- package/dist/lib/trajectory/Reducer.mjs +1 -0
- package/dist/lib/trajectory/Trajectory.mjs +1 -0
- package/dist/lib/trajectory/Transcript.mjs +1 -0
- package/dist/lib/types/Project.mjs +1 -1
- package/dist/lib/types/Skill.mjs +1 -1
- package/dist/lib/types/Spec.mjs +1 -0
- package/dist/lib/types/SpecReview.mjs +1 -0
- package/dist/types/src/AgentService.d.ts +9 -0
- package/dist/types/src/AgentService.d.ts.map +1 -1
- package/dist/types/src/AiMetering.d.ts +23 -0
- package/dist/types/src/AiMetering.d.ts.map +1 -0
- package/dist/types/src/AiMetering.test.d.ts +2 -0
- package/dist/types/src/AiMetering.test.d.ts.map +1 -0
- package/dist/types/src/Hook.d.ts +84 -0
- package/dist/types/src/Hook.d.ts.map +1 -0
- package/dist/types/src/Hook.test.d.ts +2 -0
- package/dist/types/src/Hook.test.d.ts.map +1 -0
- package/dist/types/src/Operation.d.ts +276 -2
- package/dist/types/src/Operation.d.ts.map +1 -1
- package/dist/types/src/Process.d.ts +26 -4
- package/dist/types/src/Process.d.ts.map +1 -1
- package/dist/types/src/Script.test.d.ts +2 -0
- package/dist/types/src/Script.test.d.ts.map +1 -0
- package/dist/types/src/Trace.d.ts +103 -1
- package/dist/types/src/Trace.d.ts.map +1 -1
- package/dist/types/src/errors.d.ts +30 -0
- package/dist/types/src/errors.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +3 -1
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/trajectory/Reducer.d.ts +191 -0
- package/dist/types/src/trajectory/Reducer.d.ts.map +1 -0
- package/dist/types/src/trajectory/Reducer.test.d.ts +2 -0
- package/dist/types/src/trajectory/Reducer.test.d.ts.map +1 -0
- package/dist/types/src/trajectory/Trajectory.d.ts +3211 -0
- package/dist/types/src/trajectory/Trajectory.d.ts.map +1 -0
- package/dist/types/src/trajectory/Trajectory.test.d.ts +2 -0
- package/dist/types/src/trajectory/Trajectory.test.d.ts.map +1 -0
- package/dist/types/src/trajectory/Transcript.d.ts +40 -0
- package/dist/types/src/trajectory/Transcript.d.ts.map +1 -0
- package/dist/types/src/trajectory/index.d.ts +4 -0
- package/dist/types/src/trajectory/index.d.ts.map +1 -0
- package/dist/types/src/trajectory/light-threads.test.d.ts +2 -0
- package/dist/types/src/trajectory/light-threads.test.d.ts.map +1 -0
- package/dist/types/src/trajectory/samples.test.d.ts +2 -0
- package/dist/types/src/trajectory/samples.test.d.ts.map +1 -0
- package/dist/types/src/types/Project.d.ts +11 -12
- package/dist/types/src/types/Project.d.ts.map +1 -1
- package/dist/types/src/types/Skill.d.ts +6 -51
- package/dist/types/src/types/Skill.d.ts.map +1 -1
- package/dist/types/src/types/Spec.d.ts +26 -0
- package/dist/types/src/types/Spec.d.ts.map +1 -0
- package/dist/types/src/types/SpecReview.d.ts +76 -0
- package/dist/types/src/types/SpecReview.d.ts.map +1 -0
- package/dist/types/src/types/index.d.ts +2 -0
- package/dist/types/src/types/index.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +59 -26
- package/src/AgentService.ts +9 -0
- package/src/AiMetering.test.ts +89 -0
- package/src/AiMetering.ts +93 -0
- package/src/Hook.test.ts +75 -0
- package/src/Hook.ts +154 -0
- package/src/Operation.test.ts +23 -0
- package/src/Operation.ts +334 -0
- package/src/Process.ts +33 -6
- package/src/Script.test.ts +74 -0
- package/src/Trace.ts +97 -4
- package/src/errors.ts +3 -0
- package/src/index.ts +3 -1
- package/src/trajectory/Reducer.test.ts +575 -0
- package/src/trajectory/Reducer.ts +1026 -0
- package/src/trajectory/Trajectory.test.ts +114 -0
- package/src/trajectory/Trajectory.ts +440 -0
- package/src/trajectory/Transcript.ts +113 -0
- package/src/trajectory/index.ts +7 -0
- package/src/trajectory/light-threads.test.ts +310 -0
- package/src/trajectory/samples.test.ts +285 -0
- package/src/types/Project.test.ts +2 -1
- package/src/types/Project.ts +43 -27
- package/src/types/Skill.ts +6 -61
- package/src/types/Spec.ts +68 -0
- package/src/types/SpecReview.ts +98 -0
- package/src/types/index.ts +2 -0
- package/dist/lib/McpServer.mjs +0 -1
- package/dist/lib/chunk-McpServer.mjs +0 -124
- package/dist/lib/chunk-McpServer.mjs.map +0 -1
- package/dist/types/src/McpServer.d.ts +0 -113
- package/dist/types/src/McpServer.d.ts.map +0 -1
- package/src/McpServer.ts +0 -142
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chunk-Trace.mjs","names":["Trigger.Trigger"],"sources":["../../src/Trace.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Schema from 'effect/Schema';\n\nimport { Annotation, DXN, Obj, Ref, Type } from '@dxos/echo';\nimport { EID } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { Actor, ContentBlock, Task } from '@dxos/types';\n\nimport * as Trigger from './types/Trigger.ts';\n\n/**\n * Writes ephemeral or persistent events to the trace.\n * Exposed to processes and operations to record events to the trace.\n */\nexport interface Writer {\n write<T>(eventType: EventType<T>, payload: NoInfer<T>): void;\n}\n\n/**\n * Service that writes events to the trace.\n * Exposed to processes and operations to record events to the trace.\n */\nexport class TraceService extends Context.Service<TraceService, Writer>()('@dxos/functions/TraceService') {}\n\n/**\n * Writes an event to the trace.\n */\nexport function write<T>(eventType: EventType<T>, payload: NoInfer<T>): Effect.Effect<void, never, TraceService> {\n return Effect.gen(function* () {\n log('trace write', { key: eventType.key, isEphemeral: eventType.isEphemeral });\n const writer = yield* TraceService;\n writer.write(eventType, payload);\n });\n}\n\n/**\n * Defines an event type for the trace.\n */\nexport interface EventType<T> {\n readonly key: string;\n readonly schema: Schema.Codec<T, any>;\n readonly isEphemeral: boolean;\n}\n\nexport const EventType = <T>(\n key: string,\n opts: { schema: Schema.Codec<T, any>; isEphemeral: boolean },\n): EventType<T> => {\n return {\n key,\n schema: opts.schema,\n isEphemeral: opts.isEphemeral,\n };\n};\n\n/**\n * Extracts the payload type from an event type.\n */\nexport type PayloadType<E extends EventType<unknown>> = E extends EventType<infer T> ? T : never;\n\nexport const Event = Schema.Struct({\n timestamp: Schema.Number,\n type: Schema.String,\n data: Schema.Unknown, // Type-specific payload;\n});\nexport type Event = Schema.Schema.Type<typeof Event>;\n\n/**\n * Checks if an event is of a given type.\n */\nexport const isOfType = <T, E extends Event>(eventType: EventType<T>, event: E): event is E & { data: T } => {\n return event.type === eventType.key;\n};\n\n/**\n * Extensible name informing which runtime executed the code that produced the event.\n */\nexport const RuntimeName = Schema.String.pipe(Schema.brand('@dxos/compute/Trace/RuntimeName'));\nexport type RuntimeName = Schema.Schema.Type<typeof RuntimeName>;\n\n/**\n * Common runtime names.\n */\nexport const CommonRuntimeName = {\n /**\n * Web app / CLI / Desktop app / Mobile app.\n */\n local: RuntimeName.make('local'),\n edgeIntrinsic: RuntimeName.make('edge-intrinsic'),\n edgeWorkerLoader: RuntimeName.make('edge-worker-loader'),\n edgeWorkerForPlatforms: RuntimeName.make('edge-worker-for-platforms'),\n};\n\n/**\n * Metadata on the context of a trace message.\n */\n// TODO(dmaretskyi): Expand on this: conversation id, tool call id, etc.\nexport const Meta = Schema.Struct({\n pid: Schema.optional(Schema.String), // NOTE: Not Process.ID to avoid circular dependency.\n parentPid: Schema.optional(Schema.String),\n processName: Schema.optional(Schema.String),\n\n /**\n * Space the message was produced in.\n * Stored as a string to avoid circular dependency on `@dxos/keys`.\n */\n space: Schema.optional(Schema.String),\n\n /**\n * Ref to the conversation feed object if present.\n */\n conversation: Ref.Ref(Obj.Unknown).pipe(Schema.optional),\n\n /**\n * Ref to the trigger object if invocation resulted from a trigger.\n */\n trigger: Ref.Ref(Trigger.Trigger).pipe(Schema.optional),\n\n /**\n * ID of the tool call that created the current process.\n */\n toolCallId: Schema.optional(Schema.String),\n\n /**\n * Extensible name informing which runtime executed the code that produced the event.\n */\n runtimeName: Schema.optional(RuntimeName),\n});\nexport type Meta = Schema.Schema.Type<typeof Meta>;\n\n/**\n * Checks if a runtime is an edge runtime.\n */\nexport const isEdgeRuntime = (name: RuntimeName): boolean =>\n name === CommonRuntimeName.edgeIntrinsic ||\n name === CommonRuntimeName.edgeWorkerLoader ||\n name === CommonRuntimeName.edgeWorkerForPlatforms;\n\n/**\n * Envelope for a set of events.\n */\nexport const MessageData = Schema.Struct({\n meta: Meta,\n isEphemeral: Schema.Boolean,\n events: Schema.Array(Event),\n});\nexport type MessageData = Schema.Schema.Type<typeof MessageData>;\n\nexport class Message extends Type.makeObject<Message>(DXN.make('org.dxos.type.traceMessage', '0.1.0'))(\n MessageData.pipe(Annotation.IconAnnotation.set({ icon: 'ph--note--regular', hue: 'rose' })),\n) {}\n\n/**\n * Flattened representation of a signle event in a trace message.\n * Events are stored in batched messages for efficiency, but flat representation is more convenient for consumption.\n */\nexport interface FlatEvent extends Event {\n readonly meta: Meta;\n readonly isEphemeral: boolean;\n}\n\n/**\n * Flattens a trace message into a list of flat events.\n */\nexport const flatten = (message: Message): FlatEvent[] => {\n return message.events.map((event) => ({\n ...event,\n meta: message.meta,\n isEphemeral: message.isEphemeral,\n }));\n};\n\n//\n// Swarm broadcast (DX-1125).\n//\n// Ephemeral trace messages produced on a remote runtime are broadcast over the space swarm and\n// projected into the client's progress UI. The publisher tags each message with a flat key:value list\n// derived from its meta; subscribers register a coarse tag (OR match at the swarm) and re-apply the\n// exact filter (AND) client-side.\n//\n\n/**\n * `google.protobuf.Any` type URL for a trace message broadcast over the swarm.\n */\nexport const TRACE_MESSAGE_TYPE_URL = 'dxos.compute.TraceMessage';\n\n/**\n * Declarative, serializable filter over trace messages. All present fields are ANDed. `type` matches\n * against event types within the message; the rest match against {@link Meta} fields. Refs\n * (`conversation`, `trigger`) are matched by their DXN string.\n */\nexport interface Filter {\n readonly type?: string;\n readonly pid?: string;\n readonly parentPid?: string;\n readonly conversation?: string;\n readonly trigger?: string;\n readonly space?: string;\n readonly runtimeName?: string;\n readonly toolCallId?: string;\n}\n\n/**\n * Derive the flat broadcast tag list for a message (DX-1125). The publisher emits all applicable tags;\n * subscribers match a subset (logical OR).\n */\nexport const messageToTags = (message: Pick<MessageData, 'meta' | 'events'>): string[] => {\n const { meta } = message;\n const tags: string[] = [];\n for (const event of message.events) {\n tags.push(`type:${event.type}`);\n }\n if (meta.pid) {\n tags.push(`pid:${meta.pid}`);\n }\n if (meta.parentPid) {\n tags.push(`parentPid:${meta.parentPid}`);\n }\n if (meta.conversation) {\n tags.push(`conversation:${meta.conversation.uri.toString()}`);\n }\n if (meta.trigger) {\n tags.push(`trigger:${meta.trigger.uri.toString()}`);\n }\n if (meta.space) {\n tags.push(`space:${meta.space}`);\n }\n if (meta.runtimeName) {\n tags.push(`runtime:${meta.runtimeName}`);\n }\n if (meta.toolCallId) {\n tags.push(`toolCall:${meta.toolCallId}`);\n }\n return tags;\n};\n\n/**\n * Pick the coarse subscription tag for a filter (DX-1125). The swarm cuts traffic to a superset of the\n * filter using its most selective present dimension; the client re-applies the exact filter.\n */\nexport const subscriptionTagForFilter = (filter: Filter): string | undefined => {\n if (filter.conversation !== undefined) {\n return `conversation:${filter.conversation}`;\n }\n if (filter.trigger !== undefined) {\n return `trigger:${filter.trigger}`;\n }\n if (filter.parentPid !== undefined) {\n return `parentPid:${filter.parentPid}`;\n }\n if (filter.pid !== undefined) {\n return `pid:${filter.pid}`;\n }\n if (filter.space !== undefined) {\n return `space:${filter.space}`;\n }\n if (filter.type !== undefined) {\n return `type:${filter.type}`;\n }\n return undefined;\n};\n\n/**\n * Exact (AND) filter match applied client-side after the coarse swarm subscription.\n */\nexport const matchesFilter = (message: Pick<MessageData, 'meta' | 'events'>, filter: Filter): boolean => {\n const { meta } = message;\n if (filter.type !== undefined && !message.events.some((event) => event.type === filter.type)) {\n return false;\n }\n if (filter.pid !== undefined && meta.pid !== filter.pid) {\n return false;\n }\n if (filter.parentPid !== undefined && meta.parentPid !== filter.parentPid) {\n return false;\n }\n if (filter.conversation !== undefined && meta.conversation?.uri.toString() !== filter.conversation) {\n return false;\n }\n if (filter.trigger !== undefined && meta.trigger?.uri.toString() !== filter.trigger) {\n return false;\n }\n if (filter.space !== undefined && meta.space !== filter.space) {\n return false;\n }\n if (filter.runtimeName !== undefined && meta.runtimeName !== filter.runtimeName) {\n return false;\n }\n if (filter.toolCallId !== undefined && meta.toolCallId !== filter.toolCallId) {\n return false;\n }\n return true;\n};\n\n/**\n * Wire-safe subset of {@link Meta} for broadcast. Ref fields (`conversation`, `trigger`) are not\n * carried in the payload — they are represented only as envelope tags — so the decoded message never\n * attempts ref resolution on the consumer.\n */\nconst encodeMetaForWire = (meta: Meta): Meta => ({\n pid: meta.pid,\n parentPid: meta.parentPid,\n processName: meta.processName,\n space: meta.space,\n toolCallId: meta.toolCallId,\n runtimeName: meta.runtimeName,\n});\n\n/**\n * Encode a trace message for the broadcast envelope's `google.protobuf.Any.value` (DX-1125).\n * The wire format is UTF-8 JSON of the message data (ref fields dropped — see {@link encodeMetaForWire}).\n */\nexport const encodeTraceMessage = (message: Pick<MessageData, 'meta' | 'isEphemeral' | 'events'>): Uint8Array =>\n new TextEncoder().encode(\n JSON.stringify({\n meta: encodeMetaForWire(message.meta),\n isEphemeral: message.isEphemeral,\n events: message.events,\n }),\n );\n\n/**\n * Decode a broadcast trace message back into a {@link Message} object (DX-1125). The wire payload\n * drops both ref meta fields (see {@link encodeMetaForWire}), so `tags` — the broadcast envelope's\n * tag list — is required to restore them: `trigger` addresses work for cancellation, and\n * `conversation` is what {@link matchesFilter} compares, so a subscription filtered by it matches\n * nothing without this. Restored refs are address-only (`.uri`); they are never resolved.\n */\nexport const decodeTraceMessage = (bytes: Uint8Array, tags?: readonly string[]): Message => {\n const parsed = JSON.parse(new TextDecoder().decode(bytes)) as Partial<MessageData>;\n const meta = parsed.meta ?? {};\n const conversation = meta.conversation ?? refFromTags<Obj.Unknown>(tags, 'conversation:');\n const trigger = meta.trigger ?? refFromTags<Trigger.Trigger>(tags, 'trigger:');\n return Obj.make(Message, {\n meta: {\n ...meta,\n ...(conversation ? { conversation } : {}),\n ...(trigger ? { trigger } : {}),\n },\n isEphemeral: parsed.isEphemeral ?? true,\n events: parsed.events ?? [],\n });\n};\n\n/** The ref carried on a broadcast envelope's `<prefix><uri>` tag, when present and parseable. */\nconst refFromTags = <T>(tags: readonly string[] | undefined, prefix: string): Ref.Ref<T> | undefined => {\n const uri = tags?.find((tag) => tag.startsWith(prefix))?.slice(prefix.length);\n const eid = uri !== undefined ? EID.tryParse(uri) : undefined;\n return eid !== undefined ? Ref.fromURI(eid) : undefined;\n};\n\n/**\n * Sink for complete trace messages.\n */\nexport interface Sink {\n write(message: Message): void;\n}\n\n/**\n * Sink for complete trace messages.\n * The Process Manager forwards trace messages to it.\n */\n// TODO(dmaretskyi): Consider moving sink to the Process Manager.\nexport class TraceSink extends Context.Service<TraceSink, Sink>()('@dxos/functions/TraceSink') {}\n\nexport const noopWriter: Writer = {\n write: () => {},\n};\n\nexport const writerLayerNoop: Layer.Layer<TraceService> = Layer.succeed(TraceService, noopWriter);\n\nexport const noopSink: Sink = {\n write: () => {},\n};\n\nexport const layerNoop: Layer.Layer<TraceSink> = Layer.succeed(TraceSink, noopSink);\n\nexport const layerConsole: Layer.Layer<TraceSink> = Layer.succeed(TraceSink, {\n write: (message) => {\n console.log(message);\n },\n});\n\n/**\n * Merge a set of sinks into a single sink.\n *\n * Each message is forwarded to every sink in order. Failures in one sink do not\n * prevent downstream sinks from receiving the message.\n */\nexport const mergeSinks = (sinks: readonly Sink[]): Sink => {\n if (sinks.length === 0) {\n return noopSink;\n }\n // Intentionally no singleton fast path: the guarded wrapper is the\n // contract of `mergeSinks`, so a throwing sink is always caught and\n // logged regardless of how many sinks were passed in.\n return {\n write: (message) => {\n for (const sink of sinks) {\n try {\n sink.write(message);\n } catch (err) {\n // Intentional: do not let one sink break the chain.\n // eslint-disable-next-line no-console\n console.error('[trace] sink.write threw', err);\n }\n }\n },\n };\n};\n\n/**\n * Builds a {@link TraceService} layer that wraps each `write` into a fresh {@link Message}\n * and forwards it to the provided {@link TraceSink}. Intended for tests and lightweight\n * fixtures.\n *\n * Options:\n * - `meta`: stamped on every emitted message (defaults to `{}`).\n * - `clock`: timestamp source (defaults to {@link Date.now}). Pass a monotonic counter\n * in tests to make event ordering deterministic when many writes happen in the same\n * millisecond.\n */\nexport const testTraceService = (\n opts: { meta?: Meta; clock?: () => number } = {},\n): Layer.Layer<TraceService, never, TraceSink> =>\n Layer.effect(\n TraceService,\n Effect.gen(function* () {\n const sink = yield* TraceSink;\n const clock = opts.clock ?? Date.now;\n return {\n write: (event, data) => {\n sink.write(\n Obj.make(Message, {\n meta: opts.meta ?? {},\n isEphemeral: event.isEphemeral,\n events: [{ type: event.key, timestamp: clock(), data }],\n }),\n );\n },\n };\n }),\n );\n\n//\n// Operation Trace Events\n//\n\n/**\n * Outcome of an operation invocation.\n */\nexport type OperationOutcome = 'success' | 'failure';\n\n/**\n * Operation invocation started.\n */\nexport const OperationStart = EventType('operation.start', {\n schema: Schema.Struct({\n /** Operation key. */\n key: Schema.String,\n /** Human-readable operation name. */\n name: Schema.optional(Schema.String),\n /** Phosphor icon identifier in `ph--<name>--<variant>` format. */\n icon: Schema.optional(Schema.String),\n }),\n isEphemeral: false,\n});\n\n/**\n * Operation invocation ended.\n */\nexport const OperationEnd = EventType('operation.end', {\n schema: Schema.Struct({\n /** Operation key. */\n key: Schema.String,\n /** Human-readable operation name. */\n name: Schema.optional(Schema.String),\n /** Phosphor icon identifier in `ph--<name>--<variant>` format. */\n icon: Schema.optional(Schema.String),\n /** Outcome of the operation. */\n outcome: Schema.Literals(['success', 'failure']),\n /** Error message if the operation failed. */\n error: Schema.optional(Schema.String),\n /**\n * Stable code (error name) of the failure, when the operation failed with a typed error.\n * Lets consumers match on the error kind (e.g. a run-again yield) without parsing the message.\n */\n errorCode: Schema.optional(Schema.String),\n }),\n isEphemeral: false,\n});\n\n/**\n * Operation input. Emitted as an ephemeral event alongside {@link OperationStart}\n * so subscribers (such as the undo/redo history tracker) can observe the raw\n * input payload without persisting it to long-lived sinks.\n */\nexport const OperationInput = EventType('operation.input', {\n schema: Schema.Struct({\n /** Operation key. */\n key: Schema.String,\n /** Human-readable operation name. */\n name: Schema.optional(Schema.String),\n /** Raw operation input. Shape determined by the operation definition. */\n input: Schema.Unknown,\n }),\n isEphemeral: true,\n});\n\n/**\n * Operation output. Emitted as an ephemeral event just before\n * {@link OperationEnd} for successful invocations so subscribers (such as the\n * undo/redo history tracker) can observe the raw output payload without\n * persisting it to long-lived sinks.\n */\nexport const OperationOutput = EventType('operation.output', {\n schema: Schema.Struct({\n /** Operation key. */\n key: Schema.String,\n /** Human-readable operation name. */\n name: Schema.optional(Schema.String),\n /** Raw operation output. Shape determined by the operation definition. */\n output: Schema.Unknown,\n }),\n isEphemeral: true,\n});\n\n/**\n * Emitted when a task's status changes — a new task counts as a change from nothing.\n *\n * Nothing else in a trace says which task an agent was working on, so these events are what cut a\n * session's timeline into per-task segments. Every tool that moves a task's status emits one.\n */\nexport const TaskStatusChanged = EventType('task.statusChanged', {\n schema: Schema.Struct({\n taskId: Obj.ID,\n title: Schema.String,\n status: Task.Status,\n /** Absent when the task was just created, or held no status before. */\n previousStatus: Schema.optional(Task.Status),\n }),\n isEphemeral: false,\n});\n\n/**\n * An agent put a question to a person and stopped on it. Paired with {@link QuestionAnswered}, the\n * two bound the stretch a task spent blocked on someone else — the one gap in a session's timeline\n * that is not the agent's own latency.\n */\nexport const QuestionAsked = EventType('question.asked', {\n schema: Schema.Struct({\n /** Id of the question's entry in the task's history. */\n questionId: Obj.ID,\n /** The question as put to the reader. */\n text: Schema.String,\n /** The task the question blocks. */\n taskId: Schema.optional(Obj.ID),\n /** How many pre-baked answers were offered; free-form is always available besides these. */\n options: Schema.optional(Schema.Number),\n }),\n isEphemeral: false,\n});\n\n/** A person answered a {@link QuestionAsked}. */\nexport const QuestionAnswered = EventType('question.answered', {\n schema: Schema.Struct({\n questionId: Obj.ID,\n text: Schema.String,\n taskId: Schema.optional(Obj.ID),\n /** What the reader answered — a chosen option's title, or free-form text. */\n answer: Schema.String,\n }),\n isEphemeral: false,\n});\n\n/**\n * Human-readable status update emitted by an agent or operation.\n */\nexport const StatusUpdate = EventType('status.update', {\n schema: Schema.Struct({\n /** Human-readable status message.. */\n message: Schema.optional(Schema.String),\n\n progress: Schema.optional(\n Schema.Struct({\n /** Progress key. See {@link ProgressRegistry.key}. */\n key: Schema.String,\n\n /* Progress current item index. */\n current: Schema.optional(Schema.Number),\n\n /** Progress total item count. */\n total: Schema.optional(Schema.Number),\n\n /** Progress estimate of remaining time (ms). */\n estimate: Schema.optional(Schema.Number),\n\n /**\n * How many phases the run expects, and which is in flight. Independent of `current`/`total`,\n * which describe the phase in flight: a run can be on phase 2 of 4 and know nothing about how\n * long phase 2 is.\n */\n phases: Schema.optional(Schema.Number),\n phase: Schema.optional(Schema.Number),\n }),\n ),\n }),\n isEphemeral: true,\n});\n\n/**\n * Emit the current human-readable execution status to the trace.\n */\nexport const emitStatus: (\n messageOrData: string | PayloadType<typeof StatusUpdate>,\n) => Effect.Effect<void, never, TraceService> = (message) =>\n write(StatusUpdate, typeof message === 'string' ? { message } : message);\n\n//\n// Agent events. Keyed `assistant.*` because that is what every recorded trace carries; they live\n// here rather than in the assistant so a reader of the trace does not depend on the AI stack.\n//\n\n/**\n * Partial content block emitted.\n */\nexport const PartialBlock = EventType('assistant.partialBlock', {\n schema: Schema.Struct({\n messageId: Obj.ID,\n role: Actor.Role,\n block: ContentBlock.Any,\n }),\n isEphemeral: true,\n});\n\n/**\n * Complete content block emitted.\n */\nexport const CompleteBlock = EventType('assistant.completeBlock', {\n schema: Schema.Struct({\n messageId: Obj.ID,\n role: Actor.Role,\n block: ContentBlock.Any,\n }),\n isEphemeral: false,\n});\n\nexport const AgentRequestBegin = EventType('assistant.agentRequestBegin', {\n schema: Schema.Struct({}),\n isEphemeral: false,\n});\n\nexport const AgentRequestEnd = EventType('assistant.agentRequestEnd', {\n schema: Schema.Struct({\n status: Schema.Literals(['success', 'error', 'interrupted']),\n error: Schema.optional(Schema.String),\n }),\n isEphemeral: false,\n});\n\n/**\n * Emitted by the supervisor when a delegated task is handed to a sub-agent process; the only durable\n * record of the task ↔ pid pairing, since nothing is stamped on the task itself.\n */\nexport const DelegationSpawned = EventType('assistant.delegationSpawned', {\n schema: Schema.Struct({\n taskId: Schema.String,\n pid: Schema.String,\n }),\n isEphemeral: false,\n});\n\n/**\n * Emitted by the supervisor when a delegated sub-agent's result has been folded back into the\n * conversation — the counterpart of {@link DelegationSpawned}, and the only durable record that the\n * return happened at all. A child's own trace ends with its operation; that it reported *to someone*\n * is knowable only from the supervisor's side, so without this the delegation reads as a one-way\n * spawn even though the runtime genuinely returns a value.\n */\nexport const DelegationCompleted = EventType('assistant.delegationCompleted', {\n schema: Schema.Struct({\n taskId: Schema.String,\n pid: Schema.String,\n status: Schema.Literals(['success', 'failure']),\n /** The result, rendered for a reader; the payload itself lives on the task and in the feed. */\n result: Schema.optional(Schema.String),\n }),\n isEphemeral: false,\n});\n\n/**\n * Emitted when an MCP server connection fails for a request turn.\n * Ephemeral so that misconfigured/unreachable servers don't pollute the durable feed,\n * but can still be surfaced to the user via the live ephemeral event stream.\n */\nexport const McpServerError = EventType('assistant.mcpServerError', {\n schema: Schema.Struct({\n url: Schema.String,\n protocol: Schema.Literals(['sse', 'http']),\n message: Schema.String,\n /** The server wants credentials the configuration does not (validly) supply. */\n unauthorized: Schema.optional(Schema.Boolean),\n }),\n isEphemeral: true,\n});\n\n/**\n * Stage a request has reached, in the order a turn passes through them.\n *\n * The reader waits through the setup stages before the first token arrives, and that wait is\n * dominated by whichever one is slow for their setup (a cold MCP server, a summarization pass over a\n * long feed), so each is named rather than folded into a single \"working\" state. The stages past\n * setup (`generating`, `calling-tool`) keep the line alive for the rest of the turn: an agentic turn\n * spends most of its time in tool calls, where a cleared line reads as a finished request.\n */\nexport const RequestPhaseName = Schema.Literals([\n /** Client-side: the agent process is being spawned or attached. Never emitted by the agent itself. */\n 'starting',\n /** The turn fiber has begun; nothing has been loaded yet. */\n 'preparing',\n 'loading-history',\n 'summarizing',\n 'connecting-mcp',\n 'building-toolkit',\n 'encoding-prompt',\n 'contacting-provider',\n /**\n * The model is streaming its reply. Derived client-side from the arriving blocks rather than\n * emitted by the agent: a write from inside the streaming pipeline adds a yield between parsing a\n * block and submitting it, which is observable in what the tools of that turn then see.\n */\n 'generating',\n /** A tool the model called is executing; `detail` carries the tool's name. */\n 'calling-tool',\n /**\n * The turn is over and the process is resident only to fire a pending alarm. Reported so the line\n * stops naming the stage the last turn ended in, which reads as a request that is still working.\n */\n 'sleeping',\n]);\nexport type RequestPhaseName = Schema.Schema.Type<typeof RequestPhaseName>;\n\n/**\n * Setup stage a request has reached, emitted as the agent enters it.\n *\n * Ephemeral: this is progress for a wait that is over by the time anyone could read it back, and the\n * feed already records the turn's outcome. The UI shows the latest phase until the turn settles.\n */\nexport const RequestPhase = EventType('assistant.requestPhase', {\n schema: Schema.Struct({\n phase: RequestPhaseName,\n\n /**\n * 1-based attempt at the phase. Only `contacting-provider` re-attempts (a request the provider\n * rejected for permissions that have not propagated yet), and only there does a value above 1\n * mean anything to the reader.\n */\n attempt: Schema.optional(Schema.Number),\n\n /** Phase-specific label, e.g. the number of MCP servers being contacted. */\n detail: Schema.optional(Schema.String),\n }),\n isEphemeral: true,\n});\n\n/**\n * Emit the setup stage the request has reached.\n */\nexport const emitRequestPhase = (\n phase: RequestPhaseName,\n opts: { attempt?: number; detail?: string } = {},\n): Effect.Effect<void, never, TraceService> => write(RequestPhase, { phase, ...opts });\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,IAAa,eAAb,cAAkC,QAAQ,QAA8B,CAAC,CAAC,8BAA8B,CAAC,CAAC,CAAC;;;;AAK3G,SAAgB,MAAS,WAAyB,SAA+D;CAC/G,OAAO,OAAO,IAAI,aAAa;EAC7B,IAAI,eAAe;GAAE,KAAK,UAAU;GAAK,aAAa,UAAU;EAAY,GAAA;GAAA,YAAA;GAAA,GAAA;GAAA,GAAA;GAAA,GAAA;EAAA,CAAC;EAE7E,CAAA,OADsB,aAAA,CACf,MAAM,WAAW,OAAO;CACjC,CAAC;AACH;AAWA,IAAa,aACX,KACA,SACiB;CACjB,OAAO;EACL;EACA,QAAQ,KAAK;EACb,aAAa,KAAK;CACpB;AACF;AAOA,IAAa,QAAQ,OAAO,OAAO;CACjC,WAAW,OAAO;CAClB,MAAM,OAAO;CACb,MAAM,OAAO;AACf,CAAC;;;;AAMD,IAAa,YAAgC,WAAyB,UAAuC;CAC3G,OAAO,MAAM,SAAS,UAAU;AAClC;;;;AAKA,IAAa,cAAc,OAAO,OAAO,KAAK,OAAO,MAAM,iCAAiC,CAAC;;;;AAM7F,IAAa,oBAAoB;;;;CAI/B,OAAO,YAAY,KAAK,OAAO;CAC/B,eAAe,YAAY,KAAK,gBAAgB;CAChD,kBAAkB,YAAY,KAAK,oBAAoB;CACvD,wBAAwB,YAAY,KAAK,2BAA2B;AACtE;;;;AAMA,IAAa,OAAO,OAAO,OAAO;CAChC,KAAK,OAAO,SAAS,OAAO,MAAM;CAClC,WAAW,OAAO,SAAS,OAAO,MAAM;CACxC,aAAa,OAAO,SAAS,OAAO,MAAM;;;;;CAM1C,OAAO,OAAO,SAA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AAOD,IAAa,iBAAiB,UAAU,4BAA4B;CAClE,QAAQ,OAAO,OAAO;EACpB,KAAK,OAAO;EACZ,UAAU,OAAO,SAAS,CAAC,OAAO,MAAM,CAAC;EACzC,SAAS,OAAO;;EAEhB,cAAc,OAAO,SAAS,OAAO,OAAO;CAC9C,CAAC;CACD,aAAa;AACf,CAAC;;;;;;;;;;AAWD,IAAa,mBAAmB,OAAO,SAAS;CAE9C;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CAMA;CAEA;CAKA;AACF,CAAC;;;;;;;AASD,IAAa,eAAe,UAAU,0BAA0B;CAC9D,QAAQ,OAAO,OAAO;EACpB,OAAO;;;;;;EAOP,SAAS,OAAO,SAAS,OAAO,MAAM;;EAGtC,QAAQ,OAAO,SAAS,OAAO,MAAM;CACvC,CAAC;CACD,aAAa;AACf,CAAC;;;;AAKD,IAAa,oBACX,OACA,OAA8C,CAAC,MACF,MAAM,cAAc;CAAE;CAAO,GAAG;AAAK,CAAC"}
|
|
1
|
+
{"version":3,"file":"chunk-Trace.mjs","names":["Trigger.Trigger","Message"],"sources":["../../src/Trace.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Schema from 'effect/Schema';\n\nimport { Annotation, DXN, Obj, Ref, Type } from '@dxos/echo';\nimport { EID } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { Actor, ContentBlock, Task } from '@dxos/types';\n\nimport * as Trigger from './types/Trigger.ts';\n\n/**\n * Writes ephemeral or persistent events to the trace.\n * Exposed to processes and operations to record events to the trace.\n */\nexport interface Writer {\n /** `meta` carries what only the writing fiber knows, such as its {@link CurrentThread}. */\n write<T>(eventType: EventType<T>, payload: NoInfer<T>, meta?: FiberMeta): void;\n}\n\n/**\n * Meta a {@link Writer} cannot know from its process alone.\n */\nexport type FiberMeta = Pick<Meta, 'thread'>;\n\n/**\n * Lane of the agent turn the current fiber runs (its light thread, or the prompt a turn on main answers), stamped\n * on its events as {@link Meta.thread}\n * and on the processes it spawns as {@link Meta.parentThread}: one process runs several turns at once,\n * and the pid alone cannot tell their events apart.\n */\nexport const CurrentThread: Context.Reference<string | undefined> = Context.Reference<string | undefined>(\n '@dxos/compute/Trace/CurrentThread',\n { defaultValue: () => undefined },\n);\n\n/**\n * Service that writes events to the trace.\n * Exposed to processes and operations to record events to the trace.\n */\nexport class TraceService extends Context.Service<TraceService, Writer>()('@dxos/functions/TraceService') {}\n\n/**\n * Writes an event to the trace.\n */\nexport function write<T>(eventType: EventType<T>, payload: NoInfer<T>): Effect.Effect<void, never, TraceService> {\n return Effect.gen(function* () {\n log('trace write', { key: eventType.key, isEphemeral: eventType.isEphemeral });\n const writer = yield* TraceService;\n const thread = yield* CurrentThread;\n writer.write(eventType, payload, thread === undefined ? undefined : { thread });\n });\n}\n\n/**\n * Defines an event type for the trace.\n */\nexport interface EventType<T> {\n readonly key: string;\n readonly schema: Schema.Codec<T, any>;\n readonly isEphemeral: boolean;\n}\n\nexport const EventType = <T>(\n key: string,\n opts: { schema: Schema.Codec<T, any>; isEphemeral: boolean },\n): EventType<T> => {\n return {\n key,\n schema: opts.schema,\n isEphemeral: opts.isEphemeral,\n };\n};\n\n/**\n * Extracts the payload type from an event type.\n */\nexport type PayloadType<E extends EventType<unknown>> = E extends EventType<infer T> ? T : never;\n\nexport const Event = Schema.Struct({\n timestamp: Schema.Number,\n type: Schema.String,\n data: Schema.Unknown, // Type-specific payload;\n});\nexport type Event = Schema.Schema.Type<typeof Event>;\n\n/**\n * Checks if an event is of a given type.\n */\nexport const isOfType = <T, E extends Event>(eventType: EventType<T>, event: E): event is E & { data: T } => {\n return event.type === eventType.key;\n};\n\n/**\n * Extensible name informing which runtime executed the code that produced the event.\n */\nexport const RuntimeName = Schema.String.pipe(Schema.brand('@dxos/compute/Trace/RuntimeName'));\nexport type RuntimeName = Schema.Schema.Type<typeof RuntimeName>;\n\n/**\n * Common runtime names.\n */\nexport const CommonRuntimeName = {\n /**\n * Web app / CLI / Desktop app / Mobile app.\n */\n local: RuntimeName.make('local'),\n edgeIntrinsic: RuntimeName.make('edge-intrinsic'),\n edgeWorkerLoader: RuntimeName.make('edge-worker-loader'),\n edgeWorkerForPlatforms: RuntimeName.make('edge-worker-for-platforms'),\n};\n\n/**\n * Metadata on the context of a trace message.\n */\n// TODO(dmaretskyi): Expand on this: conversation id, tool call id, etc.\nexport const Meta = Schema.Struct({\n pid: Schema.optional(Schema.String), // NOTE: Not Process.ID to avoid circular dependency.\n parentPid: Schema.optional(Schema.String),\n\n /**\n * Pid of the first invocation of the run this message belongs to.\n * A run that calls `Operation.runAgain()` continues in a new invocation with its own `pid`; each\n * continuation carries the first invocation's `pid` here so consumers can show the run as one unit.\n * Absent on the first invocation, whose own `pid` is the run's id.\n */\n runId: Schema.optional(Schema.String),\n\n processName: Schema.optional(Schema.String),\n\n /**\n * Space the message was produced in.\n * Stored as a string to avoid circular dependency on `@dxos/keys`.\n */\n space: Schema.optional(Schema.String),\n\n /**\n * Ref to the conversation feed object if present.\n */\n conversation: Ref.Ref(Obj.Unknown).pipe(Schema.optional),\n\n /**\n * Ref to the trigger object if invocation resulted from a trigger.\n */\n trigger: Ref.Ref(Trigger.Trigger).pipe(Schema.optional),\n\n /**\n * ID of the tool call that created the current process.\n */\n toolCallId: Schema.optional(Schema.String),\n\n /**\n * Extensible name informing which runtime executed the code that produced the event.\n */\n runtimeName: Schema.optional(RuntimeName),\n\n /**\n * Lane of the process's turn that produced the event (see {@link CurrentThread}).\n */\n thread: Schema.optional(Schema.String),\n\n /**\n * Light thread of the parent process's turn that spawned this process.\n */\n parentThread: Schema.optional(Schema.String),\n});\nexport type Meta = Schema.Schema.Type<typeof Meta>;\n\n/**\n * Checks if a runtime is an edge runtime.\n */\nexport const isEdgeRuntime = (name: RuntimeName): boolean =>\n name === CommonRuntimeName.edgeIntrinsic ||\n name === CommonRuntimeName.edgeWorkerLoader ||\n name === CommonRuntimeName.edgeWorkerForPlatforms;\n\n/**\n * Envelope for a set of events.\n */\nexport const MessageData = Schema.Struct({\n meta: Meta,\n isEphemeral: Schema.Boolean,\n events: Schema.Array(Event),\n});\nexport type MessageData = Schema.Schema.Type<typeof MessageData>;\n\nexport class Message extends Type.makeObject<Message>(DXN.make('org.dxos.type.traceMessage', '0.1.0'))(\n MessageData.pipe(Annotation.IconAnnotation.set({ icon: 'ph--note--regular', hue: 'rose' })),\n) {}\n\n/**\n * Flattened representation of a signle event in a trace message.\n * Events are stored in batched messages for efficiency, but flat representation is more convenient for consumption.\n */\nexport interface FlatEvent extends Event {\n readonly meta: Meta;\n readonly isEphemeral: boolean;\n}\n\n/**\n * Flattens a trace message into a list of flat events.\n */\nexport const flatten = (message: Message): FlatEvent[] => {\n return message.events.map((event) => ({\n ...event,\n meta: message.meta,\n isEphemeral: message.isEphemeral,\n }));\n};\n\n//\n// Swarm broadcast (DX-1125).\n//\n// Ephemeral trace messages produced on a remote runtime are broadcast over the space swarm and\n// projected into the client's progress UI. The publisher tags each message with a flat key:value list\n// derived from its meta; subscribers register a coarse tag (OR match at the swarm) and re-apply the\n// exact filter (AND) client-side.\n//\n\n/**\n * `google.protobuf.Any` type URL for a trace message broadcast over the swarm.\n */\nexport const TRACE_MESSAGE_TYPE_URL = 'dxos.compute.TraceMessage';\n\n/**\n * Declarative, serializable filter over trace messages. All present fields are ANDed. `type` matches\n * against event types within the message; the rest match against {@link Meta} fields. Refs\n * (`conversation`, `trigger`) are matched by their DXN string.\n */\nexport interface Filter {\n readonly type?: string;\n readonly pid?: string;\n readonly parentPid?: string;\n readonly conversation?: string;\n readonly trigger?: string;\n readonly space?: string;\n readonly runtimeName?: string;\n readonly toolCallId?: string;\n}\n\n/**\n * Derive the flat broadcast tag list for a message (DX-1125). The publisher emits all applicable tags;\n * subscribers match a subset (logical OR).\n */\nexport const messageToTags = (message: Pick<MessageData, 'meta' | 'events'>): string[] => {\n const { meta } = message;\n const tags: string[] = [];\n for (const event of message.events) {\n tags.push(`type:${event.type}`);\n }\n if (meta.pid) {\n tags.push(`pid:${meta.pid}`);\n }\n if (meta.parentPid) {\n tags.push(`parentPid:${meta.parentPid}`);\n }\n if (meta.conversation) {\n tags.push(`conversation:${meta.conversation.uri.toString()}`);\n }\n if (meta.trigger) {\n tags.push(`trigger:${meta.trigger.uri.toString()}`);\n }\n if (meta.space) {\n tags.push(`space:${meta.space}`);\n }\n if (meta.runtimeName) {\n tags.push(`runtime:${meta.runtimeName}`);\n }\n if (meta.toolCallId) {\n tags.push(`toolCall:${meta.toolCallId}`);\n }\n return tags;\n};\n\n/**\n * Pick the coarse subscription tag for a filter (DX-1125). The swarm cuts traffic to a superset of the\n * filter using its most selective present dimension; the client re-applies the exact filter.\n */\nexport const subscriptionTagForFilter = (filter: Filter): string | undefined => {\n if (filter.conversation !== undefined) {\n return `conversation:${filter.conversation}`;\n }\n if (filter.trigger !== undefined) {\n return `trigger:${filter.trigger}`;\n }\n if (filter.parentPid !== undefined) {\n return `parentPid:${filter.parentPid}`;\n }\n if (filter.pid !== undefined) {\n return `pid:${filter.pid}`;\n }\n if (filter.space !== undefined) {\n return `space:${filter.space}`;\n }\n if (filter.type !== undefined) {\n return `type:${filter.type}`;\n }\n return undefined;\n};\n\n/**\n * Exact (AND) filter match applied client-side after the coarse swarm subscription.\n */\nexport const matchesFilter = (message: Pick<MessageData, 'meta' | 'events'>, filter: Filter): boolean => {\n const { meta } = message;\n if (filter.type !== undefined && !message.events.some((event) => event.type === filter.type)) {\n return false;\n }\n if (filter.pid !== undefined && meta.pid !== filter.pid) {\n return false;\n }\n if (filter.parentPid !== undefined && meta.parentPid !== filter.parentPid) {\n return false;\n }\n if (filter.conversation !== undefined && meta.conversation?.uri.toString() !== filter.conversation) {\n return false;\n }\n if (filter.trigger !== undefined && meta.trigger?.uri.toString() !== filter.trigger) {\n return false;\n }\n if (filter.space !== undefined && meta.space !== filter.space) {\n return false;\n }\n if (filter.runtimeName !== undefined && meta.runtimeName !== filter.runtimeName) {\n return false;\n }\n if (filter.toolCallId !== undefined && meta.toolCallId !== filter.toolCallId) {\n return false;\n }\n return true;\n};\n\n/**\n * Wire-safe subset of {@link Meta} for broadcast. Ref fields (`conversation`, `trigger`) are not\n * carried in the payload — they are represented only as envelope tags — so the decoded message never\n * attempts ref resolution on the consumer.\n */\nconst encodeMetaForWire = (meta: Meta): Meta => ({\n pid: meta.pid,\n parentPid: meta.parentPid,\n runId: meta.runId,\n processName: meta.processName,\n space: meta.space,\n toolCallId: meta.toolCallId,\n runtimeName: meta.runtimeName,\n thread: meta.thread,\n parentThread: meta.parentThread,\n});\n\n/**\n * Encode a trace message for the broadcast envelope's `google.protobuf.Any.value` (DX-1125).\n * The wire format is UTF-8 JSON of the message data (ref fields dropped — see {@link encodeMetaForWire}).\n */\nexport const encodeTraceMessage = (message: Pick<MessageData, 'meta' | 'isEphemeral' | 'events'>): Uint8Array =>\n new TextEncoder().encode(\n JSON.stringify({\n meta: encodeMetaForWire(message.meta),\n isEphemeral: message.isEphemeral,\n events: message.events,\n }),\n );\n\n/**\n * Decode a broadcast trace message back into a {@link Message} object (DX-1125). The wire payload\n * drops both ref meta fields (see {@link encodeMetaForWire}), so `tags` — the broadcast envelope's\n * tag list — is required to restore them: `trigger` addresses work for cancellation, and\n * `conversation` is what {@link matchesFilter} compares, so a subscription filtered by it matches\n * nothing without this. Restored refs are address-only (`.uri`); they are never resolved.\n */\nexport const decodeTraceMessage = (bytes: Uint8Array, tags?: readonly string[]): Message => {\n const parsed = JSON.parse(new TextDecoder().decode(bytes)) as Partial<MessageData>;\n const meta = parsed.meta ?? {};\n const conversation = meta.conversation ?? refFromTags<Obj.Unknown>(tags, 'conversation:');\n const trigger = meta.trigger ?? refFromTags<Trigger.Trigger>(tags, 'trigger:');\n return Obj.make(Message, {\n meta: {\n ...meta,\n ...(conversation ? { conversation } : {}),\n ...(trigger ? { trigger } : {}),\n },\n isEphemeral: parsed.isEphemeral ?? true,\n events: parsed.events ?? [],\n });\n};\n\n/** The ref carried on a broadcast envelope's `<prefix><uri>` tag, when present and parseable. */\nconst refFromTags = <T>(tags: readonly string[] | undefined, prefix: string): Ref.Ref<T> | undefined => {\n const uri = tags?.find((tag) => tag.startsWith(prefix))?.slice(prefix.length);\n const eid = uri !== undefined ? EID.tryParse(uri) : undefined;\n return eid !== undefined ? Ref.fromURI(eid) : undefined;\n};\n\n/**\n * Sink for complete trace messages.\n */\nexport interface Sink {\n write(message: Message): void;\n}\n\n/**\n * Sink for complete trace messages.\n * The Process Manager forwards trace messages to it.\n */\n// TODO(dmaretskyi): Consider moving sink to the Process Manager.\nexport class TraceSink extends Context.Service<TraceSink, Sink>()('@dxos/functions/TraceSink') {}\n\nexport const noopWriter: Writer = {\n write: () => {},\n};\n\nexport const writerLayerNoop: Layer.Layer<TraceService> = Layer.succeed(TraceService, noopWriter);\n\nexport const noopSink: Sink = {\n write: () => {},\n};\n\nexport const layerNoop: Layer.Layer<TraceSink> = Layer.succeed(TraceSink, noopSink);\n\nexport const layerConsole: Layer.Layer<TraceSink> = Layer.succeed(TraceSink, {\n write: (message) => {\n console.log(message);\n },\n});\n\n/**\n * Merge a set of sinks into a single sink.\n *\n * Each message is forwarded to every sink in order. Failures in one sink do not\n * prevent downstream sinks from receiving the message.\n */\nexport const mergeSinks = (sinks: readonly Sink[]): Sink => {\n if (sinks.length === 0) {\n return noopSink;\n }\n // Intentionally no singleton fast path: the guarded wrapper is the\n // contract of `mergeSinks`, so a throwing sink is always caught and\n // logged regardless of how many sinks were passed in.\n return {\n write: (message) => {\n for (const sink of sinks) {\n try {\n sink.write(message);\n } catch (err) {\n // Intentional: do not let one sink break the chain.\n // eslint-disable-next-line no-console\n console.error('[trace] sink.write threw', err);\n }\n }\n },\n };\n};\n\n/**\n * Builds a {@link TraceService} layer that wraps each `write` into a fresh {@link Message}\n * and forwards it to the provided {@link TraceSink}. Intended for tests and lightweight\n * fixtures.\n *\n * Options:\n * - `meta`: stamped on every emitted message (defaults to `{}`).\n * - `clock`: timestamp source (defaults to {@link Date.now}). Pass a monotonic counter\n * in tests to make event ordering deterministic when many writes happen in the same\n * millisecond.\n */\nexport const testTraceService = (\n opts: { meta?: Meta; clock?: () => number } = {},\n): Layer.Layer<TraceService, never, TraceSink> =>\n Layer.effect(\n TraceService,\n Effect.gen(function* () {\n const sink = yield* TraceSink;\n const clock = opts.clock ?? Date.now;\n return {\n write: (event, data, fiberMeta) => {\n sink.write(\n Obj.make(Message, {\n meta: { ...opts.meta, ...fiberMeta },\n isEphemeral: event.isEphemeral,\n events: [{ type: event.key, timestamp: clock(), data }],\n }),\n );\n },\n };\n }),\n );\n\n//\n// Operation Trace Events\n//\n\n/**\n * Outcome of an operation invocation.\n */\nexport type OperationOutcome = 'success' | 'failure';\n\n/**\n * Operation invocation started.\n */\nexport const OperationStart = EventType('operation.start', {\n schema: Schema.Struct({\n /** Operation key. */\n key: Schema.String,\n /** Human-readable operation name. */\n name: Schema.optional(Schema.String),\n /** Phosphor icon identifier in `ph--<name>--<variant>` format. */\n icon: Schema.optional(Schema.String),\n }),\n isEphemeral: false,\n});\n\n/**\n * Operation invocation ended.\n */\nexport const OperationEnd = EventType('operation.end', {\n schema: Schema.Struct({\n /** Operation key. */\n key: Schema.String,\n /** Human-readable operation name. */\n name: Schema.optional(Schema.String),\n /** Phosphor icon identifier in `ph--<name>--<variant>` format. */\n icon: Schema.optional(Schema.String),\n /** Outcome of the operation. */\n outcome: Schema.Literals(['success', 'failure']),\n /** Error message if the operation failed. */\n error: Schema.optional(Schema.String),\n /**\n * Stable code (error name) of the failure, when the operation failed with a typed error.\n * Lets consumers match on the error kind (e.g. a run-again yield) without parsing the message.\n */\n errorCode: Schema.optional(Schema.String),\n }),\n isEphemeral: false,\n});\n\n/**\n * Operation input. Emitted as an ephemeral event alongside {@link OperationStart}\n * so subscribers (such as the undo/redo history tracker) can observe the raw\n * input payload without persisting it to long-lived sinks.\n */\nexport const OperationInput = EventType('operation.input', {\n schema: Schema.Struct({\n /** Operation key. */\n key: Schema.String,\n /** Human-readable operation name. */\n name: Schema.optional(Schema.String),\n /** Raw operation input. Shape determined by the operation definition. */\n input: Schema.Unknown,\n }),\n isEphemeral: true,\n});\n\n/**\n * Operation output. Emitted as an ephemeral event just before\n * {@link OperationEnd} for successful invocations so subscribers (such as the\n * undo/redo history tracker) can observe the raw output payload without\n * persisting it to long-lived sinks.\n */\nexport const OperationOutput = EventType('operation.output', {\n schema: Schema.Struct({\n /** Operation key. */\n key: Schema.String,\n /** Human-readable operation name. */\n name: Schema.optional(Schema.String),\n /** Raw operation output. Shape determined by the operation definition. */\n output: Schema.Unknown,\n }),\n isEphemeral: true,\n});\n\n/**\n * Emitted when a task's status changes — a new task counts as a change from nothing.\n *\n * Nothing else in a trace says which task an agent was working on, so these events are what cut a\n * session's timeline into per-task segments. Every tool that moves a task's status emits one.\n */\nexport const TaskStatusChanged = EventType('task.statusChanged', {\n schema: Schema.Struct({\n taskId: Obj.ID,\n title: Schema.String,\n status: Task.Status,\n /** Absent when the task was just created, or held no status before. */\n previousStatus: Schema.optional(Task.Status),\n }),\n isEphemeral: false,\n});\n\n/**\n * An agent put a question to a person and stopped on it. Paired with {@link QuestionAnswered}, the\n * two bound the stretch a task spent blocked on someone else — the one gap in a session's timeline\n * that is not the agent's own latency.\n */\nexport const QuestionAsked = EventType('question.asked', {\n schema: Schema.Struct({\n /** Id of the question's entry in the task's history. */\n questionId: Obj.ID,\n /** The question as put to the reader. */\n text: Schema.String,\n /** The task the question blocks. */\n taskId: Schema.optional(Obj.ID),\n /** How many pre-baked answers were offered; free-form is always available besides these. */\n options: Schema.optional(Schema.Number),\n }),\n isEphemeral: false,\n});\n\n/** A person answered a {@link QuestionAsked}. */\nexport const QuestionAnswered = EventType('question.answered', {\n schema: Schema.Struct({\n questionId: Obj.ID,\n text: Schema.String,\n taskId: Schema.optional(Obj.ID),\n /** What the reader answered — a chosen option's title, or free-form text. */\n answer: Schema.String,\n }),\n isEphemeral: false,\n});\n\n/**\n * Human-readable status update emitted by an agent or operation.\n */\nexport const StatusUpdate = EventType('status.update', {\n schema: Schema.Struct({\n /** Human-readable status message.. */\n message: Schema.optional(Schema.String),\n\n progress: Schema.optional(\n Schema.Struct({\n /** Progress key. See {@link ProgressRegistry.key}. */\n key: Schema.String,\n\n /* Progress current item index. */\n current: Schema.optional(Schema.Number),\n\n /** Progress total item count. */\n total: Schema.optional(Schema.Number),\n\n /** Progress estimate of remaining time (ms). */\n estimate: Schema.optional(Schema.Number),\n\n /**\n * How many phases the run expects, and which is in flight. Independent of `current`/`total`,\n * which describe the phase in flight: a run can be on phase 2 of 4 and know nothing about how\n * long phase 2 is.\n */\n phases: Schema.optional(Schema.Number),\n phase: Schema.optional(Schema.Number),\n }),\n ),\n }),\n isEphemeral: true,\n});\n\n/** {@link StatusUpdate} message that ends a run's progress: the meter completes and is removed. */\nexport const StatusComplete = 'progress.complete';\n\n/** {@link StatusUpdate} message that ends a sync's progress as failed; the meter stays visible. */\nexport const StatusFailed = 'Sync failed';\n\n/** {@link StatusUpdate} message that ends any other run's progress as failed; the meter stays visible. */\nexport const StatusError = 'Failed';\n\n/** {@link StatusUpdate} message that ends a run's progress as cancelled: the meter is removed. */\nexport const StatusCancelled = 'Cancelled';\n\n/**\n * Emit the current human-readable execution status to the trace.\n */\nexport const emitStatus: (\n messageOrData: string | PayloadType<typeof StatusUpdate>,\n) => Effect.Effect<void, never, TraceService> = (message) =>\n write(StatusUpdate, typeof message === 'string' ? { message } : message);\n\n//\n// Agent events. Keyed `assistant.*` because that is what every recorded trace carries; they live\n// here rather than in the assistant so a reader of the trace does not depend on the AI stack.\n//\n\n/**\n * Partial content block emitted.\n */\nexport const PartialBlock = EventType('assistant.partialBlock', {\n schema: Schema.Struct({\n messageId: Obj.ID,\n role: Actor.Role,\n block: ContentBlock.Any,\n }),\n isEphemeral: true,\n});\n\n/**\n * Complete content block emitted.\n */\nexport const CompleteBlock = EventType('assistant.completeBlock', {\n schema: Schema.Struct({\n messageId: Obj.ID,\n role: Actor.Role,\n block: ContentBlock.Any,\n }),\n isEphemeral: false,\n});\n\nexport const AgentRequestBegin = EventType('assistant.agentRequestBegin', {\n schema: Schema.Struct({}),\n isEphemeral: false,\n});\n\nexport const AgentRequestEnd = EventType('assistant.agentRequestEnd', {\n schema: Schema.Struct({\n status: Schema.Literals(['success', 'error', 'interrupted']),\n error: Schema.optional(Schema.String),\n }),\n isEphemeral: false,\n});\n\n/**\n * The end-request hooks a request runs, resolved when it begins (see `Hook.resolve`): which ran by their plugin's\n * default, which a setting turned on but whose skill is unbound, and which plugins a setting turned on that this\n * host lacks. Written only when one of those is non-empty.\n */\nexport const AgentHooksResolved = EventType('assistant.agentHooksResolved', {\n schema: Schema.Struct({\n run: Schema.Array(Schema.String),\n byDefault: Schema.Array(Schema.String),\n inactive: Schema.Array(Schema.String),\n missing: Schema.Array(Schema.String),\n }),\n isEphemeral: false,\n});\n\n/**\n * Emitted by the supervisor when a delegated task is handed to a sub-agent process; the only durable\n * record of the task ↔ pid pairing, since nothing is stamped on the task itself.\n */\nexport const DelegationSpawned = EventType('assistant.delegationSpawned', {\n schema: Schema.Struct({\n taskId: Schema.String,\n pid: Schema.String,\n }),\n isEphemeral: false,\n});\n\n/**\n * Emitted by the supervisor when a delegated sub-agent's result has been folded back into the\n * conversation — the counterpart of {@link DelegationSpawned}, and the only durable record that the\n * return happened at all. A child's own trace ends with its operation; that it reported *to someone*\n * is knowable only from the supervisor's side, so without this the delegation reads as a one-way\n * spawn even though the runtime genuinely returns a value.\n */\nexport const DelegationCompleted = EventType('assistant.delegationCompleted', {\n schema: Schema.Struct({\n taskId: Schema.String,\n pid: Schema.String,\n status: Schema.Literals(['success', 'failure']),\n /** The result, rendered for a reader; the payload itself lives on the task and in the feed. */\n result: Schema.optional(Schema.String),\n }),\n isEphemeral: false,\n});\n\n/**\n * One language-model call's token usage, written by the metered `AiService` (see `AiMetering`).\n * Durable so a run's cost can be read back from its trace; dollars are applied at read time from the\n * model catalog's prices, which change.\n */\nexport const ModelCall = EventType('ai.modelCall', {\n schema: Schema.Struct({\n /** Catalog id of the model (a DXN string). */\n modelId: Schema.optional(Schema.String),\n /** The provider's name for the model. */\n model: Schema.String,\n provider: Schema.optional(Schema.String),\n /** The pipeline or agent stage that made the call. */\n stage: Schema.optional(Schema.String),\n spanName: Schema.optional(Schema.String),\n inputTokens: Schema.Number,\n outputTokens: Schema.Number,\n cacheReadTokens: Schema.Number,\n cacheWriteTokens: Schema.Number,\n /** Epoch milliseconds. */\n start: Schema.Number,\n end: Schema.Number,\n }),\n isEphemeral: false,\n});\n\n/**\n * Emitted when an MCP server connection fails for a request turn.\n * Ephemeral so that misconfigured/unreachable servers don't pollute the durable feed,\n * but can still be surfaced to the user via the live ephemeral event stream.\n */\nexport const McpServerError = EventType('assistant.mcpServerError', {\n schema: Schema.Struct({\n url: Schema.String,\n protocol: Schema.Literals(['sse', 'http']),\n message: Schema.String,\n /** The server wants credentials the configuration does not (validly) supply. */\n unauthorized: Schema.optional(Schema.Boolean),\n }),\n isEphemeral: true,\n});\n\n/**\n * Stage a request has reached, in the order a turn passes through them.\n *\n * The reader waits through the setup stages before the first token arrives, and that wait is\n * dominated by whichever one is slow for their setup (a cold MCP server, a summarization pass over a\n * long feed), so each is named rather than folded into a single \"working\" state. The stages past\n * setup (`generating`, `calling-tool`) keep the line alive for the rest of the turn: an agentic turn\n * spends most of its time in tool calls, where a cleared line reads as a finished request.\n */\nexport const RequestPhaseName = Schema.Literals([\n /** Client-side: the agent process is being spawned or attached. Never emitted by the agent itself. */\n 'starting',\n /** The turn fiber has begun; nothing has been loaded yet. */\n 'preparing',\n 'loading-history',\n 'summarizing',\n 'connecting-mcp',\n 'building-toolkit',\n 'encoding-prompt',\n 'contacting-provider',\n /**\n * The model is streaming its reply. Derived client-side from the arriving blocks rather than\n * emitted by the agent: a write from inside the streaming pipeline adds a yield between parsing a\n * block and submitting it, which is observable in what the tools of that turn then see.\n */\n 'generating',\n /** A tool the model called is executing; `detail` carries the tool's name. */\n 'calling-tool',\n /**\n * The turn is over and the process is resident only to fire a pending alarm. Reported so the line\n * stops naming the stage the last turn ended in, which reads as a request that is still working.\n */\n 'sleeping',\n]);\nexport type RequestPhaseName = Schema.Schema.Type<typeof RequestPhaseName>;\n\n/**\n * Setup stage a request has reached, emitted as the agent enters it.\n *\n * Ephemeral: this is progress for a wait that is over by the time anyone could read it back, and the\n * feed already records the turn's outcome. The UI shows the latest phase until the turn settles.\n */\nexport const RequestPhase = EventType('assistant.requestPhase', {\n schema: Schema.Struct({\n phase: RequestPhaseName,\n\n /**\n * 1-based attempt at the phase. Only `contacting-provider` re-attempts (a request the provider\n * rejected for permissions that have not propagated yet), and only there does a value above 1\n * mean anything to the reader.\n */\n attempt: Schema.optional(Schema.Number),\n\n /** Phase-specific label, e.g. the number of MCP servers being contacted. */\n detail: Schema.optional(Schema.String),\n }),\n isEphemeral: true,\n});\n\n/**\n * Emit the setup stage the request has reached.\n */\nexport const emitRequestPhase = (\n phase: RequestPhaseName,\n opts: { attempt?: number; detail?: string } = {},\n): Effect.Effect<void, never, TraceService> => write(RequestPhase, { phase, ...opts });\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,IAAa,gBAAuD,QAAQ,UAC1E,qCACA,EAAE,oBAAoB,KAAA,EAAU,CAClC;;;;;AAMA,IAAa,eAAb,cAAkC,QAAQ,QAA8B,CAAC,CAAC,8BAA8B,CAAC,CAAC,CAAC;;;;AAK3G,SAAgB,MAAS,WAAyB,SAA+D;CAC/G,OAAO,OAAO,IAAI,aAAa;EAC7B,IAAI,eAAe;GAAE,KAAK,UAAU;GAAK,aAAa,UAAU;EAAY,GAAA;GAAA,YAAA;GAAA,GAAA;GAAA,GAAA;GAAA,GAAA;EAAA,CAAC;EAC7E,MAAM,SAAS,OAAO;EACtB,MAAM,SAAS,OAAO;EACtB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,OAAO,SAAS,OAAO,MAAM;CACvC,CAAC;CACD,aAAa;AACf,CAAC;;;;;;AAOD,IAAa,YAAY,UAAU,gBAAgB;CACjD,QAAQ,OAAO,OAAO;;EAEpB,SAAS,OAAO,SAAS,OAAO,MAAM;;EAEtC,OAAO,OAAO;EACd,UAAU,OAAO,SAAS,OAAO,MAAM;;EAEvC,OAAO,OAAO,SAAS,OAAO,MAAM;EACpC,UAAU,OAAO,SAAS,OAAO,MAAM;EACvC,aAAa,OAAO;EACpB,cAAc,OAAO;EACrB,iBAAiB,OAAO;EACxB,kBAAkB,OAAO;;EAEzB,OAAO,OAAO;EACd,KAAK,OAAO;CACd,CAAC;CACD,aAAa;AACf,CAAC;;;;;;AAOD,IAAa,iBAAiB,UAAU,4BAA4B;CAClE,QAAQ,OAAO,OAAO;EACpB,KAAK,OAAO;EACZ,UAAU,OAAO,SAAS,CAAC,OAAO,MAAM,CAAC;EACzC,SAAS,OAAO;;EAEhB,cAAc,OAAO,SAAS,OAAO,OAAO;CAC9C,CAAC;CACD,aAAa;AACf,CAAC;;;;;;;;;;AAWD,IAAa,mBAAmB,OAAO,SAAS;CAE9C;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CAMA;CAEA;CAKA;AACF,CAAC;;;;;;;AASD,IAAa,eAAe,UAAU,0BAA0B;CAC9D,QAAQ,OAAO,OAAO;EACpB,OAAO;;;;;;EAOP,SAAS,OAAO,SAAS,OAAO,MAAM;;EAGtC,QAAQ,OAAO,SAAS,OAAO,MAAM;CACvC,CAAC;CACD,aAAa;AACf,CAAC;;;;AAKD,IAAa,oBACX,OACA,OAA8C,CAAC,MACF,MAAM,cAAc;CAAE;CAAO,GAAG;AAAK,CAAC"}
|
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
|
|
2
|
+
import { r as Skill } from "./chunk-Skill.mjs";
|
|
3
|
+
import * as Schema from "effect/Schema";
|
|
4
|
+
import { ContentBlock, Message } from "@dxos/types";
|
|
5
|
+
import { Annotation, DXN, Feed, Obj, Ref, Type } from "@dxos/echo";
|
|
6
|
+
import { IdentityDid } from "@dxos/keys";
|
|
7
|
+
//#region src/trajectory/Trajectory.ts
|
|
8
|
+
var Trajectory_exports = /* @__PURE__ */ __exportAll({
|
|
9
|
+
AlarmCancel: () => AlarmCancel,
|
|
10
|
+
AlarmFire: () => AlarmFire,
|
|
11
|
+
AlarmSet: () => AlarmSet,
|
|
12
|
+
Compact: () => Compact,
|
|
13
|
+
ContextBind: () => ContextBind,
|
|
14
|
+
ContextUnbind: () => ContextUnbind,
|
|
15
|
+
Custom: () => Custom,
|
|
16
|
+
Event: () => Event,
|
|
17
|
+
EventId: () => EventId,
|
|
18
|
+
Fork: () => Fork,
|
|
19
|
+
HookBegin: () => HookBegin,
|
|
20
|
+
HookEnd: () => HookEnd,
|
|
21
|
+
HookKind: () => HookKind,
|
|
22
|
+
MergeMode: () => MergeMode,
|
|
23
|
+
Message: () => Message$1,
|
|
24
|
+
ModelChange: () => ModelChange,
|
|
25
|
+
Payload: () => Payload,
|
|
26
|
+
PromptCancel: () => PromptCancel,
|
|
27
|
+
PromptConsume: () => PromptConsume,
|
|
28
|
+
RequestResolve: () => RequestResolve,
|
|
29
|
+
Rewind: () => Rewind,
|
|
30
|
+
Role: () => Role,
|
|
31
|
+
Sender: () => Sender,
|
|
32
|
+
ThreadClose: () => ThreadClose,
|
|
33
|
+
ThreadId: () => ThreadId,
|
|
34
|
+
ThreadMerge: () => ThreadMerge,
|
|
35
|
+
ThreadMode: () => ThreadMode,
|
|
36
|
+
ThreadOpen: () => ThreadOpen,
|
|
37
|
+
ThreadOrigin: () => ThreadOrigin,
|
|
38
|
+
ThreadStatus: () => ThreadStatus,
|
|
39
|
+
ThreadWait: () => ThreadWait,
|
|
40
|
+
ToolBackground: () => ToolBackground,
|
|
41
|
+
ToolDeliver: () => ToolDeliver,
|
|
42
|
+
TurnBegin: () => TurnBegin,
|
|
43
|
+
TurnEnd: () => TurnEnd,
|
|
44
|
+
Usage: () => Usage,
|
|
45
|
+
is: () => is,
|
|
46
|
+
make: () => make,
|
|
47
|
+
threadOf: () => threadOf
|
|
48
|
+
});
|
|
49
|
+
/**
|
|
50
|
+
* Id of an earlier event in the same log; events reference each other by id because they are never mutated.
|
|
51
|
+
*/
|
|
52
|
+
var EventId = Obj.ID;
|
|
53
|
+
/**
|
|
54
|
+
* A thread (or turn) is a branch of the conversation's feed: its opener is the branch's base, and every event written
|
|
55
|
+
* in it continues the branch. The main thread is the root branch, which has no id.
|
|
56
|
+
*/
|
|
57
|
+
var ThreadId = Feed.BranchId;
|
|
58
|
+
/**
|
|
59
|
+
* `event` marks content from outside the conversation (alarm, webhook, email, background result), which the model
|
|
60
|
+
* sees as a synthetic user turn rather than as something a person typed.
|
|
61
|
+
*/
|
|
62
|
+
var Role = Schema.Literals([
|
|
63
|
+
"user",
|
|
64
|
+
"assistant",
|
|
65
|
+
"tool",
|
|
66
|
+
"event"
|
|
67
|
+
]);
|
|
68
|
+
var Sender = Schema.Struct({
|
|
69
|
+
role: Role,
|
|
70
|
+
/** Writer's identity, which tells participants apart in a multi-tenant chat. */
|
|
71
|
+
identity: Schema.optional(IdentityDid),
|
|
72
|
+
/** Object the sender stands for when it is not a person (agent session, service, hook). */
|
|
73
|
+
subject: Schema.optional(Ref.Ref(Obj.Unknown)),
|
|
74
|
+
name: Schema.optional(Schema.String)
|
|
75
|
+
});
|
|
76
|
+
/**
|
|
77
|
+
* Content seen by the model, attributed by the event's `sender`. A user message stays out of the prompt until a
|
|
78
|
+
* {@link PromptConsume} names it, so a prompt typed mid-turn never lands inside a prefix already sent.
|
|
79
|
+
*/
|
|
80
|
+
var Message$1 = Schema.TaggedStruct("message", {
|
|
81
|
+
blocks: Schema.Array(ContentBlock.Any),
|
|
82
|
+
/** Files or objects attached alongside the blocks, as on `Message.Message`. */
|
|
83
|
+
attachments: Schema.optional(Schema.Array(Message.Attachment)),
|
|
84
|
+
/**
|
|
85
|
+
* `Message.Message`'s properties, carried so a message converts both ways; a channel backend's post receipt lives
|
|
86
|
+
* here (e.g. `discord.messageId`), which tells a mirror the message is already posted.
|
|
87
|
+
*/
|
|
88
|
+
properties: Schema.optional(Schema.Record(Schema.String, Schema.Any))
|
|
89
|
+
});
|
|
90
|
+
var Usage = Schema.Struct({
|
|
91
|
+
inputTokens: Schema.optional(Schema.Number),
|
|
92
|
+
outputTokens: Schema.optional(Schema.Number),
|
|
93
|
+
cacheReadTokens: Schema.optional(Schema.Number),
|
|
94
|
+
cacheWriteTokens: Schema.optional(Schema.Number)
|
|
95
|
+
});
|
|
96
|
+
/**
|
|
97
|
+
* What a thread or turn could see when it started: the parent thread up to and including `event`.
|
|
98
|
+
*/
|
|
99
|
+
var ThreadOrigin = Schema.Struct({
|
|
100
|
+
/** Feed of another conversation; absent for the current one. */
|
|
101
|
+
feed: Schema.optional(Ref.Ref(Feed.Feed)),
|
|
102
|
+
/** Parent thread; absent for the main thread. */
|
|
103
|
+
thread: Schema.optional(ThreadId),
|
|
104
|
+
/**
|
|
105
|
+
* Last event of the parent that was visible: the last event the writer had folded when it wrote the opener, so an
|
|
106
|
+
* event that syncs in afterwards stays out of what the thread saw.
|
|
107
|
+
*/
|
|
108
|
+
event: EventId
|
|
109
|
+
});
|
|
110
|
+
/**
|
|
111
|
+
* Start of one model request: the base of the turn's own branch, so every event the turn produces continues that
|
|
112
|
+
* branch, and `turnEnd` (the branch's last event) merges the turn into its parent.
|
|
113
|
+
*/
|
|
114
|
+
var TurnBegin = Schema.TaggedStruct("turnBegin", {
|
|
115
|
+
/** Model DXN, as `SessionConfig.model` stores it; absent when the writer does not choose the model. */
|
|
116
|
+
model: Schema.optional(DXN.Schema),
|
|
117
|
+
/** What the turn saw; absent when it started on an empty log. */
|
|
118
|
+
from: Schema.optional(ThreadOrigin)
|
|
119
|
+
});
|
|
120
|
+
/** Ends the turn whose branch it is written on. */
|
|
121
|
+
var TurnEnd = Schema.TaggedStruct("turnEnd", {
|
|
122
|
+
finishReason: ContentBlock.FinishReason,
|
|
123
|
+
usage: Schema.optional(Usage),
|
|
124
|
+
error: Schema.optional(Schema.String)
|
|
125
|
+
});
|
|
126
|
+
/**
|
|
127
|
+
* The agent took a user message into its next turn; the message enters the prompt at this event's position.
|
|
128
|
+
*/
|
|
129
|
+
var PromptConsume = Schema.TaggedStruct("promptConsume", { message: EventId });
|
|
130
|
+
var PromptCancel = Schema.TaggedStruct("promptCancel", { message: EventId });
|
|
131
|
+
var ContextDelta = {
|
|
132
|
+
skills: Schema.Array(Ref.Ref(Skill)),
|
|
133
|
+
objects: Schema.Array(Ref.Ref(Obj.Unknown)),
|
|
134
|
+
/**
|
|
135
|
+
* Connections whose MCP server the conversation turns on (`contextBind`) or off (`contextUnbind`); one never
|
|
136
|
+
* named follows the space default.
|
|
137
|
+
*/
|
|
138
|
+
connections: Schema.optional(Schema.Array(Ref.Ref(Obj.Unknown)))
|
|
139
|
+
};
|
|
140
|
+
var ContextBind = Schema.TaggedStruct("contextBind", ContextDelta);
|
|
141
|
+
var ContextUnbind = Schema.TaggedStruct("contextUnbind", ContextDelta);
|
|
142
|
+
var AlarmSet = Schema.TaggedStruct("alarmSet", {
|
|
143
|
+
/** Epoch milliseconds. */
|
|
144
|
+
wakeAt: Schema.Number,
|
|
145
|
+
message: Schema.optional(Schema.String)
|
|
146
|
+
});
|
|
147
|
+
var AlarmCancel = Schema.TaggedStruct("alarmCancel", { alarm: EventId });
|
|
148
|
+
var AlarmFire = Schema.TaggedStruct("alarmFire", { alarm: EventId });
|
|
149
|
+
/**
|
|
150
|
+
* A tool call that outlived its turn; its result arrives later as {@link ToolDeliver}.
|
|
151
|
+
*/
|
|
152
|
+
var ToolBackground = Schema.TaggedStruct("toolBackground", {
|
|
153
|
+
toolCallId: Schema.String,
|
|
154
|
+
/** Process running the call. */
|
|
155
|
+
pid: Schema.optional(Schema.String)
|
|
156
|
+
});
|
|
157
|
+
var ToolDeliver = Schema.TaggedStruct("toolDeliver", {
|
|
158
|
+
toolCallId: Schema.String,
|
|
159
|
+
result: ContentBlock.ToolResult
|
|
160
|
+
});
|
|
161
|
+
var HookKind = Schema.Literals([
|
|
162
|
+
"inline",
|
|
163
|
+
"background",
|
|
164
|
+
"agentic"
|
|
165
|
+
]);
|
|
166
|
+
var HookBegin = Schema.TaggedStruct("hookBegin", {
|
|
167
|
+
hook: Schema.String,
|
|
168
|
+
kind: HookKind,
|
|
169
|
+
/** Thread an agentic hook runs in. */
|
|
170
|
+
thread: Schema.optional(ThreadId)
|
|
171
|
+
});
|
|
172
|
+
var HookEnd = Schema.TaggedStruct("hookEnd", {
|
|
173
|
+
begin: EventId,
|
|
174
|
+
/** Output of an inline hook, which the model sees. */
|
|
175
|
+
blocks: Schema.optional(Schema.Array(ContentBlock.Any)),
|
|
176
|
+
error: Schema.optional(Schema.String)
|
|
177
|
+
});
|
|
178
|
+
/**
|
|
179
|
+
* Replaces the inclusive range `from`..`to` with `summary` in the prompt; the events themselves stay in the log.
|
|
180
|
+
*/
|
|
181
|
+
var Compact = Schema.TaggedStruct("compact", {
|
|
182
|
+
from: EventId,
|
|
183
|
+
to: EventId,
|
|
184
|
+
summary: Schema.Array(ContentBlock.Any),
|
|
185
|
+
/** Threads whose merged entries the range holds; a thread still running is never in it. */
|
|
186
|
+
closure: Schema.optional(Schema.Array(ThreadId))
|
|
187
|
+
});
|
|
188
|
+
/**
|
|
189
|
+
* A person's answer to a `request` block an agent asked in an earlier message; the message itself never changes.
|
|
190
|
+
*/
|
|
191
|
+
var RequestResolve = Schema.TaggedStruct("requestResolve", {
|
|
192
|
+
message: EventId,
|
|
193
|
+
requestId: Schema.String,
|
|
194
|
+
resolution: Schema.Struct({
|
|
195
|
+
outcome: Schema.Literals(["selected", "cancelled"]),
|
|
196
|
+
optionId: Schema.optional(Schema.String)
|
|
197
|
+
})
|
|
198
|
+
});
|
|
199
|
+
/**
|
|
200
|
+
* Discards the main thread from `from` on: its prompt entries and thread items go, the events stay in the log.
|
|
201
|
+
*/
|
|
202
|
+
var Rewind = Schema.TaggedStruct("rewind", {
|
|
203
|
+
/** First event discarded. */
|
|
204
|
+
from: EventId });
|
|
205
|
+
/**
|
|
206
|
+
* Continues another conversation: its prompt up to `from.event` precedes this feed's main thread.
|
|
207
|
+
*/
|
|
208
|
+
var Fork = Schema.TaggedStruct("fork", { from: ThreadOrigin });
|
|
209
|
+
/**
|
|
210
|
+
* `light` is a fork of main that also starts with a transcript of each thread still running beside it (its
|
|
211
|
+
* `siblings`), so a prompt sent while the agent works runs in parallel with that work.
|
|
212
|
+
*/
|
|
213
|
+
var ThreadMode = Schema.Literals([
|
|
214
|
+
"fork",
|
|
215
|
+
"fresh",
|
|
216
|
+
"light"
|
|
217
|
+
]);
|
|
218
|
+
/**
|
|
219
|
+
* Opens a thread: the base of its own branch, whose id is the thread's; the event's `sender` owns the thread.
|
|
220
|
+
*/
|
|
221
|
+
var ThreadOpen = Schema.TaggedStruct("threadOpen", {
|
|
222
|
+
mode: ThreadMode,
|
|
223
|
+
/** Where a `fork` or `light` thread branches from; a `fresh` thread starts with no history. */
|
|
224
|
+
from: Schema.optional(ThreadOrigin),
|
|
225
|
+
purpose: Schema.optional(Schema.String),
|
|
226
|
+
/** `light` only: threads (or turns on main) still running when it opened, whose work it starts with. */
|
|
227
|
+
siblings: Schema.optional(Schema.Array(ThreadId))
|
|
228
|
+
});
|
|
229
|
+
var MergeMode = Schema.Literals(["raw", "summary"]);
|
|
230
|
+
/** Joins the thread whose branch it is written on to its parent. */
|
|
231
|
+
var ThreadMerge = Schema.TaggedStruct("threadMerge", {
|
|
232
|
+
mode: MergeMode,
|
|
233
|
+
summary: Schema.optional(Schema.Array(ContentBlock.Any))
|
|
234
|
+
});
|
|
235
|
+
/**
|
|
236
|
+
* A turn waits for another thread to end before it continues; written in the waiting turn's thread.
|
|
237
|
+
*/
|
|
238
|
+
var ThreadWait = Schema.TaggedStruct("threadWait", { on: ThreadId });
|
|
239
|
+
var ThreadStatus = Schema.Literals([
|
|
240
|
+
"completed",
|
|
241
|
+
"failed",
|
|
242
|
+
"cancelled"
|
|
243
|
+
]);
|
|
244
|
+
/** Ends the thread whose branch it is written on without merging it. */
|
|
245
|
+
var ThreadClose = Schema.TaggedStruct("threadClose", { status: ThreadStatus });
|
|
246
|
+
var ModelChange = Schema.TaggedStruct("modelChange", { model: DXN.Schema });
|
|
247
|
+
/**
|
|
248
|
+
* Extension-defined event; `blocks` reach the model only when `visible` is set.
|
|
249
|
+
*/
|
|
250
|
+
var Custom = Schema.TaggedStruct("custom", {
|
|
251
|
+
/** Namespaced extension type (e.g. `org.example.checkpoint`). */
|
|
252
|
+
type: Schema.String,
|
|
253
|
+
visible: Schema.Boolean,
|
|
254
|
+
data: Schema.optional(Schema.Unknown),
|
|
255
|
+
blocks: Schema.optional(Schema.Array(ContentBlock.Any))
|
|
256
|
+
});
|
|
257
|
+
var Payload = Schema.Union([
|
|
258
|
+
Message$1,
|
|
259
|
+
TurnBegin,
|
|
260
|
+
TurnEnd,
|
|
261
|
+
PromptConsume,
|
|
262
|
+
PromptCancel,
|
|
263
|
+
ContextBind,
|
|
264
|
+
ContextUnbind,
|
|
265
|
+
AlarmSet,
|
|
266
|
+
AlarmCancel,
|
|
267
|
+
AlarmFire,
|
|
268
|
+
ToolBackground,
|
|
269
|
+
ToolDeliver,
|
|
270
|
+
HookBegin,
|
|
271
|
+
HookEnd,
|
|
272
|
+
Compact,
|
|
273
|
+
RequestResolve,
|
|
274
|
+
Rewind,
|
|
275
|
+
Fork,
|
|
276
|
+
ThreadOpen,
|
|
277
|
+
ThreadMerge,
|
|
278
|
+
ThreadWait,
|
|
279
|
+
ThreadClose,
|
|
280
|
+
ModelChange,
|
|
281
|
+
Custom
|
|
282
|
+
]);
|
|
283
|
+
/**
|
|
284
|
+
* One immutable entry in an agent trajectory; every conversation state (history, queue, alarms, bindings, threads)
|
|
285
|
+
* is a reduction over the feed's events in feed order.
|
|
286
|
+
*/
|
|
287
|
+
var Event = class extends Type.makeObject(DXN.make("org.dxos.type.trajectory.event", "0.1.0"))(Schema.Struct({
|
|
288
|
+
sender: Sender,
|
|
289
|
+
/** ISO timestamp; display only, ordering is by feed position. */
|
|
290
|
+
created: Schema.String.pipe(Annotation.GeneratorAnnotation.set("date.iso8601")),
|
|
291
|
+
payload: Payload
|
|
292
|
+
}).pipe(Annotation.IconAnnotation.set({
|
|
293
|
+
icon: "ph--path--regular",
|
|
294
|
+
hue: "indigo"
|
|
295
|
+
}))) {};
|
|
296
|
+
/**
|
|
297
|
+
* Creates an event (not yet appended to a feed).
|
|
298
|
+
*/
|
|
299
|
+
var make = ({ id, payload, sender, thread, created }) => Obj.make(Event, {
|
|
300
|
+
id,
|
|
301
|
+
sender,
|
|
302
|
+
created: created ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
303
|
+
payload,
|
|
304
|
+
...thread !== void 0 ? { [Obj.Meta]: { keys: [Feed.branchKey(thread)] } } : {}
|
|
305
|
+
});
|
|
306
|
+
/** Branches already read off events: a fold asks for an event's thread several times, and reading meta keys is not free. */
|
|
307
|
+
var threads = /* @__PURE__ */ new WeakMap();
|
|
308
|
+
/**
|
|
309
|
+
* The thread an event belongs to: the branch it was written on, absent for the main thread. An opener (`turnBegin`,
|
|
310
|
+
* `threadOpen`) is the base of its branch, so its thread is the one it opens.
|
|
311
|
+
*/
|
|
312
|
+
var threadOf = (event) => {
|
|
313
|
+
const known = threads.get(event);
|
|
314
|
+
if (known !== void 0) return known;
|
|
315
|
+
const thread = Feed.getBranch(event);
|
|
316
|
+
if (thread !== void 0) threads.set(event, thread);
|
|
317
|
+
return thread;
|
|
318
|
+
};
|
|
319
|
+
/**
|
|
320
|
+
* Narrows an event by payload tag.
|
|
321
|
+
*/
|
|
322
|
+
var is = (event, tag) => event.payload._tag === tag;
|
|
323
|
+
//#endregion
|
|
324
|
+
export { ThreadStatus as A, threadOf as B, Sender as C, ThreadMode as D, ThreadMerge as E, TurnBegin as F, TurnEnd as I, Usage as L, ToolBackground as M, ToolDeliver as N, ThreadOpen as O, Trajectory_exports as P, is as R, Role as S, ThreadId as T, Payload as _, ContextBind as a, RequestResolve as b, Event as c, HookBegin as d, HookEnd as f, ModelChange as g, Message$1 as h, Compact as i, ThreadWait as j, ThreadOrigin as k, EventId as l, MergeMode as m, AlarmFire as n, ContextUnbind as o, HookKind as p, AlarmSet as r, Custom as s, AlarmCancel as t, Fork as u, PromptCancel as v, ThreadClose as w, Rewind as x, PromptConsume as y, make as z };
|
|
325
|
+
|
|
326
|
+
//# sourceMappingURL=chunk-Trajectory.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chunk-Trajectory.mjs","names":["Message","TypesMessage","Skill.Skill"],"sources":["../../src/trajectory/Trajectory.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Schema from 'effect/Schema';\n\nimport { Annotation, DXN, Feed, Obj, Ref, Type } from '@dxos/echo';\nimport { IdentityDid } from '@dxos/keys';\nimport { ContentBlock, Message as TypesMessage } from '@dxos/types';\n\nimport * as Skill from '../types/Skill.ts';\n\n/**\n * Id of an earlier event in the same log; events reference each other by id because they are never mutated.\n */\nexport const EventId = Obj.ID;\nexport type EventId = Schema.Schema.Type<typeof EventId>;\n\n/**\n * A thread (or turn) is a branch of the conversation's feed: its opener is the branch's base, and every event written\n * in it continues the branch. The main thread is the root branch, which has no id.\n */\nexport const ThreadId = Feed.BranchId;\nexport type ThreadId = Schema.Schema.Type<typeof ThreadId>;\n\n//\n// Sender\n//\n\n/**\n * `event` marks content from outside the conversation (alarm, webhook, email, background result), which the model\n * sees as a synthetic user turn rather than as something a person typed.\n */\nexport const Role = Schema.Literals(['user', 'assistant', 'tool', 'event']);\nexport type Role = Schema.Schema.Type<typeof Role>;\n\nexport const Sender = Schema.Struct({\n role: Role,\n /** Writer's identity, which tells participants apart in a multi-tenant chat. */\n identity: Schema.optional(IdentityDid),\n /** Object the sender stands for when it is not a person (agent session, service, hook). */\n subject: Schema.optional(Ref.Ref(Obj.Unknown)),\n name: Schema.optional(Schema.String),\n});\nexport type Sender = Schema.Schema.Type<typeof Sender>;\n\n//\n// Content\n//\n\n/**\n * Content seen by the model, attributed by the event's `sender`. A user message stays out of the prompt until a\n * {@link PromptConsume} names it, so a prompt typed mid-turn never lands inside a prefix already sent.\n */\nexport const Message = Schema.TaggedStruct('message', {\n blocks: Schema.Array(ContentBlock.Any),\n /** Files or objects attached alongside the blocks, as on `Message.Message`. */\n attachments: Schema.optional(Schema.Array(TypesMessage.Attachment)),\n /**\n * `Message.Message`'s properties, carried so a message converts both ways; a channel backend's post receipt lives\n * here (e.g. `discord.messageId`), which tells a mirror the message is already posted.\n */\n properties: Schema.optional(Schema.Record(Schema.String, Schema.Any)),\n});\nexport type Message = Schema.Schema.Type<typeof Message>;\n\n//\n// Turn\n//\n\nexport const Usage = Schema.Struct({\n inputTokens: Schema.optional(Schema.Number),\n outputTokens: Schema.optional(Schema.Number),\n cacheReadTokens: Schema.optional(Schema.Number),\n cacheWriteTokens: Schema.optional(Schema.Number),\n});\nexport type Usage = Schema.Schema.Type<typeof Usage>;\n\n/**\n * What a thread or turn could see when it started: the parent thread up to and including `event`.\n */\nexport const ThreadOrigin = Schema.Struct({\n /** Feed of another conversation; absent for the current one. */\n feed: Schema.optional(Ref.Ref(Feed.Feed)),\n /** Parent thread; absent for the main thread. */\n thread: Schema.optional(ThreadId),\n /**\n * Last event of the parent that was visible: the last event the writer had folded when it wrote the opener, so an\n * event that syncs in afterwards stays out of what the thread saw.\n */\n event: EventId,\n});\nexport type ThreadOrigin = Schema.Schema.Type<typeof ThreadOrigin>;\n\n/**\n * Start of one model request: the base of the turn's own branch, so every event the turn produces continues that\n * branch, and `turnEnd` (the branch's last event) merges the turn into its parent.\n */\nexport const TurnBegin = Schema.TaggedStruct('turnBegin', {\n /** Model DXN, as `SessionConfig.model` stores it; absent when the writer does not choose the model. */\n model: Schema.optional(DXN.Schema),\n /** What the turn saw; absent when it started on an empty log. */\n from: Schema.optional(ThreadOrigin),\n});\nexport type TurnBegin = Schema.Schema.Type<typeof TurnBegin>;\n\n/** Ends the turn whose branch it is written on. */\nexport const TurnEnd = Schema.TaggedStruct('turnEnd', {\n finishReason: ContentBlock.FinishReason,\n usage: Schema.optional(Usage),\n error: Schema.optional(Schema.String),\n});\nexport type TurnEnd = Schema.Schema.Type<typeof TurnEnd>;\n\n//\n// Prompt queue (pending = user messages with no consume or cancel).\n//\n\n/**\n * The agent took a user message into its next turn; the message enters the prompt at this event's position.\n */\nexport const PromptConsume = Schema.TaggedStruct('promptConsume', {\n message: EventId,\n});\nexport type PromptConsume = Schema.Schema.Type<typeof PromptConsume>;\n\nexport const PromptCancel = Schema.TaggedStruct('promptCancel', {\n message: EventId,\n});\nexport type PromptCancel = Schema.Schema.Type<typeof PromptCancel>;\n\n//\n// Context\n//\n\nconst ContextDelta = {\n skills: Schema.Array(Ref.Ref(Skill.Skill)),\n objects: Schema.Array(Ref.Ref(Obj.Unknown)),\n /**\n * Connections whose MCP server the conversation turns on (`contextBind`) or off (`contextUnbind`); one never\n * named follows the space default.\n */\n connections: Schema.optional(Schema.Array(Ref.Ref(Obj.Unknown))),\n};\n\nexport const ContextBind = Schema.TaggedStruct('contextBind', ContextDelta);\nexport type ContextBind = Schema.Schema.Type<typeof ContextBind>;\n\nexport const ContextUnbind = Schema.TaggedStruct('contextUnbind', ContextDelta);\nexport type ContextUnbind = Schema.Schema.Type<typeof ContextUnbind>;\n\n//\n// Alarms\n//\n\nexport const AlarmSet = Schema.TaggedStruct('alarmSet', {\n /** Epoch milliseconds. */\n wakeAt: Schema.Number,\n message: Schema.optional(Schema.String),\n});\nexport type AlarmSet = Schema.Schema.Type<typeof AlarmSet>;\n\nexport const AlarmCancel = Schema.TaggedStruct('alarmCancel', {\n alarm: EventId,\n});\nexport type AlarmCancel = Schema.Schema.Type<typeof AlarmCancel>;\n\nexport const AlarmFire = Schema.TaggedStruct('alarmFire', {\n alarm: EventId,\n});\nexport type AlarmFire = Schema.Schema.Type<typeof AlarmFire>;\n\n//\n// Background tools\n//\n\n/**\n * A tool call that outlived its turn; its result arrives later as {@link ToolDeliver}.\n */\nexport const ToolBackground = Schema.TaggedStruct('toolBackground', {\n toolCallId: Schema.String,\n /** Process running the call. */\n pid: Schema.optional(Schema.String),\n});\nexport type ToolBackground = Schema.Schema.Type<typeof ToolBackground>;\n\nexport const ToolDeliver = Schema.TaggedStruct('toolDeliver', {\n toolCallId: Schema.String,\n result: ContentBlock.ToolResult,\n});\nexport type ToolDeliver = Schema.Schema.Type<typeof ToolDeliver>;\n\n//\n// Hooks\n//\n\nexport const HookKind = Schema.Literals(['inline', 'background', 'agentic']);\nexport type HookKind = Schema.Schema.Type<typeof HookKind>;\n\nexport const HookBegin = Schema.TaggedStruct('hookBegin', {\n hook: Schema.String,\n kind: HookKind,\n /** Thread an agentic hook runs in. */\n thread: Schema.optional(ThreadId),\n});\nexport type HookBegin = Schema.Schema.Type<typeof HookBegin>;\n\nexport const HookEnd = Schema.TaggedStruct('hookEnd', {\n begin: EventId,\n /** Output of an inline hook, which the model sees. */\n blocks: Schema.optional(Schema.Array(ContentBlock.Any)),\n error: Schema.optional(Schema.String),\n});\nexport type HookEnd = Schema.Schema.Type<typeof HookEnd>;\n\n//\n// Compaction\n//\n\n/**\n * Replaces the inclusive range `from`..`to` with `summary` in the prompt; the events themselves stay in the log.\n */\nexport const Compact = Schema.TaggedStruct('compact', {\n from: EventId,\n to: EventId,\n summary: Schema.Array(ContentBlock.Any),\n /** Threads whose merged entries the range holds; a thread still running is never in it. */\n closure: Schema.optional(Schema.Array(ThreadId)),\n});\nexport type Compact = Schema.Schema.Type<typeof Compact>;\n\n/**\n * A person's answer to a `request` block an agent asked in an earlier message; the message itself never changes.\n */\nexport const RequestResolve = Schema.TaggedStruct('requestResolve', {\n message: EventId,\n requestId: Schema.String,\n resolution: Schema.Struct({\n outcome: Schema.Literals(['selected', 'cancelled']),\n optionId: Schema.optional(Schema.String),\n }),\n});\nexport type RequestResolve = Schema.Schema.Type<typeof RequestResolve>;\n\n/**\n * Discards the main thread from `from` on: its prompt entries and thread items go, the events stay in the log.\n */\nexport const Rewind = Schema.TaggedStruct('rewind', {\n /** First event discarded. */\n from: EventId,\n});\nexport type Rewind = Schema.Schema.Type<typeof Rewind>;\n\n/**\n * Continues another conversation: its prompt up to `from.event` precedes this feed's main thread.\n */\nexport const Fork = Schema.TaggedStruct('fork', {\n from: ThreadOrigin,\n});\nexport type Fork = Schema.Schema.Type<typeof Fork>;\n\n//\n// Threads\n//\n\n/**\n * `light` is a fork of main that also starts with a transcript of each thread still running beside it (its\n * `siblings`), so a prompt sent while the agent works runs in parallel with that work.\n */\nexport const ThreadMode = Schema.Literals(['fork', 'fresh', 'light']);\nexport type ThreadMode = Schema.Schema.Type<typeof ThreadMode>;\n\n/**\n * Opens a thread: the base of its own branch, whose id is the thread's; the event's `sender` owns the thread.\n */\nexport const ThreadOpen = Schema.TaggedStruct('threadOpen', {\n mode: ThreadMode,\n /** Where a `fork` or `light` thread branches from; a `fresh` thread starts with no history. */\n from: Schema.optional(ThreadOrigin),\n purpose: Schema.optional(Schema.String),\n /** `light` only: threads (or turns on main) still running when it opened, whose work it starts with. */\n siblings: Schema.optional(Schema.Array(ThreadId)),\n});\nexport type ThreadOpen = Schema.Schema.Type<typeof ThreadOpen>;\n\nexport const MergeMode = Schema.Literals(['raw', 'summary']);\nexport type MergeMode = Schema.Schema.Type<typeof MergeMode>;\n\n/** Joins the thread whose branch it is written on to its parent. */\nexport const ThreadMerge = Schema.TaggedStruct('threadMerge', {\n mode: MergeMode,\n summary: Schema.optional(Schema.Array(ContentBlock.Any)),\n});\nexport type ThreadMerge = Schema.Schema.Type<typeof ThreadMerge>;\n\n/**\n * A turn waits for another thread to end before it continues; written in the waiting turn's thread.\n */\nexport const ThreadWait = Schema.TaggedStruct('threadWait', {\n on: ThreadId,\n});\nexport type ThreadWait = Schema.Schema.Type<typeof ThreadWait>;\n\nexport const ThreadStatus = Schema.Literals(['completed', 'failed', 'cancelled']);\nexport type ThreadStatus = Schema.Schema.Type<typeof ThreadStatus>;\n\n/** Ends the thread whose branch it is written on without merging it. */\nexport const ThreadClose = Schema.TaggedStruct('threadClose', {\n status: ThreadStatus,\n});\nexport type ThreadClose = Schema.Schema.Type<typeof ThreadClose>;\n\n//\n// Config\n//\n\nexport const ModelChange = Schema.TaggedStruct('modelChange', {\n model: DXN.Schema,\n});\nexport type ModelChange = Schema.Schema.Type<typeof ModelChange>;\n\n//\n// Escape hatch\n//\n\n/**\n * Extension-defined event; `blocks` reach the model only when `visible` is set.\n */\nexport const Custom = Schema.TaggedStruct('custom', {\n /** Namespaced extension type (e.g. `org.example.checkpoint`). */\n type: Schema.String,\n visible: Schema.Boolean,\n data: Schema.optional(Schema.Unknown),\n blocks: Schema.optional(Schema.Array(ContentBlock.Any)),\n});\nexport type Custom = Schema.Schema.Type<typeof Custom>;\n\nexport const Payload = Schema.Union([\n Message,\n TurnBegin,\n TurnEnd,\n PromptConsume,\n PromptCancel,\n ContextBind,\n ContextUnbind,\n AlarmSet,\n AlarmCancel,\n AlarmFire,\n ToolBackground,\n ToolDeliver,\n HookBegin,\n HookEnd,\n Compact,\n RequestResolve,\n Rewind,\n Fork,\n ThreadOpen,\n ThreadMerge,\n ThreadWait,\n ThreadClose,\n ModelChange,\n Custom,\n]);\nexport type Payload = Schema.Schema.Type<typeof Payload>;\n\nexport type PayloadTag = Payload['_tag'];\n\nexport type PayloadOf<T extends PayloadTag> = Extract<Payload, { _tag: T }>;\n\n//\n// Event\n//\n\n/**\n * One immutable entry in an agent trajectory; every conversation state (history, queue, alarms, bindings, threads)\n * is a reduction over the feed's events in feed order.\n */\nexport class Event extends Type.makeObject<Event>(DXN.make('org.dxos.type.trajectory.event', '0.1.0'))(\n Schema.Struct({\n sender: Sender,\n /** ISO timestamp; display only, ordering is by feed position. */\n created: Schema.String.pipe(Annotation.GeneratorAnnotation.set('date.iso8601')),\n payload: Payload,\n }).pipe(Annotation.IconAnnotation.set({ icon: 'ph--path--regular', hue: 'indigo' })),\n) {}\n\n/**\n * An event narrowed to one payload kind.\n */\nexport type EventOf<T extends PayloadTag> = Event & { readonly payload: PayloadOf<T> };\n\nexport type MakeProps<T extends Payload = Payload> = {\n /** Set only when converting a record that already has an id, so references to it still resolve. */\n id?: EventId;\n payload: T;\n sender: Sender;\n /** The thread the event is written in: an append continues its branch. Absent for the main thread. */\n thread?: ThreadId;\n created?: string;\n};\n\n/**\n * Creates an event (not yet appended to a feed).\n */\nexport const make = <T extends Payload>({ id, payload, sender, thread, created }: MakeProps<T>): Event =>\n Obj.make(Event, {\n id,\n sender,\n created: created ?? new Date().toISOString(),\n payload,\n // Set at creation: putting it on afterwards opens a change on every event a turn writes.\n ...(thread !== undefined ? { [Obj.Meta]: { keys: [Feed.branchKey(thread)] } } : {}),\n });\n\n/** Branches already read off events: a fold asks for an event's thread several times, and reading meta keys is not free. */\nconst threads = new WeakMap<Event, ThreadId>();\n\n/**\n * The thread an event belongs to: the branch it was written on, absent for the main thread. An opener (`turnBegin`,\n * `threadOpen`) is the base of its branch, so its thread is the one it opens.\n */\nexport const threadOf = (event: Event): ThreadId | undefined => {\n const known = threads.get(event);\n if (known !== undefined) {\n return known;\n }\n const thread = Feed.getBranch(event);\n // An event keeps its branch once it has one; an opener has none until its fork is written, so only a found one is kept.\n if (thread !== undefined) {\n threads.set(event, thread);\n }\n return thread;\n};\n\n/**\n * Narrows an event by payload tag.\n */\nexport const is = <T extends PayloadTag>(event: Event, tag: T): event is EventOf<T> => event.payload._tag === tag;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,IAAa,UAAU,IAAI;;;;;AAO3B,IAAa,WAAW,KAAK;;;;;AAW7B,IAAa,OAAO,OAAO,SAAS;CAAC;CAAQ;CAAa;CAAQ;AAAO,CAAC;AAG1E,IAAa,SAAS,OAAO,OAAO;CAClC,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B,IAAI,KAAK,kCAAkC,OAAO,CAAC,CAAC,CACpG,OAAO,OAAO;CACZ,QAAQ;;CAER,SAAS,OAAO,OAAO,KAAK,WAAW,oBAAoB,IAAI,cAAc,CAAC;CAC9E,SAAS;AACX,CAAC,CAAC,CAAC,KAAK,WAAW,eAAe,IAAI;CAAE,MAAM;CAAqB,KAAK;AAAS,CAAC,CAAC,CACrF,CAAC,CAAC,CAAC;;;;AAoBH,IAAa,QAA2B,EAAE,IAAI,SAAS,QAAQ,QAAQ,cACrE,IAAI,KAAK,OAAO;CACd;CACA;CACA,SAAS,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CAC3C;CAEA,GAAI,WAAW,KAAA,IAAY,GAAG,IAAI,OAAO,EAAE,MAAM,CAAC,KAAK,UAAU,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC;AACnF,CAAC;;AAGH,IAAM,0BAAU,IAAI,QAAyB;;;;;AAM7C,IAAa,YAAY,UAAuC;CAC9D,MAAM,QAAQ,QAAQ,IAAI,KAAK;CAC/B,IAAI,UAAU,KAAA,GACZ,OAAO;CAET,MAAM,SAAS,KAAK,UAAU,KAAK;CAEnC,IAAI,WAAW,KAAA,GACb,QAAQ,IAAI,OAAO,MAAM;CAE3B,OAAO;AACT;;;;AAKA,IAAa,MAA4B,OAAc,QAAgC,MAAM,QAAQ,SAAS"}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
|
|
2
|
+
//#region src/trajectory/Transcript.ts
|
|
3
|
+
var Transcript_exports = /* @__PURE__ */ __exportAll({
|
|
4
|
+
BLOCK_TEXT: () => BLOCK_TEXT,
|
|
5
|
+
TAIL_ENTRIES: () => 12,
|
|
6
|
+
TOOL_TEXT: () => 300,
|
|
7
|
+
lines: () => lines,
|
|
8
|
+
render: () => render,
|
|
9
|
+
snapshot: () => snapshot,
|
|
10
|
+
status: () => status
|
|
11
|
+
});
|
|
12
|
+
/** Entries a snapshot keeps from the end of a long thread; its first entry (the request) is always kept. */
|
|
13
|
+
var TAIL_ENTRIES = 12;
|
|
14
|
+
/** Characters a tool call's arguments or result keep. */
|
|
15
|
+
var TOOL_TEXT = 300;
|
|
16
|
+
/** Characters a single text block keeps. */
|
|
17
|
+
var BLOCK_TEXT = 2e3;
|
|
18
|
+
var cut = (text, max) => text.length > max ? `${text.slice(0, max)}… (cut)` : text;
|
|
19
|
+
var renderBlock = (block) => {
|
|
20
|
+
switch (block._tag) {
|
|
21
|
+
case "text": return block.text.trim().length > 0 ? cut(block.text.trim(), BLOCK_TEXT) : void 0;
|
|
22
|
+
case "toolCall": return `[calls ${block.name}(${cut(block.input, 300)})]`;
|
|
23
|
+
case "toolResult": return `[${block.name} returned: ${cut(typeof block.result === "string" ? block.result : block.result === void 0 ? "an error" : JSON.stringify(block.result), 300)}]`;
|
|
24
|
+
case "reasoning":
|
|
25
|
+
case "stats":
|
|
26
|
+
case "status":
|
|
27
|
+
case "toolkit": return;
|
|
28
|
+
default: return `[${block._tag}]`;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* The lines of a thread's transcript; a long thread keeps its first entry and its last {@link TAIL_ENTRIES}.
|
|
33
|
+
*/
|
|
34
|
+
var lines = (entries) => {
|
|
35
|
+
return (entries.length > 13 ? [
|
|
36
|
+
entries[0],
|
|
37
|
+
void 0,
|
|
38
|
+
...entries.slice(-12)
|
|
39
|
+
] : [...entries]).flatMap((entry) => {
|
|
40
|
+
if (entry === void 0) return [`(${entries.length - 12 - 1} earlier entries left out)`];
|
|
41
|
+
const text = entry.blocks.flatMap((block) => renderBlock(block) ?? []).join("\n");
|
|
42
|
+
return text.length > 0 ? [`${entry.name ?? entry.role}: ${text}`] : [];
|
|
43
|
+
});
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* One thread wrapped in its delimiters.
|
|
47
|
+
*/
|
|
48
|
+
var render = (thread) => {
|
|
49
|
+
return [
|
|
50
|
+
`<thread ${[
|
|
51
|
+
`id="${thread.id}"`,
|
|
52
|
+
...thread.purpose ? [`title="${thread.purpose.replaceAll("\"", "'")}"`] : [],
|
|
53
|
+
...thread.owner ? [`owner="${thread.owner}"`] : [],
|
|
54
|
+
`status="${thread.status}"`
|
|
55
|
+
].join(" ")}>`,
|
|
56
|
+
...lines(thread.entries),
|
|
57
|
+
"</thread>"
|
|
58
|
+
].join("\n");
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* What a light thread starts with: the work of every thread running beside it, then the separator that tells the
|
|
62
|
+
* model that work is not its own.
|
|
63
|
+
*/
|
|
64
|
+
var snapshot = (siblings, self) => [
|
|
65
|
+
...siblings.map(render),
|
|
66
|
+
"",
|
|
67
|
+
siblings.length === 1 ? "The thread above is a separate request that is still running in parallel with this one." : "The threads above are separate requests that are still running in parallel with this one.",
|
|
68
|
+
"Their work is not yours: do not repeat, continue or answer it.",
|
|
69
|
+
`You are thread ${self}. Answer only the request that follows.`,
|
|
70
|
+
"If it depends on a result one of those threads has not produced yet, call `thread_wait` with that thread's id;",
|
|
71
|
+
"it returns once the thread ends, with what the thread did."
|
|
72
|
+
].join("\n");
|
|
73
|
+
/**
|
|
74
|
+
* One line of the latest state of a running thread, appended after the history when a turn starts.
|
|
75
|
+
*/
|
|
76
|
+
var status = (thread) => {
|
|
77
|
+
const last = thread.entries.at(-1);
|
|
78
|
+
const latest = last ? lines([last]).join(" ").replaceAll("\n", " ") : "nothing yet";
|
|
79
|
+
return `Thread ${thread.id}${thread.purpose ? ` ("${thread.purpose}")` : ""} is ${thread.status}; latest: ${cut(latest, 300)}`;
|
|
80
|
+
};
|
|
81
|
+
//#endregion
|
|
82
|
+
export { lines as a, status as c, Transcript_exports as i, TAIL_ENTRIES as n, render as o, TOOL_TEXT as r, snapshot as s, BLOCK_TEXT as t };
|
|
83
|
+
|
|
84
|
+
//# sourceMappingURL=chunk-Transcript.mjs.map
|