@abraca/orchestrator 2.90.0 → 2.91.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.
@@ -1,153 +0,0 @@
1
- /**
2
- * Orchestrator — top-level class that loads a scene, manages actors, and runs the timeline.
3
- */
4
- import { resolve } from 'node:path'
5
- import { pathToFileURL } from 'node:url'
6
- import type { Scene } from './types.ts'
7
- import { ActorConnection } from './actor-connection.ts'
8
- import { TimelineRunner, type ErrorStrategy } from './timeline-runner.ts'
9
- import { createExecutor } from './actions/index.ts'
10
- import { log } from './utils.ts'
11
-
12
- export class Orchestrator {
13
- private scene: Scene | null = null
14
- private actors = new Map<string, ActorConnection>()
15
- private vars = new Map<string, string>()
16
-
17
- /** Load a scene from a TypeScript file. */
18
- async load(scriptPath: string): Promise<void> {
19
- const absPath = resolve(scriptPath)
20
- const fileUrl = pathToFileURL(absPath).href
21
- const mod = await import(fileUrl)
22
- const scene: Scene = mod.default ?? mod
23
-
24
- if (!scene.server?.url) {
25
- throw new Error('Scene must have server.url')
26
- }
27
- if (!scene.actors?.length) {
28
- throw new Error('Scene must have at least one actor')
29
- }
30
- if (!scene.timeline?.length) {
31
- throw new Error('Scene must have at least one timeline entry')
32
- }
33
-
34
- this.scene = scene
35
- log(`Loaded scene: ${scene.actors.length} actors, ${scene.timeline.length} timeline entries`)
36
- }
37
-
38
- /** Prepare actor connections (does not connect yet — that's a timeline action). */
39
- prepare(): void {
40
- if (!this.scene) throw new Error('No scene loaded')
41
-
42
- if (this.scene.vars) {
43
- for (const [k, v] of Object.entries(this.scene.vars)) {
44
- this.vars.set(k, v)
45
- }
46
- }
47
-
48
- for (const actorDef of this.scene.actors) {
49
- if (this.actors.has(actorDef.name)) {
50
- throw new Error(`Duplicate actor name: ${actorDef.name}`)
51
- }
52
- const conn = new ActorConnection(actorDef, this.scene.server)
53
- this.actors.set(actorDef.name, conn)
54
- }
55
-
56
- log(`Prepared ${this.actors.size} actors: ${[...this.actors.keys()].join(', ')}`)
57
- }
58
-
59
- /** Validate the scene without connecting. Logs the timeline structure. */
60
- dryRun(): void {
61
- if (!this.scene) throw new Error('No scene loaded')
62
-
63
- const actorNames = new Set(this.scene.actors.map(a => a.name))
64
- const errors: string[] = []
65
-
66
- for (let i = 0; i < this.scene.timeline.length; i++) {
67
- const entry = this.scene.timeline[i]!
68
- const prefix = `timeline[${i}]`
69
-
70
- if (entry.actor && !actorNames.has(entry.actor)) {
71
- errors.push(`${prefix}: unknown actor "${entry.actor}"`)
72
- }
73
-
74
- const needsActor = !['wait', 'parallel', 'sequence', 'repeat'].includes(entry.action.type)
75
- if (needsActor && !entry.actor) {
76
- errors.push(`${prefix}: ${entry.action.type} requires an actor`)
77
- }
78
- }
79
-
80
- if (errors.length) {
81
- log(`Dry run found ${errors.length} issue(s):`)
82
- for (const e of errors) log(` - ${e}`)
83
- } else {
84
- log('Dry run: no issues found')
85
- }
86
-
87
- // Print timeline summary
88
- const sorted = [...this.scene.timeline].sort((a, b) => (a.at ?? 0) - (b.at ?? 0))
89
- log('Timeline:')
90
- for (const entry of sorted) {
91
- const ts = `${((entry.at ?? 0) / 1000).toFixed(1)}s`
92
- const actorLabel = entry.actor ?? '—'
93
- log(` [${ts}] ${actorLabel}: ${entry.action.type}`)
94
- }
95
-
96
- if (this.scene.duration) {
97
- log(`Scene duration: ${(this.scene.duration / 1000).toFixed(1)}s`)
98
- }
99
- }
100
-
101
- /** Run the timeline. */
102
- async run(): Promise<void> {
103
- if (!this.scene) throw new Error('No scene loaded')
104
-
105
- // Run onStart hook
106
- if (this.scene.onStart) {
107
- log('Running onStart hook...')
108
- await this.scene.onStart()
109
- }
110
-
111
- const executor = createExecutor({
112
- actors: this.actors,
113
- serverConfig: this.scene.server,
114
- vars: this.vars,
115
- })
116
-
117
- const runner = new TimelineRunner()
118
- log('Starting timeline...')
119
- const startTime = Date.now()
120
-
121
- if (this.scene.duration) {
122
- // Race timeline against duration timeout
123
- const timelinePromise = runner.run(this.scene.timeline, executor)
124
- const timeoutPromise = new Promise<void>(resolve => {
125
- setTimeout(() => {
126
- log(`Scene duration reached (${this.scene!.duration}ms), stopping...`)
127
- resolve()
128
- }, this.scene.duration)
129
- })
130
- await Promise.race([timelinePromise, timeoutPromise])
131
- } else {
132
- await runner.run(this.scene.timeline, executor)
133
- }
134
-
135
- const elapsed = ((Date.now() - startTime) / 1000).toFixed(1)
136
- log(`Timeline complete in ${elapsed}s`)
137
-
138
- // Run onEnd hook
139
- if (this.scene.onEnd) {
140
- log('Running onEnd hook...')
141
- await this.scene.onEnd()
142
- }
143
- }
144
-
145
- /** Disconnect all actors gracefully. */
146
- async cleanup(): Promise<void> {
147
- const disconnects = [...this.actors.values()].map(a => a.disconnect().catch(() => {}))
148
- await Promise.all(disconnects)
149
- this.actors.clear()
150
- this.vars.clear()
151
- log('All actors disconnected')
152
- }
153
- }
@@ -1,84 +0,0 @@
1
- /**
2
- * TimelineRunner — schedules and executes timed actions with drift correction.
3
- */
4
- import type { TimelineEntry } from './types.ts'
5
- import type { ActionExecutor } from './actions/index.ts'
6
- import { sleep, log } from './utils.ts'
7
-
8
- export type ErrorStrategy = 'log' | 'abort'
9
-
10
- export interface TimelineRunnerOptions {
11
- /** How to handle action errors. 'log' continues, 'abort' stops. Default: 'log'. */
12
- onError?: ErrorStrategy
13
- }
14
-
15
- export class TimelineRunner {
16
- private sceneStartTime = 0
17
- private options: TimelineRunnerOptions
18
- readonly errors: { entry: TimelineEntry; error: Error; elapsed: number }[] = []
19
-
20
- constructor(options?: TimelineRunnerOptions) {
21
- this.options = options ?? {}
22
- }
23
-
24
- /** Get elapsed ms since scene start. */
25
- get elapsed(): number {
26
- return Date.now() - this.sceneStartTime
27
- }
28
-
29
- /** Execute all timeline entries in order with proper timing. */
30
- async run(timeline: TimelineEntry[], execute: ActionExecutor): Promise<void> {
31
- const sorted = [...timeline].sort((a, b) => (a.at ?? 0) - (b.at ?? 0))
32
- const errorStrategy = this.options.onError ?? 'log'
33
-
34
- this.sceneStartTime = Date.now()
35
- const pending: Promise<void>[] = []
36
-
37
- for (let i = 0; i < sorted.length; i++) {
38
- const entry = sorted[i]!
39
- const targetTime = entry.at ?? 0
40
- const elapsed = Date.now() - this.sceneStartTime
41
- const delay = targetTime - elapsed
42
-
43
- if (delay > 0) {
44
- await sleep(delay)
45
- }
46
-
47
- // Log progress
48
- const ts = `${((Date.now() - this.sceneStartTime) / 1000).toFixed(1)}s`
49
- const actorLabel = entry.actor ?? '—'
50
- log(`[${ts}] ${actorLabel}: ${entry.action.type}`)
51
-
52
- const actionPromise = execute(entry).catch((err: Error) => {
53
- const errorInfo = {
54
- entry,
55
- error: err,
56
- elapsed: Date.now() - this.sceneStartTime,
57
- }
58
- this.errors.push(errorInfo)
59
- log(`Error in ${entry.action.type}${entry.actor ? ` for ${entry.actor}` : ''}: ${err.message}`)
60
- if (errorStrategy === 'abort') {
61
- throw err
62
- }
63
- })
64
-
65
- // Check if the next entry has the same timestamp — if so, run in parallel
66
- const nextEntry = sorted[i + 1]
67
- if (nextEntry && (nextEntry.at ?? 0) === targetTime) {
68
- pending.push(actionPromise)
69
- } else {
70
- pending.push(actionPromise)
71
- await Promise.all(pending)
72
- pending.length = 0
73
- }
74
- }
75
-
76
- if (pending.length) {
77
- await Promise.all(pending)
78
- }
79
-
80
- if (this.errors.length) {
81
- log(`Timeline finished with ${this.errors.length} error(s)`)
82
- }
83
- }
84
- }
package/src/types.ts DELETED
@@ -1,245 +0,0 @@
1
- /**
2
- * Type definitions for the orchestrator scene format.
3
- */
4
-
5
- // ── Server & Actor ──────────────────────────────────────────────────────────
6
-
7
- export interface ServerConfig {
8
- url: string
9
- inviteCode?: string
10
- }
11
-
12
- export interface ActorDef {
13
- name: string
14
- color: string
15
- keyFile?: string
16
- avatar?: string
17
- }
18
-
19
- // ── Easing ──────────────────────────────────────────────────────────────────
20
-
21
- export type EasingFn = (t: number) => number
22
- export type EasingName = 'linear' | 'easeIn' | 'easeOut' | 'easeInOut'
23
-
24
- // ── Actions ─────────────────────────────────────────────────────────────────
25
-
26
- export interface ConnectAction { type: 'connect' }
27
- export interface DisconnectAction { type: 'disconnect' }
28
-
29
- export interface NavigateAction {
30
- type: 'navigate'
31
- docId: string
32
- }
33
-
34
- export interface TypeAction {
35
- type: 'type'
36
- docId: string
37
- text: string
38
- /** ms per character (default 80) */
39
- speed?: number
40
- /** random variance +/- ms (default 30) */
41
- variance?: number
42
- /** character index to start typing at (default: end of doc) */
43
- position?: number
44
- }
45
-
46
- export interface SelectAction {
47
- type: 'select'
48
- docId: string
49
- anchor: number
50
- head: number
51
- }
52
-
53
- export interface MoveCursorAction {
54
- type: 'moveCursor'
55
- docId: string
56
- from: number
57
- to: number
58
- duration: number
59
- easing?: EasingName
60
- }
61
-
62
- export interface SetStatusAction {
63
- type: 'setStatus'
64
- status: string | null
65
- }
66
-
67
- export interface SetAwarenessAction {
68
- type: 'setAwareness'
69
- /** If set, applies to child provider; otherwise root */
70
- docId?: string
71
- fields: Record<string, unknown>
72
- }
73
-
74
- export interface ClearAwarenessAction {
75
- type: 'clearAwareness'
76
- docId?: string
77
- fields: string[]
78
- }
79
-
80
- export interface CreateDocumentAction {
81
- type: 'createDocument'
82
- parentId: string
83
- label: string
84
- docType?: string
85
- meta?: Record<string, unknown>
86
- /** Store created doc ID under this key in vars for later reference */
87
- assignId?: string
88
- }
89
-
90
- export interface MoveDocumentAction {
91
- type: 'moveDocument'
92
- docId: string
93
- newParentId: string
94
- order?: number
95
- }
96
-
97
- export interface WriteContentAction {
98
- type: 'writeContent'
99
- docId: string
100
- markdown: string
101
- }
102
-
103
- export interface DeleteContentAction {
104
- type: 'deleteContent'
105
- docId: string
106
- from: number
107
- length: number
108
- }
109
-
110
- export interface SetMetaAction {
111
- type: 'setMeta'
112
- docId: string
113
- meta: Record<string, unknown>
114
- }
115
-
116
- export interface PointerMoveAction {
117
- type: 'pointerMove'
118
- docId: string
119
- from: { x: number; y: number }
120
- to: { x: number; y: number }
121
- duration: number
122
- easing?: EasingName
123
- }
124
-
125
- export interface ScrollToAction {
126
- type: 'scrollTo'
127
- docId: string
128
- /** 0-1 normalized scroll position */
129
- position: number
130
- }
131
-
132
- export interface KanbanHoverAction {
133
- type: 'kanbanHover'
134
- docId: string
135
- cardId: string | null
136
- }
137
-
138
- export interface KanbanDragAction {
139
- type: 'kanbanDrag'
140
- docId: string
141
- cardId: string
142
- toColumnId: string
143
- duration: number
144
- }
145
-
146
- export interface RenameDocumentAction {
147
- type: 'renameDocument'
148
- docId: string
149
- label: string
150
- }
151
-
152
- export interface SendChatAction {
153
- type: 'sendChat'
154
- /** Channel key (e.g. 'group:docId' or 'dm:key1:key2') */
155
- channel: string
156
- message: string
157
- }
158
-
159
- export interface TypeDeleteAction {
160
- type: 'typeDelete'
161
- docId: string
162
- /** Number of characters to delete (backspace) */
163
- count: number
164
- /** ms per deletion (default 60) */
165
- speed?: number
166
- /** random variance +/- ms (default 20) */
167
- variance?: number
168
- /** character index to start deleting from (default: end of doc) */
169
- position?: number
170
- }
171
-
172
- export interface RepeatAction {
173
- type: 'repeat'
174
- /** Number of times to repeat */
175
- times: number
176
- actions: TimelineEntry[]
177
- }
178
-
179
- export interface WaitAction {
180
- type: 'wait'
181
- duration: number
182
- }
183
-
184
- export interface ParallelAction {
185
- type: 'parallel'
186
- actions: TimelineEntry[]
187
- }
188
-
189
- export interface SequenceAction {
190
- type: 'sequence'
191
- actions: TimelineEntry[]
192
- }
193
-
194
- export type Action =
195
- | ConnectAction
196
- | DisconnectAction
197
- | NavigateAction
198
- | TypeAction
199
- | TypeDeleteAction
200
- | SelectAction
201
- | MoveCursorAction
202
- | SetStatusAction
203
- | SetAwarenessAction
204
- | ClearAwarenessAction
205
- | CreateDocumentAction
206
- | MoveDocumentAction
207
- | RenameDocumentAction
208
- | WriteContentAction
209
- | DeleteContentAction
210
- | SetMetaAction
211
- | PointerMoveAction
212
- | ScrollToAction
213
- | KanbanHoverAction
214
- | KanbanDragAction
215
- | SendChatAction
216
- | WaitAction
217
- | ParallelAction
218
- | SequenceAction
219
- | RepeatAction
220
-
221
- // ── Timeline ────────────────────────────────────────────────────────────────
222
-
223
- export interface TimelineEntry {
224
- /** ms from scene start (or parent start for nested entries) */
225
- at?: number
226
- /** Which actor performs this action */
227
- actor?: string
228
- action: Action
229
- }
230
-
231
- // ── Scene ───────────────────────────────────────────────────────────────────
232
-
233
- export interface Scene {
234
- server: ServerConfig
235
- actors: ActorDef[]
236
- timeline: TimelineEntry[]
237
- /** Pre-defined variables (e.g. known doc IDs) */
238
- vars?: Record<string, string>
239
- /** Max scene duration in ms. Auto-cleanup after this time. */
240
- duration?: number
241
- /** Called after all actors are prepared but before timeline runs. */
242
- onStart?: () => Promise<void> | void
243
- /** Called after timeline completes (before cleanup). */
244
- onEnd?: () => Promise<void> | void
245
- }
package/src/utils.ts DELETED
@@ -1,18 +0,0 @@
1
- /**
2
- * Utility functions for the orchestrator.
3
- *
4
- * `waitForSync` / `withTimeout` are the shared provider implementations from
5
- * `@abraca/dabra` (`DocUtils`), re-exported here so existing `./utils.ts`
6
- * importers keep working. `sleep` / `log` are orchestrator-local.
7
- */
8
- export { waitForSync, withTimeout } from '@abraca/dabra'
9
-
10
- /** Sleep for a given number of milliseconds. */
11
- export function sleep(ms: number): Promise<void> {
12
- return new Promise(resolve => setTimeout(resolve, ms))
13
- }
14
-
15
- /** Log to stderr with [orchestrator] prefix. */
16
- export function log(msg: string): void {
17
- console.error(`[orchestrator] ${msg}`)
18
- }