@lincyaw/workbench 0.2.0-rc.122 → 0.2.0-rc.123

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/src/workbench.ts CHANGED
@@ -44,6 +44,7 @@ import type { ProductionBinding, ProductionPlan, ProductionPlaybackCommand, Prod
44
44
  import { workspaceClient, WorkspaceServerError } from './workspace-client.ts'
45
45
  import type { WorkspaceClient } from './workspace-client.ts'
46
46
  import { DocumentTreeActions } from './document-tree.ts'
47
+ import { DOCUMENT_TREE_MESSAGES } from './tree-messages.ts'
47
48
  import type { AuthoringClientAction, AuthoringClientActionType, AuthoringClientActionResult, AuthoringClientSnapshot } from '@lincyaw/kernel'
48
49
  import { PRODUCTION_PLAYBACK_RATES } from '@lincyaw/kernel'
49
50
 
@@ -89,6 +90,7 @@ const DOCUMENT_RESET = {
89
90
  review: undefined, history: undefined, outside: undefined, historyFailure: undefined, isHistoryBusy: false, askFailure: undefined,
90
91
  jobs: undefined, jobsFailure: undefined, jobPreparing: undefined,
91
92
  voiceoverJobs: undefined, voiceoverJobsFailure: undefined, voiceoverCacheRefresh: undefined,
93
+ documentPeek: undefined,
92
94
  } satisfies Partial<WorkbenchState>
93
95
 
94
96
  /** A free directory for a new document called `title`, beside most of the existing ones. */
@@ -137,6 +139,7 @@ export class Workbench {
137
139
  readonly #voiceover: VoiceoverJobs
138
140
  readonly #askers = new Set<(request: AgentRequest) => Promise<AgentAnswer | void>>()
139
141
  readonly #drafters = new Set<(draft: AgentDraft) => void | Promise<void>>()
142
+ #openAgentSetup?: () => void
140
143
  readonly #previewSinks = new Set<PreviewSink>()
141
144
  readonly #playbackKeys = new Set<(command: PlaybackKey) => void>()
142
145
  #unsubscribeIr?: () => void
@@ -353,7 +356,24 @@ export class Workbench {
353
356
  /** The host's way to hand a request to the conversation's agent. */
354
357
  onAgentRequest = (asker: (request: AgentRequest) => Promise<AgentAnswer | void>): (() => void) => {
355
358
  this.#askers.add(asker)
356
- return () => this.#askers.delete(asker)
359
+ this.#set({ canAskAgent: true })
360
+ return () => {
361
+ this.#askers.delete(asker)
362
+ this.#set({ canAskAgent: this.#askers.size > 0 })
363
+ }
364
+ }
365
+
366
+ /** The host's word on whether the agent has a model to run with, and its way to open the model setup. */
367
+ setAgentReadiness(readiness: 'ready' | 'missing' | 'unknown', openSetup?: () => void): void {
368
+ this.#openAgentSetup = openSetup
369
+ if (this.#state.agentReadiness !== readiness) this.#set({ agentReadiness: readiness })
370
+ }
371
+
372
+ /** Opens the host's model setup; false when the host offers none. */
373
+ openAgentSetup(): boolean {
374
+ if (!this.#openAgentSetup) return false
375
+ this.#openAgentSetup()
376
+ return true
357
377
  }
358
378
 
359
379
  /** The host's way to put a request in the conversation's composer for the author to finish; nothing is sent. */
@@ -474,6 +494,33 @@ export class Workbench {
474
494
  return answer
475
495
  }
476
496
 
497
+ /**
498
+ * A new document written by the AI from the author's source material: creates it at the end of the top level, keeps
499
+ * the files in its folder, opens it and hands the conversation's agent the request. A document whose files could not
500
+ * be added goes to the trash again. Answers the new document's ID and whether the request was sent.
501
+ */
502
+ async writeFromMaterials(files: readonly File[], note: string, signal?: AbortSignal): Promise<{ document: string, asked: boolean }> {
503
+ if (!this.client.addDocumentMaterials || !this.tree.available) throw new Error('document-materials-unavailable')
504
+ const roots = this.#state.documentTree?.roots
505
+ const created = await this.client.operateTree!({ type: 'create', title: DOCUMENT_TREE_MESSAGES[this.#state.locale].untitled, parent: null, after: roots?.at(-1) ?? null }, signal)
506
+ const id = created.created
507
+ if (!id) throw new Error('document-materials-unavailable')
508
+ await Promise.all([this.tree.load(), this.loadDocuments()])
509
+ const dir = this.tree.dirOf(id)
510
+ let added: string[]
511
+ try {
512
+ if (dir === undefined) throw new Error('document-materials-document')
513
+ added = (await this.client.addDocumentMaterials(dir, files, signal)).files
514
+ } catch (error) {
515
+ await this.tree.operate({ type: 'trash', id }).catch(() => undefined)
516
+ throw error
517
+ }
518
+ this.#record('document.materials', { 'presmium.document': id, 'presmium.files': added.join('\n') })
519
+ await this.tree.openPlace({ document: id })
520
+ const asked = await this.askAgent(this.#messages.materialsRequest(added, note), [])
521
+ return { document: id, asked }
522
+ }
523
+
477
524
  /** Upgrades the workspace's documents to the current format, then refreshes the document list. */
478
525
  async migrateWorkspace(): Promise<import('@lincyaw/kernel').WorkspaceMigrationAnswer> {
479
526
  if (!this.client.migrateWorkspace) throw new Error('workspace-migrate-unavailable')
@@ -17,7 +17,7 @@ import type { DocumentTranscriptionRequest, TranscriptionCapabilities, Transcrip
17
17
  import { randomUUID } from '@lincyaw/kernel'
18
18
  import type { ReferenceTarget } from '@lincyaw/kernel'
19
19
  // The contract's DocumentTree is the workspace's answer; the kernel's root also names its own tree builder DocumentTree.
20
- import type { DocumentLinks, DocumentPreview, DocumentSearchHit, DocumentTree, EmbedSource, TreeOperation, TreeOperationResult } from '@lincyaw/kernel/contracts'
20
+ import type { DocumentLinks, DocumentPreview, DocumentSearchHit, DocumentTree, EmbedSource, TreeOperation, TreeOperationResult, WorkspaceAttention } from '@lincyaw/kernel/contracts'
21
21
 
22
22
  /** A change of the host's pending approvals that this author may answer. */
23
23
  export type ApprovalEvent =
@@ -83,6 +83,8 @@ export interface WorkspaceClient {
83
83
  subscribeRequests?(listener: (event: WorkspaceRequestEvent) => void): () => void
84
84
  readDocuments(document?: string): Promise<DocumentsAnswer>
85
85
  importDocuments?(files: readonly File[], signal?: AbortSignal): Promise<import('@lincyaw/kernel').DocumentImportAnswer>
86
+ /** Keeps the files as the document's source material, in its folder, recorded as one revision. */
87
+ addDocumentMaterials?(document: string, files: readonly File[], signal?: AbortSignal): Promise<import('@lincyaw/kernel').DocumentMaterialsAnswer>
86
88
  /** Converts the workspace's documents to the current format, one revision per document. */
87
89
  migrateWorkspace?(): Promise<import('@lincyaw/kernel').WorkspaceMigrationAnswer>
88
90
  /** The workspace's document tree and trash (absent for a host without one). */
@@ -92,8 +94,10 @@ export interface WorkspaceClient {
92
94
  searchDocuments?(query: string, limit?: number, signal?: AbortSignal): Promise<DocumentSearchHit[]>
93
95
  readDocumentPreview?(target: ReferenceTarget, signal?: AbortSignal): Promise<DocumentPreview>
94
96
  readEmbedSource?(source: { document: string, block: string }, signal?: AbortSignal): Promise<EmbedSource>
95
- /** Each change of the workspace's document tree (created, moved, renamed, trashed, restored). */
96
- subscribeTree?(changed: () => void, failed?: () => void): () => void
97
+ /** References and synced blocks across the workspace whose target is gone or in the trash. */
98
+ readAttention?(signal?: AbortSignal): Promise<WorkspaceAttention>
99
+ /** Each change of the workspace's document tree (created, moved, renamed, trashed, restored), and of what `readAttention` answers. */
100
+ subscribeTree?(changed: (kind: 'tree' | 'attention') => void, failed?: () => void): () => void
97
101
  planProjectChange(request: ProjectPlanRequest): Promise<ProjectPlan>
98
102
  operateDocument(operation: ProjectOperation, planned?: ProjectPlan): Promise<OperationAnswer>
99
103
  readSource(document: string, path: string): Promise<SourceAnswer>
@@ -391,6 +395,11 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
391
395
  for (const file of files) body.append('files', file, file.name)
392
396
  return call(url('documents/import'), { method: 'POST', body, signal })
393
397
  },
398
+ addDocumentMaterials: (document, files, signal) => {
399
+ const body = new FormData()
400
+ for (const file of files) body.append('files', file, file.name)
401
+ return call(url('document/materials', document), { method: 'POST', body, signal })
402
+ },
394
403
  migrateWorkspace: () => call(url('workspace/migrate'), { method: 'POST' }),
395
404
  readTree: signal => call(url('tree'), { signal }),
396
405
  operateTree: (operation, signal) => post(url('tree/operation'), operation, signal),
@@ -403,7 +412,8 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
403
412
  const routes = new URL(base, globalThis.document.baseURI)
404
413
  return answer.assets ? { ...answer, assets: Object.fromEntries(Object.entries(answer.assets).map(([id, address]) => [id, new URL(address, routes).href])) } : answer
405
414
  },
406
- subscribeTree: (changed, failed) => subscribe(url('tree/events', ''), 'tree', () => changed(), failed),
415
+ readAttention: signal => call(url('tree/attention'), { signal }),
416
+ subscribeTree: (changed, failed) => subscribe<{ type?: string }>(url('tree/events', ''), 'tree', data => changed(data?.type === 'attention' ? 'attention' : 'tree'), failed),
407
417
  readSource: (document, path) => call(url('source', document, { path })),
408
418
  saveSource: (document, path, content, base, message) => post(url('source', document), { path, content, base, ...message ? { message } : {} }),
409
419
  saveSourceTransaction: (document, changes, message) => post(url('source/transaction', document), { changes, ...message ? { message } : {} }),