@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,113 +0,0 @@
1
- /**
2
- * Typewriter action — character-by-character text insertion with live cursor.
3
- *
4
- * TipTap Y.js structure: XmlFragment('default') contains:
5
- * [documentHeader, documentMeta, ...body blocks]
6
- * Each paragraph is an XmlElement('paragraph') containing XmlText nodes.
7
- *
8
- * All character indices are relative to body content only (schema nodes skipped).
9
- *
10
- * TypeDelete action — backspace simulation, deletes characters one at a time.
11
- */
12
- import * as Y from 'yjs'
13
- import type { ActorConnection } from '../actor-connection.ts'
14
- import type { TypeAction, TypeDeleteAction } from '../types.ts'
15
- import { sleep } from '../utils.ts'
16
- import {
17
- ensureDocumentStructure,
18
- findTextPosition,
19
- fragmentTextLength,
20
- getOrCreateLastParagraph,
21
- insertParagraphAfter,
22
- globalIndexOf,
23
- } from '../yjs-utils.ts'
24
-
25
- export async function executeType(
26
- actor: ActorConnection,
27
- action: TypeAction
28
- ): Promise<void> {
29
- const speed = action.speed ?? 80
30
- const variance = action.variance ?? 30
31
- const provider = await actor.getChildProvider(action.docId)
32
- const doc = provider.document
33
- const fragment = doc.getXmlFragment('default')
34
-
35
- // Ensure TipTap schema nodes exist
36
- doc.transact(() => ensureDocumentStructure(fragment))
37
-
38
- // Determine starting position
39
- const startIndex = action.position ?? fragmentTextLength(fragment)
40
-
41
- // Find the XmlText node at the starting position
42
- let currentText: Y.XmlText
43
- let currentLocalOffset: number
44
-
45
- const pos = findTextPosition(fragment, startIndex)
46
- if (pos) {
47
- currentText = pos.text
48
- currentLocalOffset = pos.offset
49
- } else {
50
- const last = getOrCreateLastParagraph(fragment)
51
- currentText = last.text
52
- currentLocalOffset = currentText.length
53
- }
54
-
55
- for (const char of action.text) {
56
- const delay = Math.max(10, speed + (Math.random() * 2 - 1) * variance)
57
- await sleep(delay)
58
-
59
- if (char === '\n') {
60
- // Re-derive global index from current node position (concurrent-safe)
61
- const globalIdx = globalIndexOf(fragment, currentText, currentLocalOffset)
62
- doc.transact(() => {
63
- currentText = insertParagraphAfter(fragment, globalIdx)
64
- currentLocalOffset = 0
65
- })
66
- } else {
67
- doc.transact(() => {
68
- currentText.insert(currentLocalOffset, char)
69
- })
70
- currentLocalOffset++
71
- }
72
-
73
- // Update cursor — re-derive global position for accuracy
74
- const cursorGlobal = globalIndexOf(fragment, currentText, currentLocalOffset)
75
- actor.setCursor(action.docId, cursorGlobal)
76
- }
77
- }
78
-
79
- export async function executeTypeDelete(
80
- actor: ActorConnection,
81
- action: TypeDeleteAction
82
- ): Promise<void> {
83
- const speed = action.speed ?? 60
84
- const variance = action.variance ?? 20
85
- const provider = await actor.getChildProvider(action.docId)
86
- const doc = provider.document
87
- const fragment = doc.getXmlFragment('default')
88
-
89
- // Find starting position
90
- const startIndex = action.position ?? fragmentTextLength(fragment)
91
- let remaining = action.count
92
-
93
- while (remaining > 0) {
94
- const delay = Math.max(10, speed + (Math.random() * 2 - 1) * variance)
95
- await sleep(delay)
96
-
97
- // Re-find position each iteration (concurrent-safe)
98
- const deleteAt = Math.max(0, startIndex - (action.count - remaining) - 1)
99
- const pos = findTextPosition(fragment, deleteAt)
100
- if (!pos || deleteAt < 0) break
101
-
102
- doc.transact(() => {
103
- if (pos.offset > 0) {
104
- pos.text.delete(pos.offset - 1, 1)
105
- }
106
- })
107
-
108
- remaining--
109
-
110
- // Update cursor
111
- actor.setCursor(action.docId, Math.max(0, deleteAt))
112
- }
113
- }
@@ -1,230 +0,0 @@
1
- /**
2
- * ActorConnection — manages a single actor's connection to the Abracadabra server.
3
- * One instance per actor. Handles auth, providers, child caching, awareness, and cursors.
4
- */
5
- import * as Y from 'yjs'
6
- import {
7
- AbracadabraProvider,
8
- AbracadabraClient,
9
- loadOrCreateKeyFile,
10
- deterministicKeypair,
11
- loginOrRegisterWithKey,
12
- openSyncedProvider,
13
- pickEntrySpace,
14
- } from '@abraca/dabra'
15
- import type { ActorDef, ServerConfig } from './types.ts'
16
- import { waitForSync, sleep, log } from './utils.ts'
17
- import { findTextPosition, fragmentTextLength } from './yjs-utils.ts'
18
-
19
- interface CachedChild {
20
- provider: AbracadabraProvider
21
- lastAccessed: number
22
- }
23
-
24
- export class ActorConnection {
25
- readonly actor: ActorDef
26
- readonly client: AbracadabraClient
27
- private _rootDocId: string | null = null
28
- private _rootDoc: Y.Doc | null = null
29
- private _rootProvider: AbracadabraProvider | null = null
30
- private _publicKey: string | null = null
31
- private _childCache = new Map<string, CachedChild>()
32
-
33
- constructor(actor: ActorDef, serverConfig: ServerConfig) {
34
- this.actor = actor
35
- // AbracadabraClient expects an HTTP(S) URL — normalize ws(s):// if provided
36
- const httpUrl = serverConfig.url
37
- .replace(/^wss:\/\//, 'https://')
38
- .replace(/^ws:\/\//, 'http://')
39
- this.client = new AbracadabraClient({ url: httpUrl })
40
- }
41
-
42
- get rootProvider(): AbracadabraProvider | null {
43
- return this._rootProvider
44
- }
45
-
46
- get rootDocId(): string | null {
47
- return this._rootDocId
48
- }
49
-
50
- /** Connect, authenticate, discover root doc, sync, and set awareness. */
51
- async connect(serverConfig: ServerConfig): Promise<void> {
52
- // Step 1: Get keypair (from file or deterministic from name)
53
- const keypair = this.actor.keyFile
54
- ? await loadOrCreateKeyFile(this.actor.keyFile)
55
- : deterministicKeypair(this.actor.name)
56
- this._publicKey = keypair.publicKeyB64
57
-
58
- // Step 2: Auth (auto-register on first run)
59
- await loginOrRegisterWithKey(this.client, keypair, {
60
- displayName: this.actor.name,
61
- deviceName: 'Orchestrator Actor',
62
- inviteCode: serverConfig.inviteCode,
63
- onRegister: () => log(`${this.actor.name}: registering new account...`),
64
- })
65
- log(`${this.actor.name}: authenticated (${keypair.publicKeyB64.slice(0, 12)}...)`)
66
-
67
- // Step 3: Pick an entry-point doc — first Space under the server root,
68
- // falling back to the first top-level doc of any kind.
69
- const { entry } = pickEntrySpace(await this.client.listChildren())
70
- const rootDocId = entry?.id ?? null
71
-
72
- if (!rootDocId) {
73
- throw new Error(`${this.actor.name}: no root document found`)
74
- }
75
- this._rootDocId = rootDocId
76
-
77
- // Step 4: Connect provider
78
- const { doc, provider } = await openSyncedProvider({ client: this.client, docId: rootDocId })
79
-
80
- this._rootDoc = doc
81
- this._rootProvider = provider
82
-
83
- // Step 5: Set awareness — actors appear as humans (isAgent: false)
84
- provider.awareness.setLocalStateField('user', {
85
- name: this.actor.name,
86
- color: this.actor.color,
87
- publicKey: this._publicKey,
88
- isAgent: false,
89
- })
90
- provider.awareness.setLocalStateField('status', null)
91
-
92
- log(`${this.actor.name}: connected to space ${rootDocId}`)
93
- }
94
-
95
- /** Get or create a child provider for a document. Caches and sets awareness. */
96
- async getChildProvider(docId: string): Promise<AbracadabraProvider> {
97
- const cached = this._childCache.get(docId)
98
- if (cached) {
99
- cached.lastAccessed = Date.now()
100
- return cached.provider
101
- }
102
-
103
- if (!this._rootProvider) {
104
- throw new Error(`${this.actor.name}: not connected`)
105
- }
106
-
107
- const childProvider = await this._rootProvider.loadChild(docId)
108
- await waitForSync(childProvider)
109
-
110
- childProvider.awareness.setLocalStateField('user', {
111
- name: this.actor.name,
112
- color: this.actor.color,
113
- publicKey: this._publicKey,
114
- isAgent: false,
115
- })
116
-
117
- this._childCache.set(docId, {
118
- provider: childProvider,
119
- lastAccessed: Date.now(),
120
- })
121
-
122
- return childProvider
123
- }
124
-
125
- /**
126
- * Set cursor position in a document (collapsed — anchor = head).
127
- *
128
- * TipTap's yCursorPlugin reads awareness field 'cursor' as
129
- * { anchor: RelativePosJSON, head: RelativePosJSON }.
130
- * Positions must point into XmlText nodes (not the fragment) with assoc=-1.
131
- */
132
- setCursor(docId: string, index: number): void {
133
- const cached = this._childCache.get(docId)
134
- if (!cached) return
135
-
136
- const fragment = cached.provider.document.getXmlFragment('default')
137
- const relPos = this._charIndexToRelativePosition(fragment, index)
138
- if (!relPos) return
139
-
140
- const json = Y.relativePositionToJSON(relPos)
141
- cached.provider.awareness.setLocalStateField('cursor', {
142
- anchor: json,
143
- head: json,
144
- })
145
- }
146
-
147
- /** Set text selection range in a document (anchor != head). */
148
- setSelection(docId: string, anchor: number, head: number): void {
149
- const cached = this._childCache.get(docId)
150
- if (!cached) return
151
-
152
- const fragment = cached.provider.document.getXmlFragment('default')
153
- const anchorPos = this._charIndexToRelativePosition(fragment, anchor)
154
- const headPos = this._charIndexToRelativePosition(fragment, head)
155
- if (!anchorPos || !headPos) return
156
-
157
- cached.provider.awareness.setLocalStateField('cursor', {
158
- anchor: Y.relativePositionToJSON(anchorPos),
159
- head: Y.relativePositionToJSON(headPos),
160
- })
161
- }
162
-
163
- /**
164
- * Convert a character index (body text only, skipping schema nodes)
165
- * to a Y.js RelativePosition pointing into the correct XmlText node.
166
- * Uses assoc=-1 (associate-left) to match TipTap's cursor behavior.
167
- */
168
- private _charIndexToRelativePosition(
169
- fragment: Y.XmlFragment,
170
- charIndex: number
171
- ): Y.RelativePosition | null {
172
- const totalLen = fragmentTextLength(fragment)
173
- const clamped = Math.max(0, Math.min(charIndex, totalLen))
174
-
175
- if (clamped === 0) {
176
- // Position at start of fragment — use assoc=-1 on the fragment itself
177
- return Y.createRelativePositionFromTypeIndex(fragment, 0, -1)
178
- }
179
-
180
- const pos = findTextPosition(fragment, clamped)
181
- if (pos) {
182
- return Y.createRelativePositionFromTypeIndex(pos.text, pos.offset, -1)
183
- }
184
-
185
- // Fallback: end of fragment
186
- return Y.createRelativePositionFromTypeIndex(fragment, fragment.length, -1)
187
- }
188
-
189
- /** Set a field on root awareness. */
190
- setRootAwareness(field: string, value: unknown): void {
191
- this._rootProvider?.awareness.setLocalStateField(field, value)
192
- }
193
-
194
- /** Set a field on a child document's awareness. */
195
- setChildAwareness(docId: string, field: string, value: unknown): void {
196
- const cached = this._childCache.get(docId)
197
- cached?.provider.awareness.setLocalStateField(field, value)
198
- }
199
-
200
- /** Disconnect and clean up all providers. */
201
- async disconnect(): Promise<void> {
202
- // Clear awareness on children
203
- for (const [, cached] of this._childCache) {
204
- cached.provider.awareness.setLocalStateField('cursor', null)
205
- }
206
-
207
- // Clear root awareness
208
- if (this._rootProvider) {
209
- this._rootProvider.awareness.setLocalStateField('status', null)
210
- this._rootProvider.awareness.setLocalStateField('docId', null)
211
- }
212
-
213
- // Wait for awareness updates to propagate before destroying
214
- await sleep(150)
215
-
216
- for (const [, cached] of this._childCache) {
217
- cached.provider.destroy()
218
- }
219
- this._childCache.clear()
220
-
221
- if (this._rootProvider) {
222
- this._rootProvider.destroy()
223
- this._rootProvider = null
224
- }
225
- this._rootDoc = null
226
- this._rootDocId = null
227
-
228
- log(`${this.actor.name}: disconnected`)
229
- }
230
- }
package/src/define.ts DELETED
@@ -1,147 +0,0 @@
1
- /**
2
- * Script definition helpers — typed factory functions for building scenes.
3
- */
4
- import type {
5
- Scene,
6
- ActorDef,
7
- ConnectAction,
8
- DisconnectAction,
9
- NavigateAction,
10
- TypeAction,
11
- TypeDeleteAction,
12
- SelectAction,
13
- MoveCursorAction,
14
- SetStatusAction,
15
- SetAwarenessAction,
16
- ClearAwarenessAction,
17
- CreateDocumentAction,
18
- MoveDocumentAction,
19
- RenameDocumentAction,
20
- WriteContentAction,
21
- DeleteContentAction,
22
- SetMetaAction,
23
- PointerMoveAction,
24
- ScrollToAction,
25
- KanbanHoverAction,
26
- KanbanDragAction,
27
- SendChatAction,
28
- WaitAction,
29
- ParallelAction,
30
- SequenceAction,
31
- RepeatAction,
32
- TimelineEntry,
33
- EasingName,
34
- } from './types.ts'
35
-
36
- /** Define a complete scene. */
37
- export function defineScene(scene: Scene): Scene {
38
- return scene
39
- }
40
-
41
- /** Define an actor. */
42
- export function actor(name: string, opts: Omit<ActorDef, 'name'>): ActorDef {
43
- return { name, ...opts }
44
- }
45
-
46
- /** Factory functions for all action types. */
47
- export const actions = {
48
- connect(): ConnectAction {
49
- return { type: 'connect' }
50
- },
51
-
52
- disconnect(): DisconnectAction {
53
- return { type: 'disconnect' }
54
- },
55
-
56
- navigate(docId: string): NavigateAction {
57
- return { type: 'navigate', docId }
58
- },
59
-
60
- type(docId: string, text: string, opts?: { speed?: number; variance?: number; position?: number }): TypeAction {
61
- return { type: 'type', docId, text, ...opts }
62
- },
63
-
64
- typeDelete(docId: string, count: number, opts?: { speed?: number; variance?: number; position?: number }): TypeDeleteAction {
65
- return { type: 'typeDelete', docId, count, ...opts }
66
- },
67
-
68
- select(docId: string, anchor: number, head: number): SelectAction {
69
- return { type: 'select', docId, anchor, head }
70
- },
71
-
72
- moveCursor(docId: string, from: number, to: number, duration: number, easing?: EasingName): MoveCursorAction {
73
- return { type: 'moveCursor', docId, from, to, duration, easing }
74
- },
75
-
76
- setStatus(status: string | null): SetStatusAction {
77
- return { type: 'setStatus', status }
78
- },
79
-
80
- setAwareness(fields: Record<string, unknown>, docId?: string): SetAwarenessAction {
81
- return { type: 'setAwareness', docId, fields }
82
- },
83
-
84
- clearAwareness(fields: string[], docId?: string): ClearAwarenessAction {
85
- return { type: 'clearAwareness', docId, fields }
86
- },
87
-
88
- createDocument(parentId: string, label: string, opts?: { docType?: string; meta?: Record<string, unknown>; assignId?: string }): CreateDocumentAction {
89
- return { type: 'createDocument', parentId, label, ...opts }
90
- },
91
-
92
- moveDocument(docId: string, newParentId: string, order?: number): MoveDocumentAction {
93
- return { type: 'moveDocument', docId, newParentId, order }
94
- },
95
-
96
- renameDocument(docId: string, label: string): RenameDocumentAction {
97
- return { type: 'renameDocument', docId, label }
98
- },
99
-
100
- writeContent(docId: string, markdown: string): WriteContentAction {
101
- return { type: 'writeContent', docId, markdown }
102
- },
103
-
104
- deleteContent(docId: string, from: number, length: number): DeleteContentAction {
105
- return { type: 'deleteContent', docId, from, length }
106
- },
107
-
108
- setMeta(docId: string, meta: Record<string, unknown>): SetMetaAction {
109
- return { type: 'setMeta', docId, meta }
110
- },
111
-
112
- pointerMove(docId: string, from: { x: number; y: number }, to: { x: number; y: number }, duration: number, easing?: EasingName): PointerMoveAction {
113
- return { type: 'pointerMove', docId, from, to, duration, easing }
114
- },
115
-
116
- scrollTo(docId: string, position: number): ScrollToAction {
117
- return { type: 'scrollTo', docId, position }
118
- },
119
-
120
- kanbanHover(docId: string, cardId: string | null): KanbanHoverAction {
121
- return { type: 'kanbanHover', docId, cardId }
122
- },
123
-
124
- kanbanDrag(docId: string, cardId: string, toColumnId: string, duration: number): KanbanDragAction {
125
- return { type: 'kanbanDrag', docId, cardId, toColumnId, duration }
126
- },
127
-
128
- sendChat(channel: string, message: string): SendChatAction {
129
- return { type: 'sendChat', channel, message }
130
- },
131
-
132
- wait(duration: number): WaitAction {
133
- return { type: 'wait', duration }
134
- },
135
-
136
- parallel(entries: TimelineEntry[]): ParallelAction {
137
- return { type: 'parallel', actions: entries }
138
- },
139
-
140
- sequence(entries: TimelineEntry[]): SequenceAction {
141
- return { type: 'sequence', actions: entries }
142
- },
143
-
144
- repeat(times: number, entries: TimelineEntry[]): RepeatAction {
145
- return { type: 'repeat', times, actions: entries }
146
- },
147
- }
package/src/easing.ts DELETED
@@ -1,15 +0,0 @@
1
- /**
2
- * Easing functions for animated actions (cursor movement, pointer, etc.)
3
- */
4
- import type { EasingName, EasingFn } from './types.ts'
5
-
6
- export const easings: Record<EasingName, EasingFn> = {
7
- linear: (t) => t,
8
- easeIn: (t) => t * t,
9
- easeOut: (t) => t * (2 - t),
10
- easeInOut: (t) => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t,
11
- }
12
-
13
- export function getEasing(name?: EasingName): EasingFn {
14
- return easings[name ?? 'easeInOut']
15
- }
package/src/index.ts DELETED
@@ -1,105 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Abracadabra Orchestrator — CouShell commercial director.
4
- *
5
- * Usage (after pnpm build:packages):
6
- * node --experimental-transform-types \
7
- * packages/orchestrator/dist/abracadabra-orchestrator.esm.js ./scripts/demo.ts
8
- *
9
- * Dry run:
10
- * node --experimental-transform-types \
11
- * packages/orchestrator/dist/abracadabra-orchestrator.esm.js --dry-run ./scripts/demo.ts
12
- */
13
- import { Orchestrator } from './orchestrator.ts'
14
-
15
- // Re-export public API for script files
16
- export { defineScene, actor, actions } from './define.ts'
17
- export { Orchestrator } from './orchestrator.ts'
18
- export type {
19
- Scene,
20
- ActorDef,
21
- ServerConfig,
22
- Action,
23
- TimelineEntry,
24
- ConnectAction,
25
- DisconnectAction,
26
- NavigateAction,
27
- TypeAction,
28
- TypeDeleteAction,
29
- SelectAction,
30
- MoveCursorAction,
31
- SetStatusAction,
32
- SetAwarenessAction,
33
- ClearAwarenessAction,
34
- CreateDocumentAction,
35
- MoveDocumentAction,
36
- RenameDocumentAction,
37
- WriteContentAction,
38
- DeleteContentAction,
39
- SetMetaAction,
40
- PointerMoveAction,
41
- ScrollToAction,
42
- KanbanHoverAction,
43
- KanbanDragAction,
44
- SendChatAction,
45
- RepeatAction,
46
- WaitAction,
47
- ParallelAction,
48
- SequenceAction,
49
- EasingName,
50
- } from './types.ts'
51
-
52
- async function main() {
53
- const args = process.argv.slice(2)
54
- const dryRun = args.includes('--dry-run')
55
- const scriptPath = args.find(a => !a.startsWith('--'))
56
-
57
- if (!scriptPath) {
58
- console.error('Usage: abracadabra-orchestrator [--dry-run] <script.ts>')
59
- console.error('')
60
- console.error(' The script file should export a Scene object (use defineScene()).')
61
- console.error('')
62
- console.error('Options:')
63
- console.error(' --dry-run Validate the scene without connecting to the server')
64
- console.error('')
65
- console.error('Example:')
66
- console.error(' node --conditions=source --experimental-transform-types \\')
67
- console.error(' packages/orchestrator/src/index.ts ./scripts/demo.ts')
68
- process.exit(1)
69
- }
70
-
71
- const orchestrator = new Orchestrator()
72
-
73
- try {
74
- await orchestrator.load(scriptPath)
75
- orchestrator.prepare()
76
-
77
- if (dryRun) {
78
- orchestrator.dryRun()
79
- } else {
80
- await orchestrator.run()
81
- }
82
- } catch (err: any) {
83
- console.error(`[orchestrator] Fatal: ${err.message}`)
84
- process.exit(1)
85
- } finally {
86
- if (!dryRun) {
87
- await orchestrator.cleanup()
88
- }
89
- }
90
- }
91
-
92
- // Only run CLI when executed directly (not imported as a library)
93
- // Check if argv[1] points to a file within this package's directory
94
- import { fileURLToPath } from 'node:url'
95
- import { dirname, resolve } from 'node:path'
96
-
97
- const __filename = fileURLToPath(import.meta.url)
98
- const __dirname = dirname(__filename)
99
-
100
- if (process.argv[1]) {
101
- const resolved = resolve(process.argv[1])
102
- if (resolved.startsWith(__dirname) || resolved.includes('abracadabra-orchestrator')) {
103
- main()
104
- }
105
- }