buckyos 0.7.183 → 0.7.185

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.
Files changed (33) hide show
  1. package/cli/dist/cli.mjs +115 -28
  2. package/cli/dist/cli.mjs.map +1 -1
  3. package/cli/modules/aiws.ts +93 -21
  4. package/cli/modules/aiws_place.ts +3 -1
  5. package/cli/modules/pikg_protocol.ts +1 -1
  6. package/cli/version.ts +1 -1
  7. package/dist/aiworkspace_client.d.ts +19 -5
  8. package/dist/aiworkspace_client.d.ts.map +1 -1
  9. package/dist/{aiws_bind-82bace11.js → aiws_bind-0654c24e.js} +2 -2
  10. package/dist/aiws_bind-0654c24e.js.map +1 -0
  11. package/dist/{aiws_bind-3b874f77.mjs → aiws_bind-0885ff99.mjs} +7 -5
  12. package/dist/aiws_bind-0885ff99.mjs.map +1 -0
  13. package/dist/aiws_ext.cjs +1 -1
  14. package/dist/aiws_ext.mjs +1 -1
  15. package/dist/{aiws_write-c2de498e.mjs → aiws_write-675664eb.mjs} +5 -3
  16. package/dist/{aiws_write-c2de498e.mjs.map → aiws_write-675664eb.mjs.map} +1 -1
  17. package/dist/{aiws_write-89b5cc2a.js → aiws_write-b0333ca1.js} +3 -3
  18. package/dist/{aiws_write-89b5cc2a.js.map → aiws_write-b0333ca1.js.map} +1 -1
  19. package/dist/aiws_write.d.ts +5 -1
  20. package/dist/aiws_write.d.ts.map +1 -1
  21. package/dist/browser.cjs +1 -1
  22. package/dist/browser.mjs +4 -4
  23. package/dist/{content_objid-dff803ff.js → content_objid-252bd154.js} +2 -2
  24. package/dist/{content_objid-dff803ff.js.map → content_objid-252bd154.js.map} +1 -1
  25. package/dist/{content_objid-a2cafba9.mjs → content_objid-39f4f273.mjs} +2 -2
  26. package/dist/{content_objid-a2cafba9.mjs.map → content_objid-39f4f273.mjs.map} +1 -1
  27. package/dist/index.cjs +1 -1
  28. package/dist/index.mjs +4 -4
  29. package/dist/node.cjs +1 -1
  30. package/dist/node.mjs +3 -3
  31. package/package.json +1 -1
  32. package/dist/aiws_bind-3b874f77.mjs.map +0 -1
  33. package/dist/aiws_bind-82bace11.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aiws_bind-0654c24e.js","sources":["../src/aiworkspace_client.ts","../src/aiws_rrule.ts","../src/aiws_schedule.ts","../src/aiws_bind.ts"],"sourcesContent":["import { canonicalJson, encodeObjQueryComponent, normalizeObjectUrl, objectSegments, objServiceUrl, parseObjectUrl } from './object_url'\nimport type { kRPCClient } from './krpc_client'\n\nexport const AIWORKSPACE_SERVICE_NAME = 'aiworkspace'\n\n/** Business results of the AI Workspace service: `{ ok, ... }`, `{ ok: false, error }`, or a three-state commit result. */\nexport interface AiwsError { code: string; retryable: boolean; detail: string; sub_code?: string; data?: unknown }\nexport type AiwsResult<T> = (T & { ok: true }) | { ok: false; error: AiwsError }\n\nexport class AiwsFailure extends Error {\n readonly code: string\n readonly subCode?: string\n readonly data?: unknown\n constructor(error: AiwsError) {\n super(`${error.code}${error.sub_code ? `/${error.sub_code}` : ''}: ${error.detail}`)\n this.name = 'AiwsFailure'\n this.code = error.code\n this.subCode = error.sub_code\n this.data = error.data\n }\n}\n\n/** A reference object (内核架构改进 D10): where, and which version. */\nexport interface AiwsReference {\n zone?: string\n workspace_id?: string\n entity_id: string\n selector?: Record<string, unknown>\n mode: 'live' | 'fixed'\n version?: { epoch: string; seq: number } | { content_root: string; path?: string }\n}\n\n/**\n * The Object URL of a Reference (buckyos doc/key url.md §6): the default\n * `obj://aiworkspace/<ws>/entities/<entity_id>` for a live reference without\n * selector; `mode=fixed`, `selector` and `version` go into the query as canonical\n * JSON, so one Reference has exactly one URL. Same rules as buckyos-api `aiws_reference_url`.\n */\nexport function aiwsReferenceUrl(reference: AiwsReference, workspaceId?: string): string {\n const ws = reference.workspace_id ?? workspaceId\n if (!ws) throw new Error('reference names no workspace')\n const query: string[] = []\n if (reference.mode === 'fixed') query.push('mode=fixed')\n if (reference.selector != null) query.push(`selector=${encodeObjQueryComponent(canonicalJson(reference.selector))}`)\n if (reference.version != null) query.push(`version=${encodeObjQueryComponent(canonicalJson(reference.version))}`)\n const base = objServiceUrl('aiworkspace', [ws, 'entities', reference.entity_id])\n return normalizeObjectUrl(query.length ? `${base}?${query.join('&')}` : base)\n}\n\n/** The Reference an `obj://aiworkspace/<ws>/entities/<entity_id>[?...]` URL projects. */\nexport function parseAiwsReferenceUrl(url: string): AiwsReference {\n const parsed = parseObjectUrl(url)\n const segments = objectSegments(parsed)\n if (parsed.kind !== 'obj' || parsed.host.name !== 'aiworkspace' || segments.length !== 3 || segments[1] !== 'entities') {\n throw new Error(`${url} is not an AI Workspace entity url`)\n }\n const reference: AiwsReference = {\n workspace_id: segments[0],\n entity_id: segments[2],\n mode: parsed.query.mode === 'fixed' ? 'fixed' : 'live',\n }\n if (parsed.query.selector !== undefined) reference.selector = JSON.parse(parsed.query.selector)\n if (parsed.query.version !== undefined) reference.version = JSON.parse(parsed.query.version)\n return reference\n}\n\n/** An entity argument: a path (`/data/销售`, `~<entity_id>/…`, from the Workspace root or an entity) or an entity id. */\nexport function aiwsTarget(target: string): { path: string } | { entity_id: string } {\n return target.startsWith('/') || target.startsWith('~') ? { path: target } : { entity_id: target }\n}\n\n/** Type filters of `doc.list` / `doc.find` / a text query: short types (`table`, `richtext`, `record`, `annotation`,\n * `block`, `container`, `asset`, `dir`, `wish`, `def`, `viewport`, `path`, `task`, `response`, `result`) or\n * `container:<kind>`, as a comma string or an array. */\nexport type AiwsTypeFilter = string | string[]\n\nexport interface AiwsListItem {\n entity_id: string\n name: string\n path: string\n type: string\n type_id: string\n kind?: string | null\n title: string | null\n children: number\n content_rev: number\n body: { state: string; format: string | null }\n schema_id?: string | null\n scope?: string\n /** A personal entity a shared one of the same name hides: reach it as `~<entity_id>`. */\n shadowed?: boolean\n}\n\nexport interface AiwsListParams {\n /** A path or an entity id (default `/`). */\n at?: string\n type?: AiwsTypeFilter\n not_type?: AiwsTypeFilter\n schema?: string\n limit?: number\n cursor?: string\n}\n\nexport interface AiwsListResult {\n at: { entity_id: string; path: string }\n items: AiwsListItem[]\n next_cursor?: string | null\n head_seq: number\n}\n\nexport interface AiwsFindParams extends AiwsListParams {\n depth?: number\n /** A literal, case-insensitive, in the name or the title. */\n name?: string\n}\n\nexport interface AiwsFindResult {\n at: { entity_id: string; path: string }\n items: (AiwsListItem & { match?: 'name' | 'title' })[]\n complete: boolean\n visited: number\n next_cursor?: string | null\n head_seq: number\n}\n\nexport interface AiwsTextQueryParams {\n case?: boolean\n at?: string\n depth?: number\n type?: AiwsTypeFilter\n not_type?: AiwsTypeFilter\n limit?: number\n cursor?: string\n}\n\nexport interface AiwsTextHit {\n entity_id: string\n path: string\n type: string\n on: 'name' | 'title' | 'body'\n selector?: Record<string, unknown>\n snippet: string\n more?: number\n}\n\nexport interface AiwsTextQueryResult {\n hits: AiwsTextHit[]\n /** An empty result means “none” only when `complete`. */\n coverage: { complete: boolean; scanned: number; bytes: number; skipped: { entity_id: string; reason: string }[] }\n at: { entity_id: string; path: string }\n next_cursor?: string | null\n head_seq: number\n}\n\nexport interface AiwsSqlParams {\n /** Positional parameters (`?`). */\n params?: unknown[]\n /** `{ alias: path | entity_id }`: only these tables, named by their alias in the SQL. */\n tables?: Record<string, string>\n /** ≤ 5000 (default 1000). */\n max_rows?: number\n /** Run only on this head (`SNAPSHOT_EXPIRED` / `HEAD_MISMATCH` otherwise). */\n expect_head?: { epoch: string; seq: number }\n}\n\nexport interface AiwsSqlResult {\n columns: string[]\n rows: unknown[][]\n truncated: boolean\n read: { table: string; entity_id: string; path: string; content_rev: number }[]\n head_seq: number\n}\n\n/** `doc.source_query`: rows of a URL table (`data_mode: url_query`) from its remote source. */\nexport interface AiwsSourceQueryParams {\n filter?: unknown\n sorts?: unknown[]\n fields?: string[]\n limit: number\n cursor?: string\n consistency?: string\n source_revision?: string\n}\n\n/** `doc.read { as: \"meta\" }`: what an entity is, without scanning its content. */\nexport interface AiwsMeta {\n entity_id: string\n path: string\n name: string\n name_follows: boolean\n title: string | null\n type: string\n type_id: string\n kind: string | null\n schema_id: string | null\n schema_version: number\n scope: string\n parent: { entity_id: string; path: string } | null\n version: { content_rev: number; meta_rev: number; life_rev: number; struct_rev: number; epoch: string; head_seq: number }\n body: { state: string; format: string | null; format_version: number; etag: string; records: number | null; bytes: number | null; reason?: string }\n /** Data entities: where the content comes from and who writes it — `edit` (Commits under `capabilities`),\n * `refresh` (only the Source's refresh; edits are `SOURCE_READ_ONLY`), `none` (a URL table: rows are remote). */\n data?: { mode: 'local' | 'synced' | 'url_query'; write: 'edit' | 'refresh' | 'none'; source?: Record<string, unknown>; derived?: Record<string, unknown> }\n children: number\n capabilities: string[]\n ops: string[]\n shows?: Record<string, unknown> | null\n definition?: Record<string, unknown>\n ref: AiwsReference\n head_seq: number\n}\n\nexport interface AiwsBodyParams {\n selector?: Record<string, unknown>\n cursor?: string\n /** 64…262 144 (default 32 768). */\n max_bytes?: number\n /** Each part's selector and its offsets in `text`. */\n parts?: boolean\n}\n\n/** `doc.read { as: \"body\" }`: one page of the entity's plain-text rendering. */\nexport interface AiwsBody {\n entity_id: string\n path: string\n text: string\n format: string\n format_version: number\n etag: string\n state: string\n complete: boolean\n next_cursor?: string | null\n parts?: { selector: Record<string, unknown>; start: number; end: number; partial?: boolean }[]\n}\n\n/** What `ext.upgrade` / `ext.build` rewrite on the instances of a definition whose new version narrows what they rely\n * on (schemas/migration.schema.json, Q30). */\nexport interface AiwsMigration {\n config?: { rename?: Record<string, string>; drop?: string[]; fill?: Record<string, unknown> }\n bindings?: { rename?: Record<string, string>; drop?: string[]; fill?: Record<string, { entity_id: string }> }\n slots?: { rename?: Record<string, string>; move?: Record<string, string> }\n events?: { rename?: Record<string, string>; drop?: string[] }\n}\n\nexport interface AiwsExtBuildParams {\n files: ({ name: string; obj_id: string } | { name: string; base64: string })[]\n folder_id?: string\n expect?: { def_rev: number; dir_rev: number }\n force?: boolean\n dry_run?: boolean\n provenance?: { pkg_id?: string; version?: string; digest?: string }\n /** With `provenance`: rebuild an identity the folder holds from another source (an upgrade across Zones, Q30). */\n upgrade?: boolean\n /** `{ <ident>: Migration }` for a build that narrows what instances rely on. */\n migration?: Record<string, AiwsMigration>\n idempotency_key?: string\n}\n\nexport interface AiwsExtUpgradeParams {\n workspace_id: string\n /** `pkg_id` default: the package the definition was imported from (`provenance.pkg_id`). */\n items: { def_entity_id: string; pkg_id?: string }[]\n migration?: Record<string, AiwsMigration>\n force?: boolean\n dry_run?: boolean\n idempotency_key?: string\n}\n\nexport interface AiwsExtUpgradeResult {\n status: 'accepted' | 'unchanged' | 'checked'\n commit_id?: string\n seq?: number\n controls: { ident: string; def_entity_id: string; action: 'upgraded' | 'unchanged'; from?: string; to?: string; migrated?: string[] }[]\n /** `dry_run`: what the migration writes on each instance. */\n plan?: { instance: string; ops: Record<string, unknown>[] }[]\n}\n\nexport interface AiwsTemplateParam { type: 'string' | 'number' | 'boolean'; title?: string; default?: string | number | boolean }\n\n/** A Workspace template of a control package (aiws-manifest.json `workspace_templates`, schemas/template.schema.json,\n * Q32): a snapshot under `templates/<id>/` and the controls of the same package it needs. */\nexport interface AiwsTemplateItem {\n id: string\n title: string\n description?: string\n snapshot: string\n digest: string\n requires: { host_api?: { html?: number; declarative?: number }; controls: string[] }\n params?: Record<string, AiwsTemplateParam>\n reset?: { tables?: string[] }\n}\n\n/** One template to export (`ext.export_template`, `ext.pack` / `ext.install` `templates`): chosen Surfaces (and data\n * entities) of the Workspace. */\nexport interface AiwsTemplateExport {\n surfaces: string[]\n data?: string[]\n template: { id: string; title: string; description?: string; params?: Record<string, AiwsTemplateParam>; reset?: { tables: string[] } }\n}\n\n/** `ext.build` / `ext.import`: one entry per control (`created | rebuilt | unchanged | satisfied`), the first also at the top. */\nexport interface AiwsExtBuildResult {\n status: 'accepted' | 'unchanged' | 'checked'\n commit_id?: string\n seq?: number\n unchanged?: boolean\n ident?: string\n def_entity_id?: string\n dir_entity_id?: string\n version?: number\n def_rev?: number\n dir_rev?: number\n action?: string\n build?: { input_digest: string; builder_version: string; built_at: string }\n controls: Record<string, unknown>[]\n diagnostics: Record<string, unknown>[]\n}\n\nexport interface AiwsLibraryPackage {\n pkg_id: string\n version: string\n title: string\n author: string\n mode: string\n installed_at: string\n /** The package's manifest_version is above what the service reads: listed, not importable. */\n needs_newer?: boolean\n controls: { ident: string; name: string; kind: string; version: number; digest: string; dir: string; title?: string; description?: string; catalog?: Record<string, unknown>; deps?: string[] }[]\n templates?: { id: string; title: string; description?: string; params?: Record<string, AiwsTemplateParam>; requires: AiwsTemplateItem['requires'] }[]\n}\n\n/** `ext.pack`: the `.pikg` the service wrote into the caller's `exports` bucket. */\nexport interface AiwsExtPackResult {\n bucket_id: string\n key: string\n obj_id: string\n size: number\n digest: string\n app_doc_object_id: string\n app_did: string\n pkg_id: string\n version: string\n /** The bucket binding with a read token (as `doc.export`'s `download`). */\n download: { bucket_id: string; key: string; version: number; obj_id: string; token: string }\n}\n\n/** What a stage's model loop used, as its executor reports it (`proc.report { usage }`): the model of the last turn,\n * the tokens of all turns, how many turns. A macro's own AI calls are counted by the program host. */\nexport interface AiwsRunUsage { model?: string; input_tokens?: number; output_tokens?: number; calls?: number }\n\n/** What an executor outside the service reports for a run (M3): the stage is done, an analysis made elsewhere, or a\n * failure — each with what it used. Results always come from the macro (`proc.program`). */\nexport interface AiwsRunReport {\n run_id: string\n attempt: number\n progress?: Record<string, unknown>\n finished?: boolean\n error?: { code: string; detail: string }\n summary?: string\n warnings?: string[]\n assumptions?: string[]\n analysis?: Record<string, unknown>\n usage?: AiwsRunUsage\n}\n\n/** One request of `doc.stage` / `doc.commit` stays under the service's 8 MiB body limit. */\nexport const AIWS_COMMIT_PART_BYTES = 6 * 1024 * 1024\n/** What one Commit may hold once its parts are assembled (aiworkspace-core `Limits`). */\nexport const AIWS_COMMIT_MAX_BYTES = 32 * 1024 * 1024\nexport const AIWS_COMMIT_MAX_OPERATIONS = 50_000\n\nexport type AiwsCall = (method: string, params: Record<string, unknown>) => Promise<unknown>\n\nexport interface AiwsCommitPartsOptions {\n /** Largest serialized size of the operations of one request (default `AIWS_COMMIT_PART_BYTES`). */\n partBytes?: number\n /** Called before request `part` of `total` is sent (1-based; the last one is the commit itself). Only when\n * the Commit is sent in more than one request. */\n onPart?: (part: number, total: number) => void\n /** `doc.prepare` instead of `doc.commit` (the parts it stages expire on their own). */\n method?: 'doc.commit' | 'doc.prepare'\n}\n\nconst utf8 = new TextEncoder()\n\nfunction jsonBytes(value: unknown): number {\n const text = JSON.stringify(value)\n // a JSON string is at most 3 UTF-8 bytes per UTF-16 unit: only count when that bound does not settle it\n return text.length\n + (/[^\\x00-\\x7f]/.test(text) ? utf8.encode(text).length - text.length : 0)\n}\n\n/** `operations` cut into runs of at most `partBytes` serialized bytes, in order; an operation larger than that\n * is a run of its own. */\nexport function splitCommitOperations<T>(operations: T[], partBytes = AIWS_COMMIT_PART_BYTES): T[][] {\n const parts: T[][] = []\n let current: T[] = []\n let size = 2\n for (const op of operations) {\n const bytes = jsonBytes(op) + 1\n if (current.length > 0 && size + bytes > partBytes) {\n parts.push(current)\n current = []\n size = 2\n }\n current.push(op)\n size += bytes\n }\n if (current.length > 0 || parts.length === 0) parts.push(current)\n return parts\n}\n\n/** Whether a Commit of these operations is within what the service assembles (`null`), or which limit it passes. */\nexport function commitOverLimit(operations: unknown[]): { limit: 'operations' | 'bytes'; value: number; max: number } | null {\n if (operations.length > AIWS_COMMIT_MAX_OPERATIONS) return { limit: 'operations', value: operations.length, max: AIWS_COMMIT_MAX_OPERATIONS }\n let bytes = 2\n for (const op of operations) bytes += jsonBytes(op) + 1\n // the envelope of the final request counts too\n return bytes + 4096 > AIWS_COMMIT_MAX_BYTES ? { limit: 'bytes', value: bytes, max: AIWS_COMMIT_MAX_BYTES } : null\n}\n\n/**\n * Send one Commit, whatever its size: a request whose operations fit `partBytes` is one `doc.commit`; a larger one\n * has its leading parts held by `doc.stage` and the last part sent as `doc.commit { staged: [digests] }`, which the\n * service assembles into the same single Commit (one transaction, one undo unit). Every call stages all parts again,\n * so resending the same request after an unknown result is safe. The three-state result is returned as it is; a\n * refused `doc.stage` comes back as a `rejected` result.\n */\nexport async function commitWithParts<T = Record<string, unknown>>(call: AiwsCall, request: Record<string, unknown>, options: AiwsCommitPartsOptions = {}): Promise<T> {\n const method = options.method ?? 'doc.commit'\n const operations = Array.isArray(request.operations) ? request.operations as unknown[] : []\n const parts = splitCommitOperations(operations, options.partBytes ?? AIWS_COMMIT_PART_BYTES)\n if (parts.length <= 1) return await call(method, request) as T\n const { workspace_id, epoch, idempotency_key } = request\n for (let attempt = 0; ; attempt++) {\n const staged: string[] = []\n for (let part = 0; part < parts.length - 1; part++) {\n options.onPart?.(part + 1, parts.length)\n const held = await call('doc.stage', { workspace_id, epoch, idempotency_key, part, operations: parts[part] }) as { ok?: boolean; digest?: string; error?: AiwsError }\n if (!held || held.ok === false || typeof held.digest !== 'string') {\n const error = held?.error ?? { code: 'STORAGE_IO_ERROR', retryable: true, detail: 'doc.stage returned no digest' }\n return { status: 'rejected', code: error.code, retryable: error.retryable, detail: error.detail, ...(error.sub_code ? { sub_code: error.sub_code } : {}), errors: [error] } as T\n }\n staged.push(held.digest)\n }\n options.onPart?.(parts.length, parts.length)\n const result = await call(method, { ...request, staged, operations: parts[parts.length - 1] }) as { status?: string; sub_code?: string }\n // the parts expired (or another send of this key consumed them) between staging and the commit: once more\n if (attempt === 0 && result?.status === 'rejected' && result.sub_code === 'STAGED_PARTS_MISSING') continue\n return result as T\n }\n}\n\n/**\n * kRPC client of the AI Workspace service (`/kapi/aiworkspace`). Every method takes the business result out of\n * `result` and throws `AiwsFailure` on `{ ok: false }`; commits return the three-state result as it is.\n * Stable methods: see `src/frame/aiworkspace/README.md` (Protocol, method levels).\n */\nexport class AiWorkspaceClient {\n constructor(private rpcClient: kRPCClient) {}\n\n async call<T = Record<string, unknown>>(method: string, params: Record<string, unknown>): Promise<T> {\n const raw = await this.rpcClient.call<AiwsResult<T>, Record<string, unknown>>(method, params)\n if (raw && typeof raw === 'object' && (raw as { ok?: unknown }).ok === false) throw new AiwsFailure((raw as { error: AiwsError }).error)\n return raw as T\n }\n\n // ---- workspace\n /** A new Workspace; `name` (unique among the caller's, fixed) answers `NAME_CONFLICT` when the caller already uses it. */\n create(title: string, opts: { workspace_id?: string; name?: string } = {}) {\n return this.call<{ workspace_id: string; epoch: string; head_seq: number; title: string; name?: string }>('ws.create', { title, ...opts })\n }\n /** The caller's Workspace named `name`, created (titled `title`, else the name) when it has none. */\n ensure(name: string, title?: string) {\n return this.call<{ workspace_id: string; epoch: string; head_seq: number; title: string; name: string; created: boolean }>('ws.ensure', { name, ...(title === undefined ? {} : { title }) })\n }\n /** The service clock (unix ms): calibrate against half the round trip. */\n time() { return this.call<{ server_ms: number }>('ws.time', {}) }\n list() { return this.call('ws.list', {}) }\n info(workspace_id: string) { return this.call('ws.get_info', { workspace_id }) }\n getUserState(workspace_id: string) { return this.call('ws.get_user_state', { workspace_id }) }\n setUserState(workspace_id: string, entries: Record<string, unknown>, expect?: Record<string, number>) {\n return this.call('ws.set_user_state', { workspace_id, entries, ...(expect ? { expect } : {}) })\n }\n\n // ---- document\n resolve(workspace_id: string, reference: AiwsReference | Record<string, unknown>) { return this.call('doc.resolve', { workspace_id, reference }) }\n resolvePath(workspace_id: string, path: string) { return this.call('doc.resolve', { workspace_id, path }) }\n /** The native content (`target`: a path or an entity id, see `aiwsTarget`). */\n read(workspace_id: string, target: string, selector?: Record<string, unknown>) {\n return this.call('doc.read', { workspace_id, ...aiwsTarget(target), ...(selector ? { selector } : {}) })\n }\n readMeta(workspace_id: string, target: string) {\n return this.call<AiwsMeta>('doc.read', { workspace_id, ...aiwsTarget(target), as: 'meta' })\n }\n /** One page of the plain-text body; follow `next_cursor` (bound to `etag`) for the rest. */\n readBody(workspace_id: string, target: string, params: AiwsBodyParams = {}) {\n return this.call<AiwsBody>('doc.read', { workspace_id, ...aiwsTarget(target), as: 'body', ...params })\n }\n /** `doc.list`: the readable direct children of `at` (default `/`), in tree order. */\n listEntities(workspace_id: string, params: AiwsListParams = {}) { return this.call<AiwsListResult>('doc.list', { workspace_id, ...params }) }\n /** `doc.find`: a pre-order walk under `at` by name / title, type and schema. */\n findEntities(workspace_id: string, params: AiwsFindParams = {}) { return this.call<AiwsFindResult>('doc.find', { workspace_id, ...params }) }\n /** `doc.query { text }`: a literal (1–256 characters) in names, titles and bodies. */\n textQuery(workspace_id: string, text: string, params: AiwsTextQueryParams = {}) {\n return this.call<AiwsTextQueryResult>('doc.query', { workspace_id, text, ...params })\n }\n /** `doc.query { sql }`: one SELECT over the logical tables (`FROM \"/data/销售\"`, `\"~<entity_id>\"`, an alias of `tables`). */\n sql(workspace_id: string, sql: string, params: AiwsSqlParams = {}) {\n return this.call<AiwsSqlResult>('doc.query', { workspace_id, sql, ...params })\n }\n /** `doc.source_query`: rows of a URL table from its remote source. */\n sourceQuery(workspace_id: string, source_id: string, params: AiwsSourceQueryParams) {\n return this.call('doc.source_query', { workspace_id, source_id, ...params })\n }\n outline(workspace_id: string) { return this.call('doc.outline', { workspace_id }) }\n private raw: AiwsCall = (method, params) => this.rpcClient.call<Record<string, unknown>, Record<string, unknown>>(method, params)\n prepare(workspace_id: string, request: Record<string, unknown>) {\n return commitWithParts(this.raw, { workspace_id, ...request }, { method: 'doc.prepare' })\n }\n /** The three-state commit result (`status: accepted | conflict | rejected`), never thrown. One call per Commit\n * whatever its size (up to `AIWS_COMMIT_MAX_BYTES` / `AIWS_COMMIT_MAX_OPERATIONS`): a large one is sent in parts. */\n commit(workspace_id: string, request: Record<string, unknown>, options: Pick<AiwsCommitPartsOptions, 'partBytes' | 'onPart'> = {}) {\n return commitWithParts(this.raw, { workspace_id, ...request }, options)\n }\n getSubmission(workspace_id: string, epoch: string, idempotency_key: string) { return this.call('doc.get_submission', { workspace_id, epoch, idempotency_key }) }\n /** Changes after `after_seq` (`filter.detail: \"touched\"` for the touched entities only). */\n getChanges(workspace_id: string, epoch: string, after_seq: number, opts: { limit?: number; touchedOnly?: boolean } = {}) {\n return this.call('doc.get_changes', { workspace_id, epoch, after_seq, ...(opts.limit ? { limit: opts.limit } : {}), ...(opts.touchedOnly ? { filter: { detail: 'touched' } } : {}) })\n }\n /** Long poll until the head passes `after_seq` (or `timeout_ms`). */\n waitChanges(workspace_id: string, after_seq: number, opts: { epoch?: string; timeout_ms?: number } = {}) {\n return this.call<{ epoch: string; head_seq: number; timed_out: boolean; server_ms: number }>('doc.wait_changes', { workspace_id, after_seq, ...opts })\n }\n /** A whole-Workspace package (`.bcanvas`): `download` names it in the owner's exports bucket. */\n exportDoc(workspace_id: string, mode: 'share' | 'personal_backup', self_contained: boolean, include_notes?: boolean) {\n return this.call('doc.export', { workspace_id, mode, self_contained, ...(include_notes === undefined ? {} : { include_notes }) })\n }\n\n // ---- assets\n /** Register a FileObject as a staged asset: `{ bucket_id, key }` (the uploader's binding) or `{ obj_id }`. */\n assetImportObject(workspace_id: string, source: { bucket_id: string; key: string } | { obj_id: string }) {\n return this.call<{ object_id: string; media_type: string; size: number }>('asset.import_object', { workspace_id, ...source })\n }\n\n // ---- Block-controls (code-registered layouts such as the mind map)\n controlsList() { return this.call('control.list', {}) }\n controlsDescribe(kind: string) { return this.call('control.describe', { kind }) }\n controlsImport(workspace_id: string, params: Record<string, unknown>) { return this.call('control.import', { workspace_id, ...params }) }\n controlsExport(workspace_id: string, entity_id: string, format?: 'markdown' | 'opml') { return this.call('control.export', { workspace_id, entity_id, ...(format ? { format } : {}) }) }\n\n // ---- extension controls (README “Extension controls”; buckyos-websdk src/aiws_ext.ts drives them)\n /** Build one control's source files into the Workspace; `BUILD_FAILED` carries `data.diagnostics`. */\n extBuild(workspace_id: string, params: AiwsExtBuildParams) { return this.call<AiwsExtBuildResult>('ext.build', { workspace_id, ...params }) }\n /** The bundle of definitions (`purpose: pull` needs read only and synthesizes the source of never-built ones). */\n extExport(workspace_id: string, entity_ids: string[], purpose: 'package' | 'pull' = 'package') {\n return this.call<{ manifest: Record<string, unknown>; controls: Record<string, unknown>[]; files: { path: string; obj_id?: string; size: number; text?: string }[] }>('ext.export', { workspace_id, entity_ids, purpose })\n }\n /** Into the caller's library: a `.pikg` object or one bound into the caller's `exports` bucket (consumed), or\n * definitions of a Workspace (`from` + `package`). */\n extInstall(params: { pikg?: { obj_id: string } | { bucket_id: string; key: string }; from?: { workspace_id: string; entity_ids: string[]; templates?: AiwsTemplateExport[] }; package?: { name: string; version?: string; title?: string }; mode?: 'dev' }) {\n return this.call<{ pkg_id: string; version: string; action: string; controls: Record<string, unknown>[] }>('ext.install', params)\n }\n /** Pack definitions (and what they build on, and templates of the Workspace) as an `aiws` `.pikg` into the caller's\n * `exports` bucket (unsigned). */\n extPack(workspace_id: string, entity_ids: string[], pkg: { name: string; version?: string; title?: string }, templates?: AiwsTemplateExport[]) {\n return this.call<AiwsExtPackResult>('ext.pack', { workspace_id, entity_ids, package: pkg, ...(templates ? { templates } : {}) })\n }\n /** Rebuild imported definitions from the caller's library (same Zone; across Zones `ext.build { provenance, upgrade }`):\n * `EXT_LOCAL_CHANGES` when the snapshot was built locally since, unless `force`. */\n extUpgrade(params: AiwsExtUpgradeParams) { return this.call<AiwsExtUpgradeResult>('ext.upgrade', { ...params }) }\n /** Chosen Surfaces as a template snapshot: the manifest item, the definitions it needs and the files (base64) of\n * `templates/<id>/`. */\n extExportTemplate(params: { workspace_id: string } & AiwsTemplateExport) {\n return this.call<{ template: AiwsTemplateItem; controls: Record<string, unknown>[]; files: { path: string; base64: string }[] }>('ext.export_template', { ...params })\n }\n /** A new Workspace from a template of the caller's library (installing a template never creates one). */\n extCreateFromTemplate(params: { pkg_id: string; template_id: string; title?: string; params?: Record<string, string | number | boolean> }) {\n return this.call<{ workspace_id: string }>('ext.create_from_template', params)\n }\n extListLibrary() { return this.call<{ packages: AiwsLibraryPackage[] }>('ext.list_library', {}) }\n extUninstall(pkg_id: string) { return this.call('ext.uninstall', { pkg_id }) }\n /** A library package's controls with their bytes (base64): what a client relays into a Workspace of another Zone. */\n extLibraryBundle(pkg_id: string, idents?: string[]) { return this.call<{ pkg_id: string; controls: Record<string, unknown>[] }>('ext.library_bundle', { pkg_id, ...(idents ? { idents } : {}) }) }\n /** Bring library controls into a Workspace of this Zone (one Commit). */\n extImport(workspace_id: string, items: { pkg_id: string; ident: string }[], opts: { folder_id?: string } = {}) {\n return this.call<AiwsExtBuildResult>('ext.import', { workspace_id, items, ...opts })\n }\n\n // ---- runs (M3 executor protocol)\n runStart(workspace_id: string, program: string, params: Record<string, unknown>, idempotency_key: string) {\n return this.call('proc.start', { workspace_id, program, params, idempotency_key })\n }\n runGet(workspace_id: string, run_id: string) { return this.call('proc.get', { workspace_id, run_id }) }\n runList(workspace_id: string, wish_id?: string, limit?: number) {\n return this.call('proc.list', { workspace_id, ...(wish_id ? { wish_id } : {}), ...(limit ? { limit } : {}) })\n }\n runClaim(workspace_id: string, run_id: string, claim_token: string, executor?: Record<string, unknown>) {\n return this.call<{ run_id: string; attempt: number; run_token: string; lease_until: string; lease_ms: number }>('proc.claim', { workspace_id, run_id, claim_token, ...(executor ? { executor } : {}) })\n }\n runHeartbeat(workspace_id: string, run_id: string, attempt: number, progress?: Record<string, unknown>) {\n return this.call('proc.heartbeat', { workspace_id, run_id, attempt, ...(progress ? { progress } : {}) })\n }\n runReport(workspace_id: string, report: AiwsRunReport) { return this.call('proc.report', { workspace_id, ...report }) }\n /** Take back what the run wrote: only the record that is current for its stage. When the outcome was changed since,\n * nothing is written and the answer is `status: \"needs_confirm\"` with what would be `lost`; again with `confirm`. */\n runRollback(workspace_id: string, run_id: string, opts: { confirm?: boolean; session_id?: string } = {}) {\n return this.call('proc.rollback', { workspace_id, run_id, ...(opts.confirm ? { confirm: true } : {}), ...(opts.session_id ? { session_id: opts.session_id } : {}) })\n }\n runCancel(workspace_id: string, run_id: string) { return this.call('proc.cancel', { workspace_id, run_id }) }\n}\n","/* Repeating events of the standard calendar table (`buckyos.calendar@1`, buckyos aiworkspace control mechanism TODO\n * G10, Q4): the iCalendar RRULE subset a mainstream calendar lets a user pick — every day / weekday / week on given\n * days / month on a day or the n-th (last) weekday / year, an interval, an end date or a count — parsed, written,\n * described and expanded here. The calendar control and the Agent commands expand with this one module; the core\n * checks the same subset (src/frame/aiworkspace/core/src/standard.rs). Anything outside it is an error naming the part,\n * never silently simplified: such rules live in `ext.rule_text` with the occurrences an Agent writes. */\n\nexport type Freq = 'DAILY' | 'WEEKLY' | 'MONTHLY' | 'YEARLY'\n/** Weekdays as RRULE writes them; index 0 is Monday. */\nexport const WEEKDAYS = ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'] as const\nexport type Weekday = (typeof WEEKDAYS)[number]\n\nexport interface ByDay { weekday: number; ordinal?: number }\n\nexport interface RRule {\n freq: Freq\n interval: number\n count?: number\n /** `YYYY-MM-DD` (a date) or an ISO UTC instant. */\n until?: string\n byDay?: ByDay[]\n byMonthDay?: number[]\n byMonth?: number[]\n bySetPos?: number\n /** Week start, 0 = Monday (the default). */\n wkst: number\n}\n\nexport class RRuleError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'RRuleError'\n }\n}\n\nconst FREQS: Freq[] = ['DAILY', 'WEEKLY', 'MONTHLY', 'YEARLY']\nconst MAX_COUNT = 1000\nconst MAX_INTERVAL = 999\n\nfunction intIn(part: string, value: string, lo: number, hi: number, zero = false): number {\n if (!/^[+-]?\\d{1,3}$/.test(value)) throw new RRuleError(`${part}: ${value} is not a number`)\n const n = Number(value)\n if (n < lo || n > hi || (!zero && n === 0)) throw new RRuleError(`${part}: ${value} is out of range`)\n return n\n}\n\nfunction list(part: string, value: string, max: number): string[] {\n const items = value.split(',')\n if (items.length === 0 || items.length > max || items.some((x) => x === '')) throw new RRuleError(`${part}: at most ${max} comma-separated values`)\n return items\n}\n\nfunction untilOf(value: string): string {\n let m = /^(\\d{4})(\\d{2})(\\d{2})$/.exec(value)\n if (m) {\n const date = `${m[1]}-${m[2]}-${m[3]}`\n if (!isDate(date)) throw new RRuleError(`UNTIL: ${value} is not a date`)\n return date\n }\n m = /^(\\d{4})(\\d{2})(\\d{2})T(\\d{2})(\\d{2})(\\d{2})Z$/.exec(value)\n if (m) {\n const ms = Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6])\n if (!isDate(`${m[1]}-${m[2]}-${m[3]}`) || +m[4] > 23 || +m[5] > 59 || +m[6] > 59) throw new RRuleError(`UNTIL: ${value} is not a UTC time`)\n return new Date(ms).toISOString()\n }\n throw new RRuleError(`UNTIL: ${value} must be YYYYMMDD or YYYYMMDDTHHMMSSZ`)\n}\n\n/** Parse a rule of the subset (an optional `RRULE:` prefix is accepted). Throws `RRuleError` naming the part. */\nexport function parseRRule(text: string): RRule {\n const body = text.startsWith('RRULE:') ? text.slice(6) : text\n if (body.trim() === '') throw new RRuleError('empty rule')\n const seen = new Set<string>()\n const raw: Record<string, string> = {}\n for (const part of body.split(';')) {\n const eq = part.indexOf('=')\n if (eq <= 0) throw new RRuleError(`${part || '(empty)'}: expected NAME=VALUE`)\n const name = part.slice(0, eq)\n const value = part.slice(eq + 1)\n if (name !== name.toUpperCase() || value !== value.toUpperCase()) throw new RRuleError(`${part}: write the rule in upper case`)\n if (seen.has(name)) throw new RRuleError(`${name}: given twice`)\n seen.add(name)\n if (!['FREQ', 'INTERVAL', 'COUNT', 'UNTIL', 'BYDAY', 'BYMONTHDAY', 'BYMONTH', 'BYSETPOS', 'WKST'].includes(name)) {\n throw new RRuleError(`${name}: not supported (supported: FREQ, INTERVAL, COUNT, UNTIL, BYDAY, BYMONTHDAY, BYMONTH, BYSETPOS, WKST)`)\n }\n if (value === '') throw new RRuleError(`${name}: empty value`)\n raw[name] = value\n }\n if (!raw.FREQ) throw new RRuleError('FREQ is required')\n if (!FREQS.includes(raw.FREQ as Freq)) throw new RRuleError(`FREQ: ${raw.FREQ} is not supported (DAILY, WEEKLY, MONTHLY, YEARLY)`)\n const freq = raw.FREQ as Freq\n const rule: RRule = { freq, interval: 1, wkst: 0 }\n if (raw.INTERVAL !== undefined) rule.interval = intIn('INTERVAL', raw.INTERVAL, 1, MAX_INTERVAL)\n if (raw.COUNT !== undefined && raw.UNTIL !== undefined) throw new RRuleError('COUNT and UNTIL cannot both be given')\n if (raw.COUNT !== undefined) rule.count = intIn('COUNT', raw.COUNT, 1, MAX_COUNT)\n if (raw.UNTIL !== undefined) rule.until = untilOf(raw.UNTIL)\n if (raw.BYDAY !== undefined) {\n rule.byDay = list('BYDAY', raw.BYDAY, 7).map((item) => {\n const m = /^([+-]?\\d)?(MO|TU|WE|TH|FR|SA|SU)$/.exec(item)\n if (!m) throw new RRuleError(`BYDAY: ${item} is not a weekday`)\n const weekday = WEEKDAYS.indexOf(m[2] as Weekday)\n if (m[1] === undefined) return { weekday }\n if (freq !== 'MONTHLY' && freq !== 'YEARLY') throw new RRuleError(`BYDAY: ${item}: an ordinal needs FREQ=MONTHLY or YEARLY`)\n return { weekday, ordinal: intIn('BYDAY', m[1], -5, 5) }\n })\n const keys = rule.byDay.map((d) => `${d.ordinal ?? ''}${d.weekday}`)\n if (new Set(keys).size !== keys.length) throw new RRuleError('BYDAY: repeated day')\n }\n if (raw.BYMONTHDAY !== undefined) {\n if (freq !== 'MONTHLY' && freq !== 'YEARLY') throw new RRuleError('BYMONTHDAY needs FREQ=MONTHLY or YEARLY')\n rule.byMonthDay = list('BYMONTHDAY', raw.BYMONTHDAY, 31).map((v) => {\n const n = intIn('BYMONTHDAY', v, -1, 31)\n return n\n })\n if (new Set(rule.byMonthDay).size !== rule.byMonthDay.length) throw new RRuleError('BYMONTHDAY: repeated day')\n }\n if (raw.BYMONTH !== undefined) {\n if (freq !== 'YEARLY') throw new RRuleError('BYMONTH needs FREQ=YEARLY')\n rule.byMonth = list('BYMONTH', raw.BYMONTH, 12).map((v) => intIn('BYMONTH', v, 1, 12))\n if (new Set(rule.byMonth).size !== rule.byMonth.length) throw new RRuleError('BYMONTH: repeated month')\n }\n if (raw.BYSETPOS !== undefined) {\n if (freq !== 'MONTHLY' || !rule.byDay) throw new RRuleError('BYSETPOS needs FREQ=MONTHLY and BYDAY')\n rule.bySetPos = intIn('BYSETPOS', raw.BYSETPOS, -5, 5)\n }\n if (raw.WKST !== undefined) {\n const w = WEEKDAYS.indexOf(raw.WKST as Weekday)\n if (w < 0) throw new RRuleError(`WKST: ${raw.WKST} is not a weekday`)\n rule.wkst = w\n }\n return rule\n}\n\n/** The rule as RRULE text, parts in a fixed order. */\nexport function formatRRule(rule: RRule): string {\n const parts = [`FREQ=${rule.freq}`]\n if (rule.interval > 1) parts.push(`INTERVAL=${rule.interval}`)\n if (rule.byMonth?.length) parts.push(`BYMONTH=${rule.byMonth.join(',')}`)\n if (rule.byMonthDay?.length) parts.push(`BYMONTHDAY=${rule.byMonthDay.join(',')}`)\n if (rule.byDay?.length) parts.push(`BYDAY=${rule.byDay.map((d) => `${d.ordinal ?? ''}${WEEKDAYS[d.weekday]}`).join(',')}`)\n if (rule.bySetPos !== undefined) parts.push(`BYSETPOS=${rule.bySetPos}`)\n if (rule.count !== undefined) parts.push(`COUNT=${rule.count}`)\n if (rule.until !== undefined) parts.push(`UNTIL=${rule.until.length === 10 ? rule.until.replace(/-/g, '') : rule.until.replace(/[-:]/g, '').replace(/\\.\\d{3}/, '')}`)\n if (rule.wkst !== 0) parts.push(`WKST=${WEEKDAYS[rule.wkst]}`)\n return parts.join(';')\n}\n\n// ---- dates (days since 1970-01-01, proleptic Gregorian, no time zone)\n\nexport function isDate(s: string): boolean {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(s)\n if (!m) return false\n const y = +m[1], mo = +m[2], d = +m[3]\n return y >= 1 && mo >= 1 && mo <= 12 && d >= 1 && d <= daysInMonth(y, mo)\n}\nexport const isLeap = (y: number) => (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0\nexport function daysInMonth(y: number, m: number): number {\n return [31, isLeap(y) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1]\n}\nexport const dayNumber = (y: number, m: number, d: number) => Math.floor(Date.UTC(y, m - 1, d) / 86_400_000)\nexport function dayOf(date: string): number {\n return dayNumber(+date.slice(0, 4), +date.slice(5, 7), +date.slice(8, 10))\n}\nexport function dateOf(day: number): string {\n return new Date(day * 86_400_000).toISOString().slice(0, 10)\n}\nexport function ymdOf(day: number): { y: number; m: number; d: number } {\n const t = new Date(day * 86_400_000)\n return { y: t.getUTCFullYear(), m: t.getUTCMonth() + 1, d: t.getUTCDate() }\n}\n/** Weekday of a day number, 0 = Monday. */\nexport const weekdayOf = (day: number) => (((day + 3) % 7) + 7) % 7\n\n// ---- time zones (Intl only)\n\nconst formatters = new Map<string, Intl.DateTimeFormat>()\nfunction formatter(tz: string): Intl.DateTimeFormat {\n let f = formatters.get(tz)\n if (!f) {\n f = new Intl.DateTimeFormat('en-US', { timeZone: tz, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' })\n formatters.set(tz, f)\n }\n return f\n}\n\n/** Is `tz` a time zone this runtime knows? */\nexport function isTimeZone(tz: string): boolean {\n try {\n formatter(tz)\n return true\n } catch {\n return false\n }\n}\n\n/** The wall clock of `ms` in `tz`. */\nexport function zonedParts(ms: number, tz: string): { y: number; m: number; d: number; h: number; mi: number; s: number } {\n const parts: Record<string, number> = {}\n for (const p of formatter(tz).formatToParts(new Date(ms))) if (p.type !== 'literal') parts[p.type] = Number(p.value)\n return { y: parts.year, m: parts.month, d: parts.day, h: parts.hour === 24 ? 0 : parts.hour, mi: parts.minute, s: parts.second }\n}\n\nfunction offsetMs(ms: number, tz: string): number {\n const p = zonedParts(ms, tz)\n return Date.UTC(p.y, p.m - 1, p.d, p.h, p.mi, p.s) - Math.floor(ms / 1000) * 1000\n}\n\n/** The instant of a wall clock in `tz` (a time skipped by a clock change moves forward by the change). */\nexport function zonedToUtc(day: number, minuteOfDay: number, secondOfMinute: number, tz: string): number {\n const local = day * 86_400_000 + minuteOfDay * 60_000 + secondOfMinute * 1000\n const first = local - offsetMs(local, tz)\n const second = local - offsetMs(first, tz)\n return second\n}\n\n/** The local date (day number) of an instant in `tz`. */\nexport function localDay(ms: number, tz: string): number {\n const p = zonedParts(ms, tz)\n return dayNumber(p.y, p.m, p.d)\n}\n\n// ---- expansion\n\n/** Where a series starts: an all-day date, or an instant with the zone it repeats in. */\nexport type SeriesStart = { kind: 'date'; date: string } | { kind: 'datetime'; utc: string; tz: string }\n\nexport interface Occurrence {\n /** The occurrence's identity within its series: its original start as the event writes it (a date, or an ISO UTC instant). */\n original: string\n /** All-day: the date. */\n date?: string\n /** Timed: the instant (ms). */\n startMs?: number\n}\n\nexport interface ExpandOptions {\n /** Originals excluded from the series (`ext.exdate`). */\n exdate?: readonly string[]\n /** Length of one occurrence (timed: ms, all-day: days − 1), so one that started before the window but overlaps it is kept. */\n durationMs?: number\n durationDays?: number\n /** The viewer's zone: all-day occurrences are dates on the viewer's calendar. Default UTC. */\n viewerTz?: string\n /** At most this many occurrences (default 2000). */\n limit?: number\n}\n\nconst MAX_PERIODS = 200_000\n\n/** Candidate days of one period (sorted), before the start / COUNT / UNTIL filters. */\nfunction candidates(rule: RRule, period: number, startDay: number): number[] {\n const s = ymdOf(startDay)\n const out: number[] = []\n const byDayAll = (day0: number, len: number, wanted: ByDay[]) => {\n for (let i = 0; i < len; i++) if (wanted.some((w) => w.ordinal === undefined && w.weekday === weekdayOf(day0 + i))) out.push(day0 + i)\n }\n const nth = (day0: number, len: number, w: ByDay) => {\n const days: number[] = []\n for (let i = 0; i < len; i++) if (weekdayOf(day0 + i) === w.weekday) days.push(day0 + i)\n const k = w.ordinal! > 0 ? w.ordinal! - 1 : days.length + w.ordinal!\n if (k >= 0 && k < days.length) out.push(days[k])\n }\n const monthDays = (y: number, m: number, list: number[]) => {\n const n = daysInMonth(y, m)\n for (const d of list) {\n const day = d > 0 ? d : n + d + 1\n if (day >= 1 && day <= n) out.push(dayNumber(y, m, day))\n }\n }\n switch (rule.freq) {\n case 'DAILY': {\n const day = startDay + period * rule.interval\n const { m, d } = ymdOf(day)\n if (rule.byMonth && !rule.byMonth.includes(m)) break\n if (rule.byMonthDay && !rule.byMonthDay.some((x) => (x > 0 ? x === d : daysInMonth(ymdOf(day).y, m) + x + 1 === d))) break\n if (rule.byDay && !rule.byDay.some((w) => w.weekday === weekdayOf(day))) break\n out.push(day)\n break\n }\n case 'WEEKLY': {\n const weekStart = startDay - ((weekdayOf(startDay) - rule.wkst + 7) % 7) + period * rule.interval * 7\n const wanted = rule.byDay ?? [{ weekday: weekdayOf(startDay) }]\n byDayAll(weekStart, 7, wanted)\n if (rule.byMonth) return out.filter((d) => rule.byMonth!.includes(ymdOf(d).m)).sort((a, b) => a - b)\n break\n }\n case 'MONTHLY': {\n const index = s.y * 12 + (s.m - 1) + period * rule.interval\n const y = Math.floor(index / 12), m = (index % 12) + 1\n const day0 = dayNumber(y, m, 1), len = daysInMonth(y, m)\n if (rule.byMonthDay) {\n monthDays(y, m, rule.byMonthDay)\n if (rule.byDay) {\n const keep = out.filter((d) => rule.byDay!.some((w) => w.weekday === weekdayOf(d)))\n out.length = 0\n out.push(...keep)\n }\n } else if (rule.byDay) {\n byDayAll(day0, len, rule.byDay)\n for (const w of rule.byDay) if (w.ordinal !== undefined) nth(day0, len, w)\n } else if (s.d <= len) out.push(dayNumber(y, m, s.d))\n break\n }\n case 'YEARLY': {\n const y = s.y + period * rule.interval\n if (rule.byDay && !rule.byMonth && !rule.byMonthDay) {\n const day0 = dayNumber(y, 1, 1), len = isLeap(y) ? 366 : 365\n byDayAll(day0, len, rule.byDay)\n for (const w of rule.byDay) if (w.ordinal !== undefined) nth(day0, len, w)\n break\n }\n const months = rule.byMonth ?? [s.m]\n for (const m of months) {\n if (rule.byMonthDay) monthDays(y, m, rule.byMonthDay)\n else if (rule.byDay) {\n const day0 = dayNumber(y, m, 1), len = daysInMonth(y, m)\n byDayAll(day0, len, rule.byDay)\n for (const w of rule.byDay) if (w.ordinal !== undefined) nth(day0, len, w)\n } else if (s.d <= daysInMonth(y, m)) out.push(dayNumber(y, m, s.d))\n }\n if (rule.byMonthDay && rule.byDay) {\n const keep = out.filter((d) => rule.byDay!.some((w) => w.weekday === weekdayOf(d)))\n out.length = 0\n out.push(...keep)\n }\n break\n }\n }\n const sorted = [...new Set(out)].sort((a, b) => a - b)\n if (rule.bySetPos !== undefined) {\n const k = rule.bySetPos > 0 ? rule.bySetPos - 1 : sorted.length + rule.bySetPos\n return k >= 0 && k < sorted.length ? [sorted[k]] : []\n }\n return sorted\n}\n\n/** The first day of period `p` (candidates of the period never fall before it). */\nfunction periodStart(rule: RRule, p: number, startDay: number): number {\n const s = ymdOf(startDay)\n switch (rule.freq) {\n case 'DAILY': return startDay + p * rule.interval\n case 'WEEKLY': return startDay - ((weekdayOf(startDay) - rule.wkst + 7) % 7) + p * rule.interval * 7\n case 'MONTHLY': {\n const index = s.y * 12 + (s.m - 1) + p * rule.interval\n return dayNumber(Math.floor(index / 12), (index % 12) + 1, 1)\n }\n case 'YEARLY': return dayNumber(s.y + p * rule.interval, 1, 1)\n }\n}\n\n/** The last period whose days all fall before `day` (−1 when none): what may be skipped when nothing is counted. */\nfunction periodsBefore(rule: RRule, startDay: number, day: number): number {\n const s = ymdOf(startDay)\n const t = ymdOf(day)\n let p: number\n switch (rule.freq) {\n case 'DAILY': p = Math.floor((day - startDay) / rule.interval); break\n case 'WEEKLY': p = Math.floor((day - periodStart(rule, 0, startDay)) / (7 * rule.interval)); break\n case 'MONTHLY': p = Math.floor((t.y * 12 + t.m - (s.y * 12 + s.m)) / rule.interval); break\n case 'YEARLY': p = Math.floor((t.y - s.y) / rule.interval); break\n }\n return Math.max(-1, p - 1)\n}\n\n/** The occurrences of a series overlapping the window `[fromMs, toMs)`, in order. DTSTART is always the first\n * occurrence (as mainstream calendars show it), counted by COUNT. Excluded originals (EXDATE) are left out but still\n * counted, as RFC 5545 says. */\nexport function expandSeries(rule: RRule, start: SeriesStart, window: { fromMs: number; toMs: number }, opts: ExpandOptions = {}): Occurrence[] {\n const limit = opts.limit ?? 2000\n const excluded = new Set(opts.exdate ?? [])\n const out: Occurrence[] = []\n let startDay: number\n let minute = 0, second = 0\n let tz = 'UTC'\n let fromDay: number, toDay: number\n const viewerTz = opts.viewerTz ?? 'UTC'\n if (start.kind === 'date') {\n startDay = dayOf(start.date)\n fromDay = localDay(window.fromMs, viewerTz) - (opts.durationDays ?? 0)\n toDay = localDay(window.toMs - 1, viewerTz)\n } else {\n tz = start.tz\n const ms = Date.parse(start.utc)\n const p = zonedParts(ms, tz)\n startDay = dayNumber(p.y, p.m, p.d)\n minute = p.h * 60 + p.mi\n second = p.s\n // generous day bounds in the series' zone; the instants are compared exactly when emitted\n fromDay = localDay(window.fromMs - (opts.durationMs ?? 0), tz) - 1\n toDay = localDay(window.toMs, tz) + 1\n }\n const untilDay = rule.until?.length === 10 ? dayOf(rule.until) : undefined\n const untilMs = rule.until && rule.until.length > 10 ? Date.parse(rule.until) : undefined\n let count = 0\n /** false: the series is over. */\n const emit = (day: number): boolean => {\n if (rule.count !== undefined && count >= rule.count) return false\n if (untilDay !== undefined && day > untilDay) return false\n let occ: Occurrence\n if (start.kind === 'date') {\n if (untilMs !== undefined && day * 86_400_000 > untilMs) return false\n const date = dateOf(day)\n occ = { original: date, date }\n } else {\n const ms = zonedToUtc(day, minute, second, tz)\n if (untilMs !== undefined && ms > untilMs) return false\n occ = { original: new Date(ms).toISOString(), startMs: ms }\n }\n count += 1\n if (excluded.has(occ.original)) return true\n if (start.kind === 'date') {\n if (day >= fromDay && day <= toDay) out.push(occ)\n } else if (occ.startMs! + (opts.durationMs ?? 0) > window.fromMs && occ.startMs! < window.toMs) out.push(occ)\n return true\n }\n if (startDay > toDay || !emit(startDay)) return out\n // nothing counted: the periods wholly before the window are skipped\n let period = rule.count === undefined ? periodsBefore(rule, startDay, fromDay) + 1 : 0\n for (let guard = 0; guard < MAX_PERIODS && out.length < limit; guard++, period++) {\n if (periodStart(rule, period, startDay) > toDay) break\n for (const day of candidates(rule, period, startDay)) {\n if (day <= startDay) continue\n if (day > toDay) return out\n if (!emit(day) || out.length >= limit) return out\n }\n }\n return out\n}\n\n/** The series of an event record's values (`start` / `start_date`, `ext.tz`), or null when it does not repeat. */\nexport function seriesStartOf(values: { all_day?: unknown; start?: unknown; start_date?: unknown }, tz: string | undefined, fallbackTz = 'UTC'): SeriesStart | null {\n if (values.all_day === true) return typeof values.start_date === 'string' ? { kind: 'date', date: values.start_date } : null\n return typeof values.start === 'string' ? { kind: 'datetime', utc: values.start, tz: tz && isTimeZone(tz) ? tz : fallbackTz } : null\n}\n\n/** The original of the occurrence that starts at `ms` (timed) or on `date` (all-day): its identity in `ext.exdate` /\n * `ext.recurrence_id.original`. */\nexport function originalOf(occ: { date?: string; startMs?: number }): string {\n return occ.date ?? new Date(occ.startMs!).toISOString()\n}\n\n/** `<record_id>@<original>`: an occurrence's id, apart from where it is planned (D4 §5.5). */\nexport function occurrenceId(recordId: string, original: string): string {\n return `${recordId}@${original}`\n}\nexport function parseOccurrenceId(id: string): { recordId: string; original: string | null } {\n const at = id.indexOf('@')\n return at < 0 ? { recordId: id, original: null } : { recordId: id.slice(0, at), original: id.slice(at + 1) }\n}\n\n// ---- the choices a mainstream calendar offers, and a description\n\nexport type RecurrenceLocale = 'zh' | 'en'\n\nconst ORD_ZH: Record<number, string> = { 1: '第一个', 2: '第二个', 3: '第三个', 4: '第四个', 5: '第五个', [-1]: '最后一个', [-2]: '倒数第二个', [-3]: '倒数第三个', [-4]: '倒数第四个', [-5]: '倒数第五个' }\nconst ORD_EN: Record<number, string> = { 1: 'first', 2: 'second', 3: 'third', 4: 'fourth', 5: 'fifth', [-1]: 'last', [-2]: 'second to last', [-3]: 'third to last', [-4]: 'fourth to last', [-5]: 'fifth to last' }\nconst WD_ZH = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']\nconst WD_EN = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\nconst MONTH_EN = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']\n\nconst isWorkdays = (d?: ByDay[]) => !!d && d.length === 5 && d.every((x) => x.ordinal === undefined) && [0, 1, 2, 3, 4].every((w) => d.some((x) => x.weekday === w))\n\n/** A sentence for a rule (\"每个工作日\", \"每月最后一个周五\", \"every 2 weeks on Monday, Wednesday, 10 times\"). */\nexport function describeRRule(rule: RRule, locale: RecurrenceLocale = 'zh'): string {\n const zh = locale === 'zh'\n const n = rule.interval\n const days = (d: ByDay[]) => d.map((x) => {\n const wd = zh ? WD_ZH[x.weekday] : WD_EN[x.weekday]\n if (x.ordinal === undefined) return wd\n return zh ? `${ORD_ZH[x.ordinal]}${wd}` : `${ORD_EN[x.ordinal]} ${wd}`\n })\n const join = (xs: string[]) => (zh ? xs.join('、') : xs.length > 1 ? `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}` : xs.join(''))\n const mday = (d: number) => (zh ? (d === -1 ? '最后一天' : `${d} 日`) : d === -1 ? 'the last day' : `day ${d}`)\n let text: string\n switch (rule.freq) {\n case 'DAILY':\n text = zh ? (n === 1 ? '每天' : `每 ${n} 天`) : n === 1 ? 'every day' : `every ${n} days`\n break\n case 'WEEKLY':\n if (isWorkdays(rule.byDay) && n === 1) text = zh ? '每个工作日' : 'every weekday'\n else {\n const on = rule.byDay ? join(days(rule.byDay)) : ''\n text = zh ? `${n === 1 ? '每周' : `每 ${n} 周的`}${on}` : `${n === 1 ? 'every week' : `every ${n} weeks`}${on ? ` on ${on}` : ''}`\n }\n break\n case 'MONTHLY': {\n let on = ''\n if (rule.byMonthDay) on = join(rule.byMonthDay.map(mday))\n else if (rule.byDay && rule.bySetPos !== undefined) {\n on = isWorkdays(rule.byDay) ? (zh ? `${ORD_ZH[rule.bySetPos]}工作日` : `the ${ORD_EN[rule.bySetPos]} weekday`) : (zh ? `${ORD_ZH[rule.bySetPos]}${join(days(rule.byDay))}` : `the ${ORD_EN[rule.bySetPos]} of ${join(days(rule.byDay))}`)\n } else if (rule.byDay) on = zh ? join(days(rule.byDay)) : `the ${join(days(rule.byDay))}`\n text = zh ? `${n === 1 ? '每月' : `每 ${n} 个月的`}${on}` : `${n === 1 ? 'every month' : `every ${n} months`}${on ? ` on ${on}` : ''}`\n break\n }\n case 'YEARLY': {\n const months = rule.byMonth?.map((m) => (zh ? `${m} 月` : MONTH_EN[m - 1]))\n let on = months ? join(months) : ''\n if (rule.byMonthDay) on += zh ? join(rule.byMonthDay.map(mday)) : ` ${join(rule.byMonthDay.map((d) => (d === -1 ? 'last day' : String(d))))}`\n else if (rule.byDay) on += zh ? join(days(rule.byDay)) : ` on the ${join(days(rule.byDay))}`\n text = zh ? `${n === 1 ? '每年' : `每 ${n} 年的`}${on}` : `${n === 1 ? 'every year' : `every ${n} years`}${on.trim() ? ` in ${on.trim()}` : ''}`\n break\n }\n }\n if (rule.count !== undefined) text += zh ? `,共 ${rule.count} 次` : `, ${rule.count} times`\n if (rule.until !== undefined) text += zh ? `,到 ${rule.until.slice(0, 10)} 为止` : `, until ${rule.until.slice(0, 10)}`\n return text\n}\n\nexport interface RecurrencePreset {\n id: 'none' | 'daily' | 'weekdays' | 'weekly' | 'monthly_day' | 'monthly_nth' | 'monthly_last' | 'yearly'\n label: string\n /** null: does not repeat. */\n rrule: string | null\n}\n\n/** The choices of a mainstream calendar's \"repeat\" menu for an event starting on `date` (`YYYY-MM-DD`, local). */\nexport function recurrencePresets(date: string, locale: RecurrenceLocale = 'zh'): RecurrencePreset[] {\n const day = dayOf(date)\n const { y, m, d } = ymdOf(day)\n const wd = weekdayOf(day)\n const nth = Math.floor((d - 1) / 7) + 1\n const last = d + 7 > daysInMonth(y, m)\n const zh = locale === 'zh'\n const w = WEEKDAYS[wd]\n const out: RecurrencePreset[] = [\n { id: 'none', label: zh ? '不重复' : 'Does not repeat', rrule: null },\n { id: 'daily', label: zh ? '每天' : 'Daily', rrule: 'FREQ=DAILY' },\n { id: 'weekdays', label: zh ? '每个工作日(周一至周五)' : 'Every weekday (Monday to Friday)', rrule: 'FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR' },\n { id: 'weekly', label: zh ? `每周的${WD_ZH[wd]}` : `Weekly on ${WD_EN[wd]}`, rrule: `FREQ=WEEKLY;BYDAY=${w}` },\n { id: 'monthly_day', label: zh ? `每月 ${d} 日` : `Monthly on day ${d}`, rrule: `FREQ=MONTHLY;BYMONTHDAY=${d}` },\n ]\n if (nth <= 4) out.push({ id: 'monthly_nth', label: zh ? `每月${ORD_ZH[nth]}${WD_ZH[wd]}` : `Monthly on the ${ORD_EN[nth]} ${WD_EN[wd]}`, rrule: `FREQ=MONTHLY;BYDAY=${nth}${w}` })\n if (last) out.push({ id: 'monthly_last', label: zh ? `每月最后一个${WD_ZH[wd]}` : `Monthly on the last ${WD_EN[wd]}`, rrule: `FREQ=MONTHLY;BYDAY=-1${w}` })\n out.push({ id: 'yearly', label: zh ? `每年 ${m} 月 ${d} 日` : `Annually on ${MONTH_EN[m - 1]} ${d}`, rrule: `FREQ=YEARLY;BYMONTH=${m};BYMONTHDAY=${d}` })\n return out\n}\n","/* The standard to-do and calendar data of AI Workspace (buckyos aiworkspace control mechanism TODO G8–G11): the two\n * table schemas (`buckyos.todo@1`, `buckyos.calendar@1`, the contract is buckyos src/frame/aiworkspace/schemas/\n * standard-tables.md, checked by the core at admission), the operations that read and change them — add, complete,\n * move, reschedule one / following / all occurrences, skip, postpone — and the person's private schedule Workspace\n * (`ws.ensure { name: \"schedule\" }`, fixed table ids `todo` and `calendar`). The official controls, the Agent commands\n * and notification buttons all use these builders: one meaning per action (07). Pure functions build operations; the\n * `ScheduleClient` at the end commits them over an `AiWorkspaceClient`. */\n\nimport { AiwsFailure } from './aiworkspace_client'\nimport { dayOf, dateOf, expandSeries, formatRRule, isDate, occurrenceId, parseRRule, seriesStartOf, type Occurrence, type RRule } from './aiws_rrule'\n\nexport const TODO_SCHEMA_ID = 'buckyos.todo@1'\nexport const CALENDAR_SCHEMA_ID = 'buckyos.calendar@1'\nexport const SCHEDULE_WORKSPACE_NAME = 'schedule'\nexport const SCHEDULE_TODO_ID = 'todo'\nexport const SCHEDULE_CALENDAR_ID = 'calendar'\nexport const SCHEDULE_SURFACE_ID = 'schedule-board'\nexport const TODO_DONE = 'done'\nexport const AIWS_PROTOCOL_VERSION = '1.2'\n\nexport type Json = null | boolean | number | string | Json[] | { [key: string]: Json }\nexport type Op = Record<string, Json>\nexport type ScheduleLocale = 'zh' | 'en'\n\nexport interface FieldDef {\n field_id: string\n name: string\n type: string\n required?: boolean\n nullable?: boolean\n options?: { option_id: string; label: string }[]\n}\n\nconst LABELS: Record<ScheduleLocale, Record<string, string>> = {\n zh: {\n title: '标题', status: '状态', due: '截止', order: '顺序', done_at: '完成时间', ext: '扩展',\n todo: '待办', doing: '进行中', done: '已完成',\n all_day: '全天', start: '开始', end: '结束', start_date: '开始日期', end_date: '结束日期',\n confirmed: '已确认', tentative: '暂定', cancelled: '已取消',\n todo_table: '待办', calendar_table: '日程', workspace: '我的日程', board: '日程',\n },\n en: {\n title: 'Title', status: 'Status', due: 'Due', order: 'Order', done_at: 'Completed', ext: 'Extension',\n todo: 'To do', doing: 'In progress', done: 'Done',\n all_day: 'All day', start: 'Start', end: 'End', start_date: 'Start date', end_date: 'End date',\n confirmed: 'Confirmed', tentative: 'Tentative', cancelled: 'Cancelled',\n todo_table: 'To-do', calendar_table: 'Calendar', workspace: 'My schedule', board: 'Schedule',\n },\n}\n\nexport function scheduleLabel(locale: ScheduleLocale, key: string): string {\n return LABELS[locale][key] ?? LABELS.en[key] ?? key\n}\n\n/** The standard fields of a to-do table (`buckyos.todo@1`). */\nexport function todoFields(locale: ScheduleLocale = 'zh'): FieldDef[] {\n const l = (k: string) => scheduleLabel(locale, k)\n return [\n { field_id: 'title', name: l('title'), type: 'text', required: true },\n { field_id: 'status', name: l('status'), type: 'select', required: true, options: ['todo', 'doing', 'done'].map((id) => ({ option_id: id, label: l(id) })) },\n { field_id: 'due', name: l('due'), type: 'date', nullable: true },\n { field_id: 'order', name: l('order'), type: 'text', nullable: true },\n { field_id: 'done_at', name: l('done_at'), type: 'datetime', nullable: true },\n { field_id: 'ext', name: l('ext'), type: 'json', nullable: true },\n ]\n}\n\n/** The standard fields of a calendar table (`buckyos.calendar@1`). */\nexport function calendarFields(locale: ScheduleLocale = 'zh'): FieldDef[] {\n const l = (k: string) => scheduleLabel(locale, k)\n return [\n { field_id: 'title', name: l('title'), type: 'text', required: true },\n { field_id: 'all_day', name: l('all_day'), type: 'boolean', nullable: true },\n { field_id: 'start', name: l('start'), type: 'datetime', nullable: true },\n { field_id: 'end', name: l('end'), type: 'datetime', nullable: true },\n { field_id: 'start_date', name: l('start_date'), type: 'date', nullable: true },\n { field_id: 'end_date', name: l('end_date'), type: 'date', nullable: true },\n { field_id: 'status', name: l('status'), type: 'select', nullable: true, options: ['confirmed', 'tentative', 'cancelled'].map((id) => ({ option_id: id, label: l(id) })) },\n { field_id: 'ext', name: l('ext'), type: 'json', nullable: true },\n ]\n}\n\n/** `entity.create` of a standard table. */\nexport function standardTableOp(kind: 'todo' | 'calendar', args: { entity_id: string; parent_id: string; order_key: string; name?: string; locale?: ScheduleLocale }): Op {\n const locale = args.locale ?? 'zh'\n return {\n op: 'entity.create', entity_id: args.entity_id, type_id: 'buckyos.table-source', parent_id: args.parent_id, order_key: args.order_key,\n schema_id: kind === 'todo' ? TODO_SCHEMA_ID : CALENDAR_SCHEMA_ID,\n name: args.name ?? scheduleLabel(locale, kind === 'todo' ? 'todo_table' : 'calendar_table'),\n payload: { title_field_id: 'title', fields: (kind === 'todo' ? todoFields(locale) : calendarFields(locale)) as unknown as Json },\n }\n}\n\n// ---- order keys (the core's `order_key_between`, core/src/order_key.rs: base-36, never ending in 0, ≤ 64)\n\nconst DIGITS = '0123456789abcdefghijklmnopqrstuvwxyz'\nconst MAX_KEY_LEN = 64\nconst APPEND_WIDTH = 8\n\nexport function isOrderKey(k: unknown): k is string {\n return typeof k === 'string' && k.length > 0 && k.length <= MAX_KEY_LEN && /^[0-9a-z]+$/.test(k) && !k.endsWith('0')\n}\n\nfunction midpoint(a: string, b: string | null): string {\n if (b !== null) {\n let n = 0\n while (n < b.length && (a[n] ?? '0') === b[n]) n++\n if (n > 0) return b.slice(0, n) + midpoint(a.length > n ? a.slice(n) : '', b.slice(n))\n }\n const da = a.length ? DIGITS.indexOf(a[0]) : 0\n const db = b !== null ? DIGITS.indexOf(b[0]) : DIGITS.length\n if (db - da > 1) return DIGITS[Math.floor((da + db + 1) / 2)]\n if (b !== null && b.length > 1) return b[0]\n return DIGITS[da] + midpoint(a.length > 1 ? a.slice(1) : '', null)\n}\n\nfunction after(a: string): string {\n const out = a.padEnd(Math.max(a.length, APPEND_WIDTH), '0').split('')\n let i = out.length - 1\n while (i >= 0 && out[i] === 'z') i--\n if (i >= 0) {\n out[i] = DIGITS[DIGITS.indexOf(out[i]) + 1]\n for (let j = i + 1; j < out.length; j++) out[j] = '0'\n if (out[out.length - 1] === '0') out[out.length - 1] = '1'\n return out.join('')\n }\n if (out.length >= MAX_KEY_LEN) throw new Error('order key space exhausted; rebalance')\n const longer = out.join('').padEnd(Math.min(out.length + APPEND_WIDTH, MAX_KEY_LEN), '0')\n return longer.slice(0, -1) + '1'\n}\n\n/** A key strictly between `a` and `b` (null: open end), as the core computes it. */\nexport function orderKeyBetween(a?: string | null, b?: string | null): string {\n const lo = a ?? null, hi = b ?? null\n if (lo !== null && hi !== null && lo >= hi) throw new Error('orderKeyBetween requires a < b')\n const key = lo !== null && hi === null ? after(lo) : midpoint(lo ?? '', hi)\n if (!isOrderKey(key)) throw new Error('order key space exhausted; rebalance')\n return key\n}\n\n/** `count` keys spread between `a` and `b`, in order. */\nexport function orderKeysBetween(a: string | null, b: string | null, count: number): string[] {\n const out: string[] = []\n let lo = a\n for (let i = 0; i < count; i++) {\n lo = orderKeyBetween(lo, b)\n out.push(lo)\n }\n return out\n}\n\n// ---- records\n\n/** A record as `doc.read` (`table_record`) and the SQL `_record` column answer it. */\nexport interface RowLike {\n record_id: string\n rev?: number\n revs?: Record<string, number>\n values: Record<string, Json | undefined>\n /** The record's rich-text body (notes), when it has one. */\n body_ref?: { entity_id: string }\n}\n\nlet counter = 0\n/** A record id: `r` + time + a counter + randomness (lower case, ≤ 64). */\nexport function newRecordId(prefix = 'r'): string {\n counter = (counter + 1) % 1296\n const rand = Math.floor(Math.random() * 36 ** 6).toString(36).padStart(6, '0')\n return `${prefix}${Date.now().toString(36)}${counter.toString(36).padStart(2, '0')}${rand}`\n}\n\n/** `table.set_values` / `table.unset_values` of `changes` (null or undefined unsets), each cell expected at the rev the\n * row was read with — the core requires it: concurrent writers of other cells merge, the same cell conflicts. */\nexport function setValuesOps(sourceId: string, row: RowLike, changes: Record<string, Json | undefined>): Op[] {\n const set: Op[] = []\n const unset: Op[] = []\n for (const [field, value] of Object.entries(changes)) {\n const cell: Op = { record_id: row.record_id, field_id: field, expect: { rev: row.revs?.[field] ?? 0 } }\n if (value === null || value === undefined) {\n if (row.values[field] !== undefined && row.values[field] !== null) unset.push(cell)\n } else {\n set.push({ ...cell, value })\n }\n }\n const out: Op[] = []\n if (set.length) out.push({ op: 'table.set_values', source_id: sourceId, values: set })\n if (unset.length) out.push({ op: 'table.unset_values', source_id: sourceId, values: unset })\n return out\n}\n\nexport function insertRecordOp(sourceId: string, records: { record_id: string; values: Record<string, Json | undefined> }[]): Op {\n return {\n op: 'table.insert_records', source_id: sourceId,\n records: records.map((r) => ({ record_id: r.record_id, values: Object.fromEntries(Object.entries(r.values).filter(([, v]) => v !== undefined && v !== null)) as Json })),\n }\n}\n\n/** `table.delete_records` of rows as read (each expected at its record rev, as the core requires). */\nexport function deleteRecordsOp(sourceId: string, rows: RowLike[]): Op {\n return { op: 'table.delete_records', source_id: sourceId, records: rows.map((r): Json => ({ record_id: r.record_id, expect: { rev: r.rev ?? 0 } })) }\n}\n\n/** An original start as the series writes it: a date as it is, an instant as canonical UTC (`ext` keeps what was\n * written, any RFC 3339 offset). */\nexport function canonicalOriginal(x: string): string {\n if (isDate(x)) return x\n const t = Date.parse(x)\n return Number.isFinite(t) ? new Date(t).toISOString() : x\n}\nconst originals = (v: Json | undefined): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string').map(canonicalOriginal) : [])\n\nconst extOf = (row: RowLike | undefined): Record<string, Json> => {\n const e = row?.values.ext\n return e && typeof e === 'object' && !Array.isArray(e) ? { ...(e as Record<string, Json>) } : {}\n}\n\n// ---- to-do\n\nexport interface TodoValues {\n title?: string\n status?: string\n due?: string | null\n order?: string | null\n done_at?: string | null\n ext?: Record<string, Json> | null\n}\n\n/** A to-do as the controls read it; still the record it came from (`values`, `revs`), so the operations take it. */\nexport interface TodoItem extends RowLike {\n title: string\n status: string\n due: string | null\n order: string | null\n done: boolean\n done_at: string | null\n ext: Record<string, Json>\n}\n\nexport function todoItem(row: RowLike): TodoItem {\n const v = row.values\n const status = typeof v.status === 'string' ? v.status : 'todo'\n return {\n record_id: row.record_id, rev: row.rev, revs: row.revs, values: row.values,\n title: typeof v.title === 'string' ? v.title : '', status,\n due: typeof v.due === 'string' ? v.due : null, order: isOrderKey(v.order) ? v.order : null,\n done: status === TODO_DONE, done_at: typeof v.done_at === 'string' ? v.done_at : null, ext: extOf(row),\n }\n}\n\n/** To-do items in list order: by `order`, items without one last (by id, stable). */\nexport function sortTodos<T extends { order: string | null; record_id: string }>(items: T[]): T[] {\n return [...items].sort((a, b) => (a.order === b.order ? a.record_id.localeCompare(b.record_id) : a.order === null ? 1 : b.order === null ? -1 : a.order < b.order ? -1 : 1))\n}\n\n/** Add a to-do: `order` between its neighbours (`after` / `before` keys, default: at the end of `items`). */\nexport function todoAddOps(sourceId: string, input: TodoValues & { title: string; record_id?: string }, place: { after?: string | null; before?: string | null; items?: { order: string | null }[] } = {}): { record_id: string; ops: Op[]; order: string } {\n const record_id = input.record_id ?? newRecordId('t')\n let order = input.order ?? null\n if (!order) {\n if (place.after !== undefined || place.before !== undefined) order = orderKeyBetween(place.after ?? null, place.before ?? null)\n else {\n const last = (place.items ?? []).map((i) => i.order).filter(isOrderKey).sort().pop() ?? null\n order = orderKeyBetween(last, null)\n }\n }\n const status = input.status ?? 'todo'\n const values: Record<string, Json | undefined> = {\n title: input.title, status, order,\n due: input.due ?? undefined, ext: input.ext && Object.keys(input.ext).length ? input.ext : undefined,\n done_at: status === TODO_DONE ? (input.done_at ?? new Date().toISOString()) : undefined,\n }\n return { record_id, order, ops: [insertRecordOp(sourceId, [{ record_id, values }])] }\n}\n\n/** Complete (or reopen) a to-do: status `done` and `done_at`, or back to `reopenStatus` (default `todo`). */\nexport function todoCompleteOps(sourceId: string, row: RowLike, done: boolean, opts: { now?: string; reopenStatus?: string } = {}): Op[] {\n if (done) return setValuesOps(sourceId, row, { status: TODO_DONE, done_at: opts.now ?? new Date().toISOString() })\n return setValuesOps(sourceId, row, { status: opts.reopenStatus ?? 'todo', done_at: null })\n}\n\n/** Move a to-do: to another status (column) and / or a new place (`order`). Completing by moving to `done` stamps\n * `done_at`, leaving it clears it. */\nexport function todoMoveOps(sourceId: string, row: RowLike, to: { status?: string; order?: string | null }, opts: { now?: string } = {}): Op[] {\n const changes: Record<string, Json | undefined> = {}\n const was = typeof row.values.status === 'string' ? row.values.status : undefined\n if (to.status !== undefined && to.status !== was) {\n changes.status = to.status\n if (to.status === TODO_DONE) changes.done_at = opts.now ?? new Date().toISOString()\n else if (was === TODO_DONE) changes.done_at = null\n }\n if (to.order !== undefined && to.order !== row.values.order) changes.order = to.order\n return Object.keys(changes).length ? setValuesOps(sourceId, row, changes) : []\n}\n\n/** Change fields of a to-do (title, due, ext …). `ext` is merged into the stored one (null removes a key). */\nexport function todoUpdateOps(sourceId: string, row: RowLike, changes: TodoValues & { ext_merge?: Record<string, Json | null> }): Op[] {\n const out: Record<string, Json | undefined> = {}\n for (const k of ['title', 'status', 'due', 'order', 'done_at'] as const) if (changes[k] !== undefined) out[k] = changes[k] as Json\n if (changes.ext !== undefined) out.ext = changes.ext && Object.keys(changes.ext).length ? changes.ext : null\n if (changes.ext_merge) {\n const ext = extOf(row)\n for (const [k, v] of Object.entries(changes.ext_merge)) if (v === null) delete ext[k]; else ext[k] = v\n out.ext = Object.keys(ext).length ? ext : null\n }\n if (out.status !== undefined && out.status !== row.values.status && out.done_at === undefined) {\n if (out.status === TODO_DONE) out.done_at = new Date().toISOString()\n else if (row.values.status === TODO_DONE) out.done_at = null\n }\n return setValuesOps(sourceId, row, out)\n}\n\n/** The order key for placing an item at `index` among `items` (sorted, the moved one excluded). */\nexport function orderAt(items: { order: string | null }[], index: number): string {\n const keys = items.map((i) => i.order)\n const before = index > 0 ? keys[index - 1] : null\n const afterKey = index < keys.length ? keys[index] : null\n if (before !== null && !isOrderKey(before)) return orderKeyBetween(null, null)\n if (afterKey !== null && isOrderKey(afterKey) && (before === null || before < afterKey)) return orderKeyBetween(before, afterKey)\n return orderKeyBetween(before, null)\n}\n\n// ---- calendar\n\nexport interface EventValues {\n title?: string\n all_day?: boolean\n start?: string | null\n end?: string | null\n start_date?: string | null\n end_date?: string | null\n status?: string | null\n ext?: Record<string, Json> | null\n}\n\n/** One shown occurrence of an event: a single event, an occurrence of a series, or the record overriding one. */\nexport interface EventOccurrence {\n /** `record_id`, or `<master>@<original>` for an occurrence of a series. */\n id: string\n /** The record holding what is shown (the master, or the override). */\n row: RowLike\n /** The series' master when this is an occurrence of a series. */\n master?: RowLike\n /** The occurrence's original start (its identity in the series). */\n original?: string\n title: string\n allDay: boolean\n /** Timed: instants (ms). */\n startMs?: number\n endMs?: number\n /** All-day: dates, end inclusive. */\n startDate?: string\n endDate?: string\n status: string | null\n ext: Record<string, Json>\n /** The record repeats (a master or an occurrence of one). */\n recurring: boolean\n /** The record overrides one occurrence of a series (`ext.recurrence_id`). */\n override: boolean\n /** Shown from `ext.occurrences` an Agent wrote (a rule the subset cannot express). */\n agentWritten: boolean\n}\n\nconst DEFAULT_EVENT_MS = 3600_000\n\nfunction rowTimes(row: RowLike): { allDay: boolean; startMs?: number; endMs?: number; startDate?: string; endDate?: string } | null {\n const v = row.values\n if (v.all_day === true) {\n if (typeof v.start_date !== 'string' || !isDate(v.start_date)) return null\n const endDate = typeof v.end_date === 'string' && isDate(v.end_date) && v.end_date >= v.start_date ? v.end_date : v.start_date\n return { allDay: true, startDate: v.start_date, endDate }\n }\n if (typeof v.start !== 'string') return null\n const startMs = Date.parse(v.start)\n if (!Number.isFinite(startMs)) return null\n const end = typeof v.end === 'string' ? Date.parse(v.end) : NaN\n return { allDay: false, startMs, endMs: Number.isFinite(end) && end >= startMs ? end : startMs + DEFAULT_EVENT_MS }\n}\n\nfunction addDays(date: string, n: number): string {\n return dateOf(dayOf(date) + n)\n}\nconst daysBetween = (a: string, b: string) => dayOf(b) - dayOf(a)\n\nfunction occurrenceOf(row: RowLike, times: NonNullable<ReturnType<typeof rowTimes>>, extra: Partial<EventOccurrence>): EventOccurrence {\n const ext = extOf(row)\n return {\n id: row.record_id, row, title: typeof row.values.title === 'string' ? row.values.title : '', allDay: times.allDay,\n startMs: times.startMs, endMs: times.endMs, startDate: times.startDate, endDate: times.endDate,\n status: typeof row.values.status === 'string' ? row.values.status : null, ext,\n recurring: false, override: false, agentWritten: false, ...extra,\n }\n}\n\n/** Does an occurrence overlap the window (all-day dates are compared on the viewer's calendar)? */\nfunction overlaps(o: { allDay: boolean; startMs?: number; endMs?: number; startDate?: string; endDate?: string }, window: { fromMs: number; toMs: number }, viewerTz: string): boolean {\n if (!o.allDay) return o.startMs! < window.toMs && Math.max(o.endMs!, o.startMs! + 1) > window.fromMs\n const from = localDate(window.fromMs, viewerTz), to = localDate(window.toMs - 1, viewerTz)\n return o.startDate! <= to && o.endDate! >= from\n}\n\n/** The date of an instant on a zone's calendar. */\nexport function localDate(ms: number, tz: string): string {\n const f = new Intl.DateTimeFormat('en-CA', { timeZone: tz, year: 'numeric', month: '2-digit', day: '2-digit' })\n return f.format(new Date(ms))\n}\n\nexport function viewerTimeZone(): string {\n try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC' } catch { return 'UTC' }\n}\n\n/** Every occurrence of the calendar's records overlapping `[fromMs, toMs)`: single events, expanded series (EXDATE\n * removed, overridden occurrences replaced by their override records), and the occurrences an Agent wrote for rules\n * outside the subset. Sorted by start. A series whose rule cannot be read shows its first occurrence only. */\nexport function calendarOccurrences(rows: RowLike[], window: { fromMs: number; toMs: number }, opts: { viewerTz?: string; limit?: number } = {}): EventOccurrence[] {\n const viewerTz = opts.viewerTz ?? viewerTimeZone()\n const out: EventOccurrence[] = []\n const overrides = new Map<string, RowLike>()\n for (const row of rows) {\n const rid = extOf(row).recurrence_id\n if (rid && typeof rid === 'object' && !Array.isArray(rid) && typeof rid.master === 'string' && typeof rid.original === 'string') overrides.set(`${rid.master}@${canonicalOriginal(rid.original)}`, row)\n }\n const byId = new Map(rows.map((r) => [r.record_id, r]))\n for (const row of rows) {\n const times = rowTimes(row)\n if (!times) continue\n const ext = extOf(row)\n const rid = ext.recurrence_id as Record<string, Json> | undefined\n if (rid && typeof rid === 'object') {\n // an override is shown in place of its occurrence (also when its master is gone: it is an event of its own then)\n const master = typeof rid.master === 'string' ? byId.get(rid.master) : undefined\n const original = typeof rid.original === 'string' ? canonicalOriginal(rid.original) : undefined\n const occ = occurrenceOf(row, times, { id: master && original ? occurrenceId(master.record_id, original) : row.record_id, master, original, recurring: Boolean(master), override: true })\n if (overlaps(occ, window, viewerTz)) out.push(occ)\n continue\n }\n const duration = times.allDay ? daysBetween(times.startDate!, times.endDate!) : times.endMs! - times.startMs!\n const shift = (o: Occurrence): EventOccurrence | null => {\n const key = `${row.record_id}@${o.original}`\n if (overrides.has(key)) return null\n if (times.allDay) return occurrenceOf(row, { allDay: true, startDate: o.date!, endDate: addDays(o.date!, duration) }, { id: key, master: row, original: o.original, recurring: true })\n return occurrenceOf(row, { allDay: false, startMs: o.startMs!, endMs: o.startMs! + duration }, { id: key, master: row, original: o.original, recurring: true })\n }\n let rule: RRule | null = null\n if (typeof ext.rrule === 'string') {\n try { rule = parseRRule(ext.rrule) } catch { rule = null }\n }\n if (rule) {\n const start = seriesStartOf(row.values, typeof ext.tz === 'string' ? ext.tz : undefined, viewerTz)\n if (!start) continue\n const exdate = originals(ext.exdate)\n const occs = expandSeries(rule, start, window, { exdate, viewerTz, durationMs: times.allDay ? undefined : duration, durationDays: times.allDay ? duration : undefined, limit: opts.limit })\n for (const o of occs) { const s = shift(o); if (s) out.push(s) }\n continue\n }\n if (Array.isArray(ext.occurrences) && ext.occurrences.length > 0) {\n const exdate = new Set(originals(ext.exdate))\n for (const raw of ext.occurrences) {\n if (typeof raw !== 'string') continue\n const x = canonicalOriginal(raw)\n if (exdate.has(x)) continue\n const o: Occurrence = times.allDay ? { original: x, date: x } : { original: x, startMs: Date.parse(x) }\n if (!times.allDay && !Number.isFinite(o.startMs)) continue\n if (times.allDay && !isDate(x)) continue\n const s = shift(o)\n if (s && overlaps(s, window, viewerTz)) out.push({ ...s, agentWritten: true })\n }\n continue\n }\n const occ = occurrenceOf(row, times, {})\n if (overlaps(occ, window, viewerTz)) out.push(occ)\n }\n return out.sort((a, b) => sortKey(a) - sortKey(b) || a.id.localeCompare(b.id))\n}\n\nconst sortKey = (o: EventOccurrence) => (o.allDay ? Date.parse(`${o.startDate}T00:00:00Z`) : o.startMs!)\n\n/** A new event: timed (`start` / `end` ISO) or all-day (`start_date` / `end_date`). */\nexport function eventAddOps(sourceId: string, input: EventValues & { title: string; record_id?: string }): { record_id: string; ops: Op[] } {\n const record_id = input.record_id ?? newRecordId('e')\n const values: Record<string, Json | undefined> = { title: input.title, status: input.status ?? undefined, ext: input.ext && Object.keys(input.ext).length ? input.ext : undefined }\n if (input.all_day) {\n values.all_day = true\n values.start_date = input.start_date ?? undefined\n values.end_date = input.end_date && input.end_date !== input.start_date ? input.end_date : undefined\n } else {\n values.start = input.start ?? undefined\n values.end = input.end ?? undefined\n }\n return { record_id, ops: [insertRecordOp(sourceId, [{ record_id, values }])] }\n}\n\n/** When an event happens: timed or all-day. */\nexport type EventTimes = { allDay: false; start: string; end: string } | { allDay: true; startDate: string; endDate: string }\n\nfunction timesChanges(times: EventTimes): Record<string, Json | undefined> {\n return times.allDay\n ? { all_day: true, start_date: times.startDate, end_date: times.endDate !== times.startDate ? times.endDate : null, start: null, end: null }\n : { all_day: null, start: times.start, end: times.end, start_date: null, end_date: null }\n}\n\n/** What an edit of one occurrence changes: its times and / or other fields. */\nexport interface EventChange {\n times?: EventTimes\n values?: Omit<EventValues, 'all_day' | 'start' | 'end' | 'start_date' | 'end_date'>\n /** Keys merged into `ext` (null removes). */\n ext_merge?: Record<string, Json | null>\n /** A new rule (`null`: stop repeating); only for `all` / `following`. */\n rrule?: string | null\n}\n\nexport type RecurrenceScope = 'one' | 'following' | 'all'\n\nexport interface CalendarContext {\n /** Every record of the calendar (or at least the series' master and its overrides). */\n rows: RowLike[]\n newRecordId?: () => string\n}\n\nfunction overridesOf(rows: RowLike[], masterId: string): RowLike[] {\n return rows.filter((r) => {\n const rid = extOf(r).recurrence_id as Record<string, Json> | undefined\n return rid && typeof rid === 'object' && rid.master === masterId\n })\n}\n\nconst isoShift = (iso: string, deltaMs: number) => new Date(Date.parse(iso) + deltaMs).toISOString()\n/** Shift an original (date or instant) by a time change. */\nfunction shiftOriginal(original: string, allDay: boolean, deltaMs: number, deltaDays: number): string {\n return allDay ? addDays(original, deltaDays) : isoShift(original, deltaMs)\n}\n\n/** A weekly / monthly rule follows its series to another day: BYDAY weekdays and BYMONTHDAY days move with it. */\nfunction shiftRule(rule: RRule, deltaDays: number): RRule {\n if (!deltaDays) return rule\n const next = { ...rule }\n if (rule.byDay && rule.byDay.every((d) => d.ordinal === undefined) && (rule.freq === 'WEEKLY' || rule.freq === 'DAILY')) {\n next.byDay = rule.byDay.map((d) => ({ weekday: (((d.weekday + deltaDays) % 7) + 7) % 7 }))\n } else if (rule.byDay && rule.freq === 'MONTHLY' && rule.byDay.length === 1 && rule.bySetPos === undefined && Math.abs(deltaDays) < 7) {\n next.byDay = [{ ...rule.byDay[0], weekday: (((rule.byDay[0].weekday + deltaDays) % 7) + 7) % 7 }]\n } else if (rule.byMonthDay && rule.byMonthDay.length === 1 && rule.byMonthDay[0] > 0) {\n const d = rule.byMonthDay[0] + deltaDays\n if (d >= 1 && d <= 28) next.byMonthDay = [d]\n }\n return next\n}\n\n/** The ops of a change of one occurrence of an event (or of a single event): `one` overrides just that occurrence\n * (“仅此一次”), `following` splits the series there (“此后全部”), `all` changes the series (“全部”), shifting its\n * start, its exclusions and its overrides by the same amount. */\nexport function eventEditOps(sourceId: string, occ: Pick<EventOccurrence, 'row' | 'master' | 'original' | 'allDay' | 'startMs' | 'startDate'>, change: EventChange, scope: RecurrenceScope, ctx: CalendarContext): { ops: Op[]; record_id: string } {\n const newId = ctx.newRecordId ?? (() => newRecordId('e'))\n const fieldChanges = (row: RowLike): Record<string, Json | undefined> => {\n const out: Record<string, Json | undefined> = { ...(change.values as Record<string, Json | undefined> | undefined) }\n if (change.ext_merge) {\n const ext = extOf(row)\n for (const [k, v] of Object.entries(change.ext_merge)) if (v === null) delete ext[k]; else ext[k] = v\n out.ext = Object.keys(ext).length ? ext : null\n }\n return out\n }\n const master = occ.master\n // a single event, or an override edited as itself\n if (!master || (occ.row !== master && scope === 'one')) {\n const row = occ.row\n const changes = { ...fieldChanges(row), ...(change.times ? timesChanges(change.times) : {}) }\n if (change.rrule !== undefined && !master) {\n const ext = (changes.ext as Record<string, Json> | null | undefined) ?? extOf(row)\n const next = { ...(ext ?? {}) }\n if (change.rrule === null) delete next.rrule; else next.rrule = formatRRule(parseRRule(change.rrule))\n if (change.rrule === null) delete next.exdate\n changes.ext = Object.keys(next).length ? next : null\n }\n return { ops: setValuesOps(sourceId, row, changes), record_id: row.record_id }\n }\n const original = occ.original!\n const masterTimes = rowTimes(master)!\n const masterExt = extOf(master)\n if (scope === 'one') {\n // a new override from the master's values for this occurrence\n const id = newId()\n const ext: Record<string, Json> = { ...masterExt, recurrence_id: { master: master.record_id, original } }\n delete ext.rrule; delete ext.exdate; delete ext.occurrences; delete ext.rule_text; delete ext.covered_until; delete ext.maintenance\n const base: Record<string, Json | undefined> = { title: master.values.title, status: master.values.status, ext }\n const times: EventTimes = change.times ?? (occ.allDay\n ? { allDay: true, startDate: occ.startDate!, endDate: addDays(occ.startDate!, daysBetween(masterTimes.startDate!, masterTimes.endDate!)) }\n : { allDay: false, start: new Date(occ.startMs!).toISOString(), end: new Date(occ.startMs! + (masterTimes.endMs! - masterTimes.startMs!)).toISOString() })\n const values = { ...base, ...fieldChanges({ record_id: id, values: { ext } }), ...timesChanges(times) }\n if (!values.ext) values.ext = ext\n return { ops: [insertRecordOp(sourceId, [{ record_id: id, values }])], record_id: id }\n }\n // the time change the edit makes to this occurrence (from where the series puts it), applied to the series\n let deltaMs = 0, deltaDays = 0\n let durationMs = masterTimes.allDay ? 0 : masterTimes.endMs! - masterTimes.startMs!\n let durationDays = masterTimes.allDay ? daysBetween(masterTimes.startDate!, masterTimes.endDate!) : 0\n if (change.times) {\n if (change.times.allDay !== masterTimes.allDay) throw new Error('changing a series between all-day and timed: edit the series itself (scope all) with new times')\n if (change.times.allDay) {\n deltaDays = daysBetween(original, change.times.startDate)\n durationDays = daysBetween(change.times.startDate, change.times.endDate)\n } else {\n deltaMs = Date.parse(change.times.start) - Date.parse(original)\n deltaDays = Math.round(deltaMs / 86_400_000)\n durationMs = Date.parse(change.times.end) - Date.parse(change.times.start)\n }\n }\n const rule = typeof masterExt.rrule === 'string' ? parseRRule(masterExt.rrule) : null\n const overrides = overridesOf(ctx.rows, master.record_id)\n const exdate = originals(masterExt.exdate)\n const isFirst = masterTimes.allDay ? original === masterTimes.startDate : original === new Date(masterTimes.startMs!).toISOString()\n const seriesTimes = (startMs: number | undefined, startDate: string | undefined): EventTimes => (masterTimes.allDay\n ? { allDay: true, startDate: addDays(startDate!, deltaDays), endDate: addDays(addDays(startDate!, deltaDays), durationDays) }\n : { allDay: false, start: new Date(startMs! + deltaMs).toISOString(), end: new Date(startMs! + deltaMs + durationMs).toISOString() })\n const nextRule = (r: RRule | null): string | null => {\n if (change.rrule !== undefined) return change.rrule === null ? null : formatRRule(parseRRule(change.rrule))\n return r ? formatRRule(shiftRule(r, deltaDays)) : null\n }\n const ops: Op[] = []\n if (scope === 'all' || isFirst) {\n const times = seriesTimes(masterTimes.startMs, masterTimes.startDate)\n const ext = { ...masterExt }\n const r = nextRule(rule)\n if (r) ext.rrule = r; else { delete ext.rrule; delete ext.exdate }\n if (r && exdate.length) ext.exdate = exdate.map((x) => shiftOriginal(x, masterTimes.allDay, deltaMs, deltaDays))\n const fc = fieldChanges({ record_id: master.record_id, values: { ext } })\n const extOut = fc.ext !== undefined ? fc.ext : ext\n ops.push(...setValuesOps(sourceId, master, { ...fc, ...timesChanges(times), ext: extOut && Object.keys(extOut as object).length ? extOut : null }))\n for (const o of overrides) {\n const oext = extOf(o)\n const rid = oext.recurrence_id as Record<string, Json>\n if (!r) { ops.push(deleteRecordsOp(sourceId, [o])); continue }\n if (deltaMs || deltaDays) ops.push(...setValuesOps(sourceId, o, { ext: { ...oext, recurrence_id: { ...rid, original: shiftOriginal(String(rid.original), masterTimes.allDay, deltaMs, deltaDays) } } }))\n }\n return { ops, record_id: master.record_id }\n }\n // following: the master ends before this occurrence, a new series starts here\n if (!rule) throw new Error('not a repeating event')\n const id = newId()\n const before = (x: string) => (masterTimes.allDay ? x < original : Date.parse(x) < Date.parse(original))\n let headRule: RRule = { ...rule }\n let tailRule: RRule = { ...rule }\n if (rule.count !== undefined) {\n const start = seriesStartOf(master.values, typeof masterExt.tz === 'string' ? masterExt.tz : undefined)!\n const fromMs = masterTimes.allDay ? Date.parse(`${masterTimes.startDate}T00:00:00Z`) - 86_400_000 * 2 : masterTimes.startMs!\n const toMs = masterTimes.allDay ? Date.parse(`${original}T00:00:00Z`) : Date.parse(original)\n const done = expandSeries(rule, start, { fromMs, toMs }, { viewerTz: 'UTC' }).filter((o) => before(o.original)).length\n headRule = { ...rule, count: Math.max(1, done) }\n tailRule = { ...rule, count: Math.max(1, rule.count - done) }\n } else {\n headRule = { ...rule, until: masterTimes.allDay ? addDays(original, -1) : new Date(Date.parse(original) - 1000).toISOString().replace(/\\.\\d{3}Z$/, '.000Z') }\n }\n const headExt: Record<string, Json> = { ...masterExt, rrule: formatRRule(headRule) }\n const headEx = exdate.filter(before)\n if (headEx.length) headExt.exdate = headEx; else delete headExt.exdate\n ops.push(...setValuesOps(sourceId, master, { ext: headExt }))\n const tailExt: Record<string, Json> = { ...masterExt }\n const tr = nextRule(tailRule)\n if (tr) tailExt.rrule = tr; else delete tailExt.rrule\n const tailEx = exdate.filter((x) => !before(x)).map((x) => shiftOriginal(x, masterTimes.allDay, deltaMs, deltaDays))\n if (tailEx.length && tr) tailExt.exdate = tailEx; else delete tailExt.exdate\n const times = seriesTimes(masterTimes.allDay ? undefined : Date.parse(original), masterTimes.allDay ? original : undefined)\n const fc = fieldChanges({ record_id: id, values: { ext: tailExt } })\n const values: Record<string, Json | undefined> = { title: master.values.title, status: master.values.status, ...fc, ...timesChanges(times) }\n values.ext = (fc.ext !== undefined ? fc.ext : tailExt) ?? undefined\n ops.push(insertRecordOp(sourceId, [{ record_id: id, values }]))\n for (const o of overrides) {\n const oext = extOf(o)\n const rid = oext.recurrence_id as Record<string, Json>\n if (before(String(rid.original))) continue\n if (!tr) { ops.push(deleteRecordsOp(sourceId, [o])); continue }\n ops.push(...setValuesOps(sourceId, o, { ext: { ...oext, recurrence_id: { master: id, original: shiftOriginal(String(rid.original), masterTimes.allDay, deltaMs, deltaDays) } } }))\n }\n return { ops, record_id: id }\n}\n\n/** Remove one occurrence (“今天不用了”: an exclusion, and its override goes), this and the following ones (the series\n * ends before it), or the whole series with its overrides. A single event is deleted. */\nexport function eventDeleteOps(sourceId: string, occ: Pick<EventOccurrence, 'row' | 'master' | 'original'>, scope: RecurrenceScope, ctx: CalendarContext): Op[] {\n const master = occ.master\n if (!master) return [deleteRecordsOp(sourceId, [occ.row])]\n const original = occ.original!\n const masterExt = extOf(master)\n const masterTimes = rowTimes(master)!\n const overrides = overridesOf(ctx.rows, master.record_id)\n const isFirst = masterTimes.allDay ? original === masterTimes.startDate : original === new Date(masterTimes.startMs!).toISOString()\n if (scope === 'all' || (scope === 'following' && isFirst)) return [deleteRecordsOp(sourceId, [master, ...overrides])]\n const ops: Op[] = []\n if (scope === 'one') {\n const exdate = originals(masterExt.exdate)\n if (!exdate.includes(original)) ops.push(...setValuesOps(sourceId, master, { ext: { ...masterExt, exdate: [...exdate, original].sort() } }))\n const own = overrides.filter((o) => canonicalOriginal(String((extOf(o).recurrence_id as Record<string, Json>).original)) === original)\n if (own.length) ops.push(deleteRecordsOp(sourceId, own))\n return ops\n }\n const rule = typeof masterExt.rrule === 'string' ? parseRRule(masterExt.rrule) : null\n if (!rule) return [deleteRecordsOp(sourceId, [occ.row])]\n const before = (x: string) => (masterTimes.allDay ? x < original : Date.parse(x) < Date.parse(original))\n const head: RRule = { ...rule, count: undefined, until: masterTimes.allDay ? addDays(original, -1) : new Date(Date.parse(original) - 1000).toISOString() }\n const ext: Record<string, Json> = { ...masterExt, rrule: formatRRule(head) }\n if (Array.isArray(masterExt.exdate)) {\n const keep = originals(masterExt.exdate).filter(before)\n if (keep.length) ext.exdate = keep; else delete ext.exdate\n }\n ops.push(...setValuesOps(sourceId, master, { ext }))\n const gone = overrides.filter((o) => !before(String((extOf(o).recurrence_id as Record<string, Json>).original)))\n if (gone.length) ops.push(deleteRecordsOp(sourceId, gone))\n return ops\n}\n\n/** Skip one occurrence (D4: the notification's “skip”). */\nexport const eventSkipOps = (sourceId: string, occ: Pick<EventOccurrence, 'row' | 'master' | 'original'>, ctx: CalendarContext) => eventDeleteOps(sourceId, occ, 'one', ctx)\n\n/** Postpone one occurrence by `minutes` (D4: the notification's “snooze”): an override of that occurrence. */\nexport function eventPostponeOps(sourceId: string, occ: Pick<EventOccurrence, 'row' | 'master' | 'original' | 'allDay' | 'startMs' | 'endMs' | 'startDate' | 'endDate'>, minutes: number, ctx: CalendarContext): { ops: Op[]; record_id: string } {\n const times: EventTimes = occ.allDay\n ? { allDay: true, startDate: addDays(occ.startDate!, Math.max(1, Math.round(minutes / 1440))), endDate: addDays(occ.endDate!, Math.max(1, Math.round(minutes / 1440))) }\n : { allDay: false, start: new Date(occ.startMs! + minutes * 60_000).toISOString(), end: new Date(occ.endMs! + minutes * 60_000).toISOString() }\n return eventEditOps(sourceId, occ, { times }, 'one', ctx)\n}\n\n// ---- the private schedule Workspace\n\nexport interface ScheduleHandle {\n workspace_id: string\n epoch: string\n created: boolean\n todo: string\n calendar: string\n}\n\nconst ROWS_PAGE = 1000\n\n/** How the schedule talks to the service: one kRPC call whose business failure (`ok: false`) throws — an\n * `AiWorkspaceClient`, or the CLI's service call. */\nexport interface ScheduleTransport {\n call<T = Record<string, unknown>>(method: string, params: Record<string, unknown>): Promise<T>\n}\n\n/** The person's private schedule (Q5): one Workspace named `schedule`, its to-do table `todo` and calendar table\n * `calendar` (fixed ids), and a page showing both, created the first time. Agents and commands use it by name. */\nexport class ScheduleClient {\n private handle: ScheduleHandle | null = null\n private readonly locale: ScheduleLocale\n\n constructor(readonly aiws: ScheduleTransport, opts: { locale?: ScheduleLocale } = {}) {\n this.locale = opts.locale ?? 'zh'\n }\n\n /** The schedule Workspace with its two tables (created when missing; concurrent first uses converge). */\n async ensure(): Promise<ScheduleHandle> {\n if (this.handle) return this.handle\n const ws = await this.aiws.call<{ workspace_id: string; epoch: string; created: boolean }>('ws.ensure', { name: SCHEDULE_WORKSPACE_NAME, title: scheduleLabel(this.locale, 'workspace') })\n const handle: ScheduleHandle = { workspace_id: ws.workspace_id, epoch: ws.epoch, created: ws.created, todo: SCHEDULE_TODO_ID, calendar: SCHEDULE_CALENDAR_ID }\n // what is there already (`doc.read` is stable; the outline is the Desktop's)\n const have = new Set<string>()\n for (const id of [SCHEDULE_TODO_ID, SCHEDULE_CALENDAR_ID, SCHEDULE_SURFACE_ID]) {\n try {\n const read = await this.aiws.call<{ deleted?: boolean }>('doc.read', { workspace_id: ws.workspace_id, entity_id: id })\n if (!read.deleted) have.add(id)\n } catch (error) {\n // a transport's failure carries the service's code (an AiwsFailure, or any error with `code`)\n const code = (error as { code?: unknown } | null)?.code\n if (code !== 'NOT_FOUND' && code !== 'TARGET_DELETED') throw error\n }\n }\n const ops: Op[] = []\n if (!have.has(SCHEDULE_TODO_ID)) ops.push(standardTableOp('todo', { entity_id: SCHEDULE_TODO_ID, parent_id: 'data', order_key: 'u', locale: this.locale }))\n if (!have.has(SCHEDULE_CALENDAR_ID)) ops.push(standardTableOp('calendar', { entity_id: SCHEDULE_CALENDAR_ID, parent_id: 'data', order_key: 'v', locale: this.locale }))\n if (!have.has(SCHEDULE_SURFACE_ID)) ops.push(...scheduleBoardOps(this.locale))\n if (ops.length) {\n const result = await this.commitTo(handle, ops, 'create the schedule', 'system')\n // a concurrent first use created them: fine\n const idConflict = (result.sub_code ?? result.errors?.[0]?.sub_code ?? result.error?.sub_code) === 'ID_CONFLICT'\n if (result.status !== 'accepted' && !(result.status === 'rejected' && idConflict)) throw failureOf(result)\n }\n this.handle = handle\n return handle\n }\n\n private async commitTo(handle: ScheduleHandle, operations: Op[], message: string, origin: 'agent' | 'human' | 'system' = 'agent'): Promise<CommitResult> {\n const key = `sched-${newRecordId('k')}`\n const request = (epoch: string) => ({ protocol_version: AIWS_PROTOCOL_VERSION, workspace_id: handle.workspace_id, epoch, idempotency_key: key, origin, message, operations })\n let result = await this.aiws.call<CommitResult>('doc.commit', request(handle.epoch))\n if (result.status === 'rejected' && (result.code ?? result.error?.code) === 'EPOCH_MISMATCH') {\n const info = await this.aiws.call<{ epoch: string }>('ws.get_info', { workspace_id: handle.workspace_id })\n handle.epoch = info.epoch\n result = await this.aiws.call<CommitResult>('doc.commit', request(handle.epoch))\n }\n return result\n }\n\n /** Commit operations into the schedule; a refusal or conflict throws with the service's reason. */\n async commit(operations: Op[], message: string): Promise<CommitResult> {\n const handle = await this.ensure()\n const result = await this.commitTo(handle, operations, message)\n if (result.status !== 'accepted') throw failureOf(result)\n return result\n }\n\n /** Every live record of a table, as `doc.read` answers one (the SQL `_record` column), by record id. */\n async rows(sourceId: string): Promise<RowLike[]> {\n const handle = await this.ensure()\n const rows: RowLike[] = []\n for (let i = 0; i < 100; i++) {\n const page = await this.aiws.call<{ rows: unknown[][] }>('doc.query', {\n workspace_id: handle.workspace_id, sql: 'SELECT \"_record\" FROM t ORDER BY \"_id\" LIMIT ? OFFSET ?',\n params: [ROWS_PAGE, i * ROWS_PAGE], tables: { t: sourceId }, max_rows: ROWS_PAGE,\n })\n for (const [record] of page.rows) rows.push((typeof record === 'string' ? JSON.parse(record) : record) as RowLike)\n if (page.rows.length < ROWS_PAGE) break\n }\n return rows\n }\n\n async row(sourceId: string, recordId: string): Promise<RowLike> {\n const handle = await this.ensure()\n const r = await this.aiws.call<{ content?: RowLike }>('doc.read', { workspace_id: handle.workspace_id, entity_id: sourceId, selector: { kind: 'table_record', record_id: recordId } })\n const row = r.content as RowLike\n if (!row?.record_id) throw new AiwsFailure({ code: 'NOT_FOUND', retryable: false, detail: `record ${recordId} not found` })\n return row\n }\n\n // ---- to-do\n\n async todos(opts: { includeDone?: boolean } = {}): Promise<TodoItem[]> {\n const items = sortTodos((await this.rows(SCHEDULE_TODO_ID)).map(todoItem))\n return opts.includeDone ? items : items.filter((i) => !i.done)\n }\n\n async addTodo(input: TodoValues & { title: string }, place: { after?: string; before?: string } = {}): Promise<TodoItem> {\n const items = sortTodos((await this.rows(SCHEDULE_TODO_ID)).map(todoItem))\n const at = (id?: string) => items.find((i) => i.record_id === id)\n let pos: { after?: string | null; before?: string | null; items?: TodoItem[] } = { items }\n if (place.after) { const i = items.findIndex((x) => x.record_id === place.after); pos = { after: at(place.after)?.order ?? null, before: items[i + 1]?.order ?? null } }\n else if (place.before) { const i = items.findIndex((x) => x.record_id === place.before); pos = { after: items[i - 1]?.order ?? null, before: at(place.before)?.order ?? null } }\n const { record_id, ops } = todoAddOps(SCHEDULE_TODO_ID, input, pos)\n await this.commit(ops, `add to-do: ${input.title}`)\n return todoItem(await this.row(SCHEDULE_TODO_ID, record_id))\n }\n\n async completeTodo(recordId: string, done = true): Promise<void> {\n const row = await this.row(SCHEDULE_TODO_ID, recordId)\n const ops = todoCompleteOps(SCHEDULE_TODO_ID, row, done)\n if (ops.length) await this.commit(ops, `${done ? 'complete' : 'reopen'} to-do ${recordId}`)\n }\n\n async updateTodo(recordId: string, changes: TodoValues & { ext_merge?: Record<string, Json | null> }): Promise<void> {\n const row = await this.row(SCHEDULE_TODO_ID, recordId)\n const ops = todoUpdateOps(SCHEDULE_TODO_ID, row, changes)\n if (ops.length) await this.commit(ops, `update to-do ${recordId}`)\n }\n\n /** Move a to-do before / after another one, and / or into another status. */\n async moveTodo(recordId: string, to: { status?: string; before?: string; after?: string }): Promise<void> {\n const items = sortTodos((await this.rows(SCHEDULE_TODO_ID)).map(todoItem))\n const row = items.find((i) => i.record_id === recordId)\n if (!row) throw new AiwsFailure({ code: 'NOT_FOUND', retryable: false, detail: `to-do ${recordId} not found` })\n const others = items.filter((i) => i.record_id !== recordId)\n let order: string | undefined\n if (to.before || to.after) {\n const anchor = others.findIndex((i) => i.record_id === (to.before ?? to.after))\n if (anchor < 0) throw new AiwsFailure({ code: 'NOT_FOUND', retryable: false, detail: `to-do ${to.before ?? to.after} not found` })\n order = orderAt(others, to.before ? anchor : anchor + 1)\n }\n const ops = todoMoveOps(SCHEDULE_TODO_ID, row, { status: to.status, order })\n if (ops.length) await this.commit(ops, `move to-do ${recordId}`)\n }\n\n async removeTodos(recordIds: string[]): Promise<void> {\n const rows = await Promise.all(recordIds.map((id) => this.row(SCHEDULE_TODO_ID, id)))\n await this.commit([deleteRecordsOp(SCHEDULE_TODO_ID, rows)], `delete to-do ${recordIds.join(', ')}`)\n }\n\n // ---- calendar\n\n async events(window: { fromMs: number; toMs: number }, opts: { viewerTz?: string } = {}): Promise<EventOccurrence[]> {\n return calendarOccurrences(await this.rows(SCHEDULE_CALENDAR_ID), window, opts)\n }\n\n async addEvent(input: EventValues & { title: string }): Promise<string> {\n if (input.ext?.rrule !== undefined && typeof input.ext.rrule === 'string') input = { ...input, ext: { ...input.ext, rrule: formatRRule(parseRRule(input.ext.rrule)) } }\n const { record_id, ops } = eventAddOps(SCHEDULE_CALENDAR_ID, input)\n await this.commit(ops, `add event: ${input.title}`)\n return record_id\n }\n\n /** The occurrence an id names (`record_id` or `<master>@<original>`), from all rows. */\n async occurrence(id: string): Promise<{ occ: EventOccurrence; rows: RowLike[] }> {\n const rows = await this.rows(SCHEDULE_CALENDAR_ID)\n return { occ: findOccurrence(rows, id), rows }\n }\n\n async editEvent(id: string, change: EventChange, scope: RecurrenceScope = 'one'): Promise<string> {\n const { occ, rows } = await this.occurrence(id)\n const { ops, record_id } = eventEditOps(SCHEDULE_CALENDAR_ID, occ, change, scope, { rows })\n if (ops.length) await this.commit(ops, `edit event ${id} (${scope})`)\n return record_id\n }\n\n async deleteEvent(id: string, scope: RecurrenceScope = 'one'): Promise<void> {\n const { occ, rows } = await this.occurrence(id)\n await this.commit(eventDeleteOps(SCHEDULE_CALENDAR_ID, occ, scope, { rows }), `delete event ${id} (${scope})`)\n }\n}\n\nexport interface CommitResult {\n status: 'accepted' | 'conflict' | 'rejected' | 'saved_locally'\n seq?: number\n commit_id?: string\n code?: string\n sub_code?: string\n detail?: string\n errors?: { code: string; sub_code?: string; detail?: string }[]\n error?: { code: string; sub_code?: string; detail: string; retryable: boolean }\n conflicts?: { selector?: unknown; entity_id?: string; code?: string }[]\n}\n\nfunction failureOf(result: CommitResult): AiwsFailure {\n const first = result.errors?.[0]\n if (result.status === 'conflict') {\n const c = result.conflicts?.[0]\n return new AiwsFailure({ code: result.code ?? 'REVISION_CONFLICT', retryable: true, detail: `changed meanwhile, read it again${c ? `: ${JSON.stringify(c.selector ?? c)}` : ''}` })\n }\n return new AiwsFailure({ code: result.code ?? result.error?.code ?? 'REJECTED', sub_code: result.sub_code ?? first?.sub_code, retryable: false, detail: first?.detail ?? result.detail ?? result.error?.detail ?? 'refused' })\n}\n\n/** The occurrence an id names among a calendar's rows: a record id, or `<master>@<original>` (an occurrence of a\n * series, overridden or not). */\nexport function findOccurrence(rows: RowLike[], id: string): EventOccurrence {\n const at = id.indexOf('@')\n const recordId = at < 0 ? id : id.slice(0, at)\n const original = at < 0 ? null : canonicalOriginal(id.slice(at + 1))\n const row = rows.find((r) => r.record_id === recordId)\n if (!row) throw new AiwsFailure({ code: 'NOT_FOUND', retryable: false, detail: `event ${recordId} not found` })\n if (original === null) {\n const times = rowTimes(row)\n if (!times) throw new AiwsFailure({ code: 'INVALID_OPERATION', retryable: false, detail: `event ${recordId} has no time` })\n const ext = extOf(row)\n const rid = ext.recurrence_id as Record<string, Json> | undefined\n const master = rid && typeof rid.master === 'string' ? rows.find((r) => r.record_id === rid.master) : undefined\n return occurrenceOf(row, times, master ? { master, original: String(rid!.original), recurring: true, override: true } : { recurring: typeof ext.rrule === 'string', master: typeof ext.rrule === 'string' ? row : undefined, original: typeof ext.rrule === 'string' ? (times.allDay ? times.startDate : new Date(times.startMs!).toISOString()) : undefined })\n }\n const override = rows.find((r) => {\n const rid = extOf(r).recurrence_id as Record<string, Json> | undefined\n return rid && rid.master === recordId && typeof rid.original === 'string' && canonicalOriginal(rid.original) === canonicalOriginal(original)\n })\n const times = rowTimes(row)\n if (!times) throw new AiwsFailure({ code: 'INVALID_OPERATION', retryable: false, detail: `event ${recordId} has no time` })\n if (override) return occurrenceOf(override, rowTimes(override)!, { id, master: row, original, recurring: true, override: true })\n const allDay = times.allDay\n const durationMs = allDay ? 0 : times.endMs! - times.startMs!\n const durationDays = allDay ? daysBetween(times.startDate!, times.endDate!) : 0\n const occTimes = allDay ? { allDay: true, startDate: original, endDate: addDays(original, durationDays) } : { allDay: false, startMs: Date.parse(original), endMs: Date.parse(original) + durationMs }\n return occurrenceOf(row, occTimes, { id, master: row, original, recurring: true })\n}\n\n/** The schedule page of the private Workspace: a Surface with the calendar and the to-do list side by side. */\nexport function scheduleBoardOps(locale: ScheduleLocale = 'zh'): Op[] {\n const folder = `${SCHEDULE_SURFACE_ID}-content`\n const title = scheduleLabel(locale, 'board')\n return [\n { op: 'entity.create', entity_id: folder, type_id: 'buckyos.container', parent_id: 'canvas-content', order_key: 'u', name: title, payload: { kind: 'folder', title, system: 'surface_content', surface_id: SCHEDULE_SURFACE_ID } },\n { op: 'entity.create', entity_id: SCHEDULE_SURFACE_ID, type_id: 'buckyos.container', parent_id: 'surfaces', order_key: 'a', name: title, payload: { kind: 'surface', layout: { mode: 'free' }, title, content_folder_id: folder } },\n { op: 'entity.create', entity_id: `${SCHEDULE_SURFACE_ID}-calendar`, type_id: 'buckyos.container', parent_id: SCHEDULE_SURFACE_ID, order_key: 'a', placement: { x: 40, y: 40, w: 880, h: 640 },\n payload: { kind: 'calendar', layout: { mode: 'data' }, title: scheduleLabel(locale, 'calendar_table'), bindings: { events: [{ entity_id: SCHEDULE_CALENDAR_ID }], todo: [{ entity_id: SCHEDULE_TODO_ID }] }, config: { view: 'week' } } },\n { op: 'entity.create', entity_id: `${SCHEDULE_SURFACE_ID}-todo`, type_id: 'buckyos.container', parent_id: SCHEDULE_SURFACE_ID, order_key: 'b', placement: { x: 960, y: 40, w: 420, h: 640 },\n payload: { kind: 'todo', layout: { mode: 'data' }, title: scheduleLabel(locale, 'todo_table'), bindings: { items: { entity_id: SCHEDULE_TODO_ID } }, config: { mode: 'list' } } },\n ]\n}\n\nexport { isDate } from './aiws_rrule'\n","/**\n * What a control binds when it is placed or re-bound (buckyos notepads/aiworkspace-control-on-bind-todo.md): every\n * control placed in one go — a composite and the first Blocks of its slots, say — runs `on_bind` from parent to child\n * (a child sees what its parent bound), then `on_init_control` from child to parent (a parent checks its children are\n * ready); a failure or a cancelled dialog places nothing. A control without its own `on_bind` follows the default rule\n * of its binding declarations (`required`, `many`, `schema_id`); a composite writes its steps in component.json. The\n * host (the Desktop, the CLI) answers the data queries, shows the dialogs — or, with `no_ui` (an Agent), fails where a\n * person would have to choose — and turns the result into one Commit (`bindOps`). Shared by the Desktop and the CLI.\n */\nimport { CALENDAR_SCHEMA_ID, standardTableOp, TODO_SCHEMA_ID, type Json, type Op } from './aiws_schedule'\n\n/** One binding a control declares (component.json `bindings`, a built-in control's contract). */\nexport interface BindingDecl {\n accepts?: string[]\n required?: boolean\n /** Takes several data: the instance binds a list. */\n many?: boolean\n /** Only tables of this business schema. */\n schema_id?: string\n title?: string\n description?: string\n}\n\n/** Bound data by binding name: one id, or a list for a `many` binding. An id may be a `ref` of data created here. */\nexport type Bound = Record<string, string | string[]>\n\n/** Data of the Workspace a query answers. */\nexport interface DataInfo { entity_id: string; type_id: string; schema_id?: string | null; title?: string | null; name?: string | null; place?: string | null }\n/** `ids`: only these (a control's own on_bind narrowing what a dialog offers). */\nexport interface DataQuery { accepts?: string[]; schema_id?: string; ids?: string[] }\n\n/** Data the binding creates, in the canvas's content folder, owned by the control (`ref` names it in `bindings`). */\nexport type CreateSpec =\n | { ref: string; kind: 'standard'; schema_id: string; name: string }\n | { ref: string; kind: 'table'; name: string; title_field_id?: string; fields: Json[] }\n | { ref: string; kind: 'dir'; name: string }\n\n/** The host's dialogs (`no_ui`: each fails with `needsUi`). */\nexport interface BindDialogs {\n pickOne(o: { title: string; note?: string; query: DataQuery; allow_new?: boolean; current?: string | null }): Promise<string | { new: true } | null>\n /** Each chosen id, and `{ new: true }` for a new one (when `allow_new`). */\n pickMany(o: { title: string; note?: string; query: DataQuery; preselect?: 'all' | 'none' | string[]; allow_new?: boolean }): Promise<(string | { new: true })[] | null>\n confirm(o: { title: string; text: string }): Promise<boolean>\n}\n\nexport class BindFailure extends Error {\n constructor(message: string, readonly code: 'NEEDS_UI' | 'NO_DATA' | 'NOT_READY' | 'CANCELLED' | 'INVALID', readonly node?: string, readonly binding?: string) {\n super(message)\n }\n}\n\nexport interface BindCtx {\n reason: 'insert' | 'rebind'\n no_ui: boolean\n /** The control's id in this placement and its title. */\n node: string\n title: string\n decls: Record<string, BindingDecl>\n /** Bindings already given: by an Agent, chosen before inserting, or the current ones on a re-bind. */\n given: Bound\n /** What the parent control declared and bound (none for the control placed at the top). */\n parent: { decls: Record<string, BindingDecl>; bound: Bound } | null\n find(q: DataQuery): DataInfo[]\n /** The standard schemas the host can create a table of. */\n canCreate(decl: BindingDecl): boolean\n dialogs: BindDialogs\n}\n\nexport interface BindResult { bindings: Bound; create: CreateSpec[] }\nexport type OnBind = (ctx: BindCtx) => Promise<BindResult | null>\n\nexport interface ChildState { node: string; title: string; ready: boolean; missing: string[] }\nexport interface InitCtx {\n reason: 'insert' | 'rebind'\n no_ui: boolean\n node: string\n title: string\n decls: Record<string, BindingDecl>\n bound: Bound\n children: ChildState[]\n dialogs: BindDialogs\n}\n/** Ready (`true`), or why not. */\nexport type OnInit = (ctx: InitCtx) => Promise<true | string>\n\n/** A composite's declared steps (component.json manifest 5). */\nexport type OnBindStep =\n | { binding: string; pick: 'one' | 'many' | 'all'; title?: string; allow_new?: boolean }\n | { binding: string; from_parent: string }\n | { binding: string; create: { standard: string } | { table: { name: string; title_field_id?: string; fields: Json[] } } | { dir: { name: string } }; when?: 'missing' | 'always' }\nexport type OnInitStep = { require: 'children' } | { then: { action: string } }\n\n/** A control of this placement, with the controls placed under it. */\nexport interface BindNode {\n id: string\n title: string\n decls: Record<string, BindingDecl>\n given?: Bound\n onBind?: OnBind | OnBindStep[]\n onInit?: OnInit | OnInitStep[]\n children: BindNode[]\n}\n\nexport interface BindHost {\n reason: 'insert' | 'rebind'\n no_ui: boolean\n find(q: DataQuery): DataInfo[]\n /** Standard schemas the host creates a table of (default: the to-do and calendar tables). */\n standardSchemas?: string[]\n dialogs: BindDialogs\n /** The control the placed one goes into, when it is one already on the canvas (a Block put into a composite). */\n parent?: { decls: Record<string, BindingDecl>; bound: Bound } | null\n}\n\nexport type BindOutcome =\n | { ok: true; results: Map<string, BindResult>; then: { node: string; action: string }[] }\n | { ok: false; error: BindFailure }\n\nexport const STANDARD_SCHEMAS = [TODO_SCHEMA_ID, CALENDAR_SCHEMA_ID]\n\nconst asList = (v: string | string[] | undefined): string[] => (v === undefined ? [] : Array.isArray(v) ? v : [v])\nconst label = (name: string, decl: BindingDecl) => decl.title ?? name\n\n/** Whether `data` is what a declaration takes. */\nexport function bindingAccepts(decl: BindingDecl, data: Pick<DataInfo, 'type_id' | 'schema_id'>): boolean {\n if (decl.accepts && decl.accepts.length > 0 && !decl.accepts.includes(data.type_id)) return false\n if (decl.schema_id && data.schema_id !== decl.schema_id) return false\n return true\n}\n\nconst queryOf = (decl: BindingDecl): DataQuery => ({ ...(decl.accepts?.length ? { accepts: decl.accepts } : {}), ...(decl.schema_id ? { schema_id: decl.schema_id } : {}) })\n\n/** The dialogs of a host without a person: every one fails, naming the binding a caller has to give. */\nexport function noUiDialogs(): BindDialogs {\n const fail = (title: string): never => { throw new BindFailure(`needs a choice: ${title}`, 'NEEDS_UI') }\n return { pickOne: async (o) => fail(o.title), pickMany: async (o) => fail(o.title), confirm: async (o) => fail(o.title) }\n}\n\nlet refSeq = 0\nconst newRef = () => `ref:${++refSeq}`\n\nconst MAX_ITEMS = 32\nconst MAX_CREATE = 16\n\n/** An on_bind's result as the host takes it — also what an HTML control's script returned (TODO §2.9): every binding a\n * declared one, a single binding one id, a `many` one at most 32; what it creates well-formed, its refs used and renamed\n * apart from other controls' refs of the same placement. */\nexport function checkBindResult(value: unknown, decls: Record<string, BindingDecl>, node: string): BindResult {\n const bad = (message: string): never => { throw new BindFailure(`on_bind result: ${message}`, 'INVALID', node) }\n const isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)\n if (!isObject(value) || !isObject(value.bindings)) return bad('{ bindings, create? } (or null to cancel)')\n const created = value.create === undefined ? [] : value.create\n if (!Array.isArray(created) || created.length > MAX_CREATE) return bad(`create: a list of at most ${MAX_CREATE}`)\n const refs = new Map<string, string>()\n const create: CreateSpec[] = created.map((c, i) => {\n const at = `create[${i}]`\n if (!isObject(c) || typeof c.ref !== 'string' || !c.ref) return bad(`${at}: { ref, kind, … }`)\n if (refs.has(c.ref)) return bad(`${at}: ref ${c.ref} twice`)\n const ref = newRef()\n refs.set(c.ref, ref)\n const name = typeof c.name === 'string' && c.name.trim() && c.name.length <= 128 ? c.name.trim() : null\n if (c.kind === 'standard') {\n if (typeof c.schema_id !== 'string') return bad(`${at}: a standard table names its schema_id`)\n return { ref, kind: 'standard', schema_id: c.schema_id, name: name ?? c.schema_id }\n }\n if (!name) return bad(`${at}: a name (at most 128 characters)`)\n if (c.kind === 'table') {\n if (!Array.isArray(c.fields) || c.fields.length === 0) return bad(`${at}: a table lists its fields`)\n if (c.title_field_id !== undefined && typeof c.title_field_id !== 'string') return bad(`${at}: title_field_id is a field id`)\n return { ref, kind: 'table', name, fields: c.fields as Json[], ...(c.title_field_id ? { title_field_id: c.title_field_id as string } : {}) }\n }\n if (c.kind === 'dir') return { ref, kind: 'dir', name }\n return bad(`${at}: kind standard, table or dir`)\n })\n const bindings: Bound = {}\n const used = new Set<string>()\n for (const [name, v] of Object.entries(value.bindings)) {\n const decl = decls[name]\n if (!decl) return bad(`${name} is not a declared binding`)\n if (v === null || v === undefined) continue\n const list = typeof v === 'string' ? [v] : Array.isArray(v) && v.every((x) => typeof x === 'string' && x) ? v as string[] : bad(`${name}: an id, or a list of ids`)\n if (!decl.many && (Array.isArray(v) || list.length !== 1)) return bad(`${name} takes one`)\n if (list.length > MAX_ITEMS || new Set(list).size !== list.length) return bad(`${name}: at most ${MAX_ITEMS}, each once`)\n const ids = list.map((id) => { if (refs.has(id)) used.add(id); return refs.get(id) ?? id })\n if (decl.many) { if (ids.length > 0) bindings[name] = ids } else bindings[name] = ids[0]\n }\n const unused = [...refs.keys()].filter((r) => !used.has(r))\n if (unused.length > 0) return bad(`created but not bound: ${unused.join(', ')}`)\n return { bindings, create }\n}\n\n/** The default rule of a declaration (TODO §2.4): given → the parent's matching data → the Workspace's data. */\nexport const defaultOnBind: OnBind = async (ctx) => {\n const bindings: Bound = {}\n const create: CreateSpec[] = []\n const parentData = ctx.parent ? Object.values(ctx.parent.bound).flatMap(asList) : []\n const known = new Map(ctx.find({}).map((d) => [d.entity_id, d]))\n for (const [name, decl] of Object.entries(ctx.decls)) {\n const failNamed = (message: string, code: BindFailure['code']) => new BindFailure(message, code, ctx.node, name)\n if (ctx.reason === 'rebind') {\n if (ctx.given[name] !== undefined && ctx.no_ui) { bindings[name] = ctx.given[name]; continue }\n const current = asList(ctx.given[name])\n if (decl.many) {\n const picked = await withName(name, () => ctx.dialogs.pickMany({ title: label(name, decl), query: queryOf(decl), preselect: current, allow_new: ctx.canCreate(decl) }))\n if (picked === null) return null\n bindings[name] = picked.map((p) => { if (typeof p === 'string') return p; const ref = newRef(); create.push(standardSpec(ref, decl, ctx.title)); return ref })\n } else {\n const picked = await withName(name, () => ctx.dialogs.pickOne({ title: label(name, decl), query: queryOf(decl), allow_new: ctx.canCreate(decl), current: current[0] ?? null }))\n if (picked === null) return null\n if (typeof picked === 'string') bindings[name] = picked\n else { const ref = newRef(); create.push(standardSpec(ref, decl, ctx.title)); bindings[name] = ref }\n }\n continue\n }\n if (ctx.given[name] !== undefined) { bindings[name] = decl.many ? asList(ctx.given[name]) : asList(ctx.given[name])[0]; continue }\n // what the parent bound that this binding takes (a child shares its parent's data)\n const fromParent = parentData.filter((id) => { const d = known.get(id); return d !== undefined && bindingAccepts(decl, d) })\n if (decl.many && fromParent.length > 0) { bindings[name] = fromParent; continue }\n if (!decl.many && fromParent.length === 1) { bindings[name] = fromParent[0]; continue }\n const found = ctx.find(queryOf(decl)).filter((d) => bindingAccepts(decl, d))\n if (found.length === 0) {\n if (!decl.required) continue\n if (!ctx.canCreate(decl)) throw failNamed(`no ${label(name, decl)} in this Workspace yet`, 'NO_DATA')\n const ref = newRef()\n create.push(standardSpec(ref, decl, ctx.title))\n bindings[name] = decl.many ? [ref] : ref\n } else if (decl.many) {\n bindings[name] = found.map((d) => d.entity_id)\n } else if (found.length === 1) {\n bindings[name] = found[0].entity_id\n } else if (decl.required) {\n const picked = await withName(name, () => ctx.dialogs.pickOne({ title: label(name, decl), query: queryOf(decl), allow_new: ctx.canCreate(decl) }))\n if (picked === null) return null\n if (typeof picked === 'string') bindings[name] = picked\n else { const ref = newRef(); create.push(standardSpec(ref, decl, ctx.title)); bindings[name] = ref }\n }\n }\n return { bindings, create }\n}\n\n/** A standard table to create for `decl`, named after the control placed. */\nfunction standardSpec(ref: string, decl: BindingDecl, title: string): CreateSpec {\n return { ref, kind: 'standard', schema_id: decl.schema_id!, name: title || decl.title || 'Table' }\n}\n\nasync function withName<T>(binding: string, run: () => Promise<T>): Promise<T> {\n try { return await run() } catch (error) {\n if (error instanceof BindFailure && error.code === 'NEEDS_UI') throw new BindFailure(`binding ${binding} needs a choice: give it`, 'NEEDS_UI', undefined, binding)\n throw error\n }\n}\n\n/** A composite's declared steps; bindings no step settles follow the default rule. */\nexport function stepsOnBind(steps: OnBindStep[]): OnBind {\n return async (ctx) => {\n const bindings: Bound = {}\n const create: CreateSpec[] = []\n for (const step of steps) {\n const decl = ctx.decls[step.binding] ?? {}\n if (ctx.given[step.binding] !== undefined && ctx.reason === 'insert') { bindings[step.binding] = ctx.given[step.binding]; continue }\n if ('from_parent' in step) {\n const v = ctx.parent?.bound[step.from_parent]\n if (v !== undefined) bindings[step.binding] = decl.many ? asList(v) : asList(v)[0]\n } else if ('pick' in step) {\n const query = queryOf(decl)\n const title = step.title ?? label(step.binding, decl)\n const allowNew = step.allow_new !== false && ctx.canCreate(decl)\n const current = asList(ctx.given[step.binding])\n if (step.pick === 'all') bindings[step.binding] = ctx.find(query).filter((d) => bindingAccepts(decl, d)).map((d) => d.entity_id)\n else if (step.pick === 'many') {\n const picked = await withName(step.binding, () => ctx.dialogs.pickMany({ title, query, preselect: current.length ? current : 'none', allow_new: allowNew }))\n if (picked === null) return null\n bindings[step.binding] = picked.map((p) => { if (typeof p === 'string') return p; const ref = newRef(); create.push(standardSpec(ref, decl, ctx.title)); return ref })\n } else {\n const picked = await withName(step.binding, () => ctx.dialogs.pickOne({ title, query, allow_new: allowNew, current: current[0] ?? null }))\n if (picked === null) return null\n if (typeof picked === 'string') bindings[step.binding] = decl.many ? [picked] : picked\n else { const ref = newRef(); create.push(standardSpec(ref, decl, ctx.title)); bindings[step.binding] = decl.many ? [ref] : ref }\n }\n } else {\n const missing = ctx.find(queryOf(decl)).filter((d) => bindingAccepts(decl, d)).length === 0\n if ((step.when ?? 'missing') === 'missing' && !missing) continue\n const ref = newRef()\n const c = step.create\n create.push('standard' in c ? { ref, kind: 'standard', schema_id: c.standard, name: label(step.binding, decl) }\n : 'table' in c ? { ref, kind: 'table', name: c.table.name, title_field_id: c.table.title_field_id, fields: c.table.fields }\n : { ref, kind: 'dir', name: c.dir.name })\n bindings[step.binding] = decl.many ? [ref] : ref\n }\n }\n // the rest by the default rule\n const rest = Object.fromEntries(Object.entries(ctx.decls).filter(([name]) => bindings[name] === undefined))\n if (Object.keys(rest).length > 0) {\n const more = await defaultOnBind({ ...ctx, decls: rest })\n if (more === null) return null\n Object.assign(bindings, more.bindings)\n create.push(...more.create)\n }\n return { bindings, create }\n }\n}\n\nconst missingOf = (decls: Record<string, BindingDecl>, bound: Bound) =>\n Object.entries(decls).filter(([name, d]) => d.required && asList(bound[name]).length === 0).map(([name, d]) => label(name, d))\n\n/** The default `on_init_control`: ready when this control and its children have their required bindings. */\nexport const defaultOnInit: OnInit = async (ctx) => {\n const own = missingOf(ctx.decls, ctx.bound)\n if (own.length > 0) return `${ctx.title}: ${own.join(', ')} not bound`\n const waiting = ctx.children.filter((c) => !c.ready)\n return waiting.length > 0 ? `not ready: ${waiting.map((c) => `${c.title} (${c.missing.join(', ')})`).join('; ')}` : true\n}\n\n/** Run both events over a placement; the `then` actions run after the host's Commit. */\nexport async function resolveBindings(root: BindNode, host: BindHost): Promise<BindOutcome> {\n const schemas = host.standardSchemas ?? STANDARD_SCHEMAS\n const dialogs = host.no_ui ? noUiDialogs() : host.dialogs\n const results = new Map<string, BindResult>()\n const then: { node: string; action: string }[] = []\n const visit = async (node: BindNode, parent: { decls: Record<string, BindingDecl>; bound: Bound } | null): Promise<ChildState> => {\n const ctx: BindCtx = {\n reason: host.reason, no_ui: host.no_ui, node: node.id, title: node.title, decls: node.decls, given: node.given ?? {}, parent,\n find: host.find, canCreate: (d) => Boolean(d.schema_id && schemas.includes(d.schema_id)), dialogs,\n }\n const run: OnBind = typeof node.onBind === 'function' ? node.onBind : Array.isArray(node.onBind) ? stepsOnBind(node.onBind) : defaultOnBind\n let result: BindResult | null\n try { result = await run(ctx) } catch (error) {\n if (error instanceof BindFailure) throw new BindFailure(error.message, error.code, error.node ?? node.id, error.binding)\n throw error\n }\n if (result === null) throw new BindFailure(`${node.title}: cancelled`, 'CANCELLED', node.id)\n result = checkBindResult(result, node.decls, node.id)\n results.set(node.id, result)\n const children: ChildState[] = []\n for (const child of node.children) children.push(await visit(child, { decls: node.decls, bound: result.bindings }))\n const init: OnInit = typeof node.onInit === 'function' ? node.onInit : defaultOnInit\n const steps = Array.isArray(node.onInit) ? node.onInit : []\n const verdict = await init({ reason: host.reason, no_ui: host.no_ui, node: node.id, title: node.title, decls: node.decls, bound: result.bindings, children, dialogs })\n if (verdict !== true) throw new BindFailure(verdict, 'NOT_READY', node.id)\n for (const step of steps) if ('then' in step) then.push({ node: node.id, action: step.then.action })\n return { node: node.id, title: node.title, ready: true, missing: [] }\n }\n try {\n await visit(root, host.parent ?? null)\n return { ok: true, results, then }\n } catch (error) {\n if (error instanceof BindFailure) return { ok: false, error }\n throw error\n }\n}\n\n/** The operations of what a placement creates, ids for its refs: `name(spec)` gives a free name in the folder, `orderKey()`\n * the next key there. */\nexport function createOps(results: Map<string, BindResult>, opts: { folderId: string; newId: () => string; orderKey: () => string; freeName: (name: string) => string; locale?: 'zh' | 'en' }): { ops: Op[]; ids: Record<string, string> } {\n const ops: Op[] = []\n const ids: Record<string, string> = {}\n for (const result of results.values()) {\n for (const spec of result.create) {\n const entity_id = opts.newId()\n ids[spec.ref] = entity_id\n const base = { entity_id, parent_id: opts.folderId, order_key: opts.orderKey(), name: opts.freeName(spec.name) }\n if (spec.kind === 'standard') {\n const kind = spec.schema_id === TODO_SCHEMA_ID ? 'todo' : spec.schema_id === CALENDAR_SCHEMA_ID ? 'calendar' : null\n if (!kind) throw new BindFailure(`cannot create a table of ${spec.schema_id}`, 'INVALID')\n ops.push(standardTableOp(kind, { ...base, locale: opts.locale }))\n } else if (spec.kind === 'table') {\n ops.push({ op: 'entity.create', type_id: 'buckyos.table-source', ...base, payload: { fields: spec.fields, ...(spec.title_field_id ? { title_field_id: spec.title_field_id } : {}) } })\n } else {\n ops.push({ op: 'entity.create', type_id: 'buckyos.dir', ...base, payload: { members: {} } })\n }\n }\n }\n return { ops, ids }\n}\n\n/** A control's `payload.bindings` from a result: a list for a `many` binding (none bound: left out). */\nexport function bindingsPayload(bound: Bound, decls: Record<string, BindingDecl>, ids: Record<string, string>): Record<string, Json> {\n const out: Record<string, Json> = {}\n for (const [name, value] of Object.entries(bound)) {\n const list = asList(value).map((id) => ({ entity_id: ids[id] ?? id }))\n if (decls[name]?.many || Array.isArray(value)) { if (list.length > 0) out[name] = list }\n else if (list[0]) out[name] = list[0]\n }\n return out\n}\n\n/** The ids a binding names (an outline's `bindings` value, one or a list). */\nexport function boundIds(value: string | string[] | null | undefined): string[] {\n return value === null || value === undefined ? [] : Array.isArray(value) ? value : [value]\n}\n\n/** Problems of declared steps (component.json manifest 5): `on_bind` / `on_init_control`, against the bindings and\n * actions the control declares. */\nexport function checkBindSteps(onBind: unknown, onInit: unknown, decls: Record<string, BindingDecl>, actions: string[]): string[] {\n const out: string[] = []\n if (onBind !== undefined) {\n if (!Array.isArray(onBind) || onBind.length > 16) out.push('on_bind: at most 16 steps')\n else for (const [i, raw] of onBind.entries()) {\n const s = raw as Record<string, unknown>\n const where = `on_bind[${i}]`\n if (!s || typeof s !== 'object' || typeof s.binding !== 'string') { out.push(`${where}: names a binding`); continue }\n const decl = decls[s.binding]\n if (!decl) { out.push(`${where}: ${s.binding} is not a declared binding`); continue }\n const kinds = ['pick', 'from_parent', 'create'].filter((k) => k in s)\n if (kinds.length !== 1) { out.push(`${where}: one of pick, from_parent, create`); continue }\n if ('pick' in s && !['one', 'many', 'all'].includes(String(s.pick))) out.push(`${where}: pick is one, many or all`)\n if ('pick' in s && s.pick !== 'one' && !decl.many) out.push(`${where}: ${s.binding} takes one`)\n if ('from_parent' in s && typeof s.from_parent !== 'string') out.push(`${where}: from_parent names a binding of the parent`)\n if ('create' in s) {\n const c = s.create as Record<string, unknown> | null\n const which = c && typeof c === 'object' ? ['standard', 'table', 'dir'].filter((k) => k in c) : []\n if (which.length !== 1) out.push(`${where}: create one of standard, table, dir`)\n else if (which[0] === 'standard' && !STANDARD_SCHEMAS.includes(String(c!.standard))) out.push(`${where}: no standard table ${String(c!.standard)}`)\n else if (which[0] === 'table' && (!Array.isArray((c!.table as Record<string, unknown>)?.fields) || typeof (c!.table as Record<string, unknown>)?.name !== 'string')) out.push(`${where}: create.table needs name and fields`)\n else if (which[0] === 'dir' && typeof (c!.dir as Record<string, unknown>)?.name !== 'string') out.push(`${where}: create.dir needs name`)\n if (s.when !== undefined && s.when !== 'missing' && s.when !== 'always') out.push(`${where}: when is missing or always`)\n }\n }\n }\n if (onInit !== undefined) {\n if (!Array.isArray(onInit) || onInit.length > 16) out.push('on_init_control: at most 16 steps')\n else for (const [i, raw] of onInit.entries()) {\n const s = raw as Record<string, unknown>\n const where = `on_init_control[${i}]`\n if (s?.require === 'children') continue\n const action = (s?.then as Record<string, unknown> | undefined)?.action\n if (typeof action !== 'string') out.push(`${where}: { require: \"children\" } or { then: { action } }`)\n else if (!actions.includes(action)) out.push(`${where}: ${action} is not a declared action`)\n }\n }\n return out\n}\n"],"names":["AiwsFailure","Error","constructor","error","super","code","sub_code","detail","this","name","subCode","data","aiwsTarget","target","startsWith","path","entity_id","AIWS_COMMIT_PART_BYTES","AIWS_COMMIT_MAX_BYTES","AIWS_COMMIT_MAX_OPERATIONS","utf8","TextEncoder","jsonBytes","value","text","JSON","stringify","length","test","encode","splitCommitOperations","operations","partBytes","parts","current","size","op","bytes","push","async","commitWithParts","call","request","options","method","Array","isArray","workspace_id","epoch","idempotency_key","attempt","staged","part","_a","onPart","held","ok","digest","retryable","status","errors","_b","result","WEEKDAYS","RRuleError","message","FREQS","intIn","lo","hi","zero","n","Number","list","max","items","split","some","x","parseRRule","body","slice","trim","seen","Set","raw","eq","indexOf","toUpperCase","has","add","includes","FREQ","freq","rule","interval","wkst","INTERVAL","COUNT","UNTIL","count","until","m","exec","date","isDate","ms","Date","UTC","toISOString","untilOf","BYDAY","byDay","map","item","weekday","ordinal","keys","d","BYMONTHDAY","byMonthDay","v","BYMONTH","byMonth","BYSETPOS","bySetPos","WKST","w","formatRRule","join","_c","replace","s","y","mo","daysInMonth","isLeap","dayNumber","Math","floor","dayOf","dateOf","day","ymdOf","t","getUTCFullYear","getUTCMonth","getUTCDate","weekdayOf","formatters","Map","formatter","tz","f","get","Intl","DateTimeFormat","timeZone","hourCycle","year","month","hour","minute","second","set","isTimeZone","zonedParts","p","formatToParts","type","h","mi","offsetMs","zonedToUtc","minuteOfDay","secondOfMinute","local","first","localDay","candidates","period","startDay","out","byDayAll","day0","len","wanted","i","nth","days","k","monthDays","filter","sort","a","b","index","keep","months","sorted","periodStart","expandSeries","start","window","opts","limit","excluded","exdate","fromDay","toDay","viewerTz","kind","fromMs","durationDays","toMs","parse","utc","durationMs","untilDay","untilMs","emit","occ","original","startMs","periodsBefore","guard","seriesStartOf","values","fallbackTz","all_day","start_date","occurrenceId","recordId","ORD_ZH","ORD_EN","WD_ZH","WD_EN","MONTH_EN","isWorkdays","every","TODO_SCHEMA_ID","CALENDAR_SCHEMA_ID","SCHEDULE_WORKSPACE_NAME","SCHEDULE_TODO_ID","SCHEDULE_CALENDAR_ID","SCHEDULE_SURFACE_ID","TODO_DONE","LABELS","zh","title","due","order","done_at","ext","todo","doing","done","end","end_date","confirmed","tentative","cancelled","todo_table","calendar_table","workspace","board","en","scheduleLabel","locale","key","todoFields","l","field_id","required","id","option_id","label","nullable","calendarFields","standardTableOp","args","type_id","parent_id","order_key","schema_id","payload","title_field_id","fields","DIGITS","isOrderKey","endsWith","midpoint","da","db","orderKeyBetween","padEnd","j","min","after","counter","newRecordId","prefix","rand","random","toString","padStart","now","setValuesOps","sourceId","row","changes","unset","field","Object","entries","cell","record_id","expect","rev","revs","source_id","insertRecordOp","records","r","fromEntries","deleteRecordsOp","rows","canonicalOriginal","isFinite","originals","extOf","e","todoItem","sortTodos","localeCompare","todoAddOps","input","place","before","pop","ops","todoCompleteOps","reopenStatus","todoMoveOps","to","was","todoUpdateOps","ext_merge","orderAt","afterKey","rowTimes","endDate","allDay","startDate","NaN","endMs","addDays","daysBetween","occurrenceOf","times","extra","recurring","override","agentWritten","overlaps","o","from","localDate","format","viewerTimeZone","resolvedOptions","calendarOccurrences","overrides","rid","recurrence_id","master","byId","Boolean","duration","shift","rrule","occs","occurrences","sortKey","eventAddOps","timesChanges","overridesOf","masterId","shiftOriginal","deltaMs","deltaDays","iso","isoShift","eventEditOps","change","scope","ctx","newId","fieldChanges","next","masterTimes","masterExt","rule_text","covered_until","maintenance","base","round","isFirst","seriesTimes","nextRule","abs","shiftRule","fc","extOut","oext","String","headRule","tailRule","headExt","headEx","tailExt","tr","tailEx","eventDeleteOps","own","head","gone","ROWS_PAGE","failureOf","c","conflicts","selector","_d","findOccurrence","at","find","scheduleBoardOps","folder","system","surface_id","layout","mode","content_folder_id","placement","bindings","events","config","view","BindFailure","node","binding","STANDARD_SCHEMAS","asList","decl","bindingAccepts","accepts","queryOf","noUiDialogs","fail","pickOne","pickMany","confirm","refSeq","newRef","checkBindResult","decls","bad","isObject","created","create","refs","ref","used","many","ids","unused","defaultOnBind","parentData","parent","bound","flatMap","known","failNamed","reason","given","no_ui","picked","withName","dialogs","query","preselect","allow_new","canCreate","standardSpec","fromParent","found","run","stepsOnBind","steps","step","from_parent","allowNew","pick","missing","when","standard","table","dir","rest","more","assign","defaultOnInit","waiting","children","ready","rpcClient","params","ensure","time","info","getUserState","setUserState","resolve","reference","resolvePath","read","readMeta","as","readBody","listEntities","findEntities","textQuery","sql","sourceQuery","outline","prepare","commit","getSubmission","getChanges","after_seq","touchedOnly","waitChanges","exportDoc","self_contained","include_notes","assetImportObject","source","controlsList","controlsDescribe","controlsImport","controlsExport","extBuild","extExport","entity_ids","purpose","extInstall","extPack","pkg","templates","package","extUpgrade","extExportTemplate","extCreateFromTemplate","extListLibrary","extUninstall","pkg_id","extLibraryBundle","idents","extImport","runStart","program","runGet","run_id","runList","wish_id","runClaim","claim_token","executor","runHeartbeat","progress","runReport","report","runRollback","session_id","runCancel","aiws","handle","ws","calendar","have","deleted","commitTo","idConflict","origin","protocol_version","page","tables","max_rows","record","content","todos","includeDone","addTodo","pos","findIndex","completeTodo","updateTodo","moveTodo","others","anchor","removeTodos","recordIds","Promise","all","addEvent","occurrence","editEvent","deleteEvent","workspaceId","encodeObjQueryComponent","canonicalJson","version","objServiceUrl","normalizeObjectUrl","onBind","onInit","actions","where","which","require","action","then","results","spec","folderId","orderKey","freeName","members","wd","xs","mday","on","minutes","url","parsed","parseObjectUrl","segments","objectSegments","host","last","root","schemas","standardSchemas","visit","child","init","verdict"],"mappings":"yDASO,MAAMA,UAAoBC,MAI/B,WAAAC,CAAYC,GACVC,MAAM,GAAGD,EAAME,OAAOF,EAAMG,SAAW,IAAIH,EAAMG,WAAa,OAAOH,EAAMI,UAC3EC,KAAKC,KAAO,cACZD,KAAKH,KAAOF,EAAME,KAClBG,KAAKE,QAAUP,EAAMG,SACrBE,KAAKG,KAAOR,EAAMQ,IACpB,EAgDK,SAASC,EAAWC,GACzB,OAAOA,EAAOC,WAAW,MAAQD,EAAOC,WAAW,KAAO,CAAEC,KAAMF,GAAW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,CACA,GAAe,OAAX2D,EAAuB,MAAA,IAAIkY,GAAY,GAAGC,EAAKxM,mBAAoB,YAAawM,EAAK/K,IACzFpN,EAASkZ,GAAgBlZ,EAAQmY,EAAKgB,MAAOhB,EAAK/K,IAC1CsW,EAAApd,IAAI6R,EAAK/K,GAAIpN,GACrB,MAAMmc,EAAyB,GAC/B,IAAA,MAAW6I,KAAS7M,EAAKgE,SAAUA,EAAS3d,WAAWumB,EAAMC,EAAO,CAAE7L,MAAOhB,EAAKgB,MAAOc,MAAOja,EAAO8X,YACvG,MAAMmN,EAAsC,mBAAhB9M,EAAKgL,OAAwBhL,EAAKgL,OAASlH,GACjEb,EAAQrc,MAAMC,QAAQmZ,EAAKgL,QAAUhL,EAAKgL,OAAS,GACnD+B,QAAgBD,EAAK,CAAE5K,OAAQqK,EAAKrK,OAAQE,MAAOmK,EAAKnK,MAAOpC,KAAMA,EAAK/K,GAAIzB,MAAOwM,EAAKxM,MAAOwN,MAAOhB,EAAKgB,MAAOc,MAAOja,EAAO8X,SAAUqE,WAAUzB,YAC5J,IAAgB,IAAZwK,EAAkB,MAAM,IAAIhN,GAAYgN,EAAS,YAAa/M,EAAK/K,IACvE,IAAA,MAAWiO,KAAQD,EAAW,SAAUC,GAAWoI,EAAAjlB,KAAK,CAAE2Z,KAAMA,EAAK/K,GAAIoW,OAAQnI,EAAKoI,KAAKD,SACpF,MAAA,CAAErL,KAAMA,EAAK/K,GAAIzB,MAAOwM,EAAKxM,MAAOyQ,OAAO,EAAMX,QAAS,GAAG,EAElE,IAEF,aADMsJ,EAAMH,EAAMF,EAAK1K,QAAU,MAC1B,CAAEta,IAAI,EAAMgkB,UAASD,cACrBpnB,GACP,GAAIA,aAAiB6b,GAAoB,MAAA,CAAExY,IAAI,EAAOrD,SAChD,MAAAA,CACR,CACF"}
@@ -272,8 +272,8 @@ class AiWorkspaceClient {
272
272
  runStart(workspace_id, program, params, idempotency_key) {
273
273
  return this.call("proc.start", { workspace_id, program, params, idempotency_key });
274
274
  }
275
- runGet(workspace_id, run_id, choices) {
276
- return this.call("proc.get", { workspace_id, run_id, ...choices ? { choices } : {} });
275
+ runGet(workspace_id, run_id) {
276
+ return this.call("proc.get", { workspace_id, run_id });
277
277
  }
278
278
  runList(workspace_id, wish_id, limit) {
279
279
  return this.call("proc.list", { workspace_id, ...wish_id ? { wish_id } : {}, ...limit ? { limit } : {} });
@@ -287,8 +287,10 @@ class AiWorkspaceClient {
287
287
  runReport(workspace_id, report) {
288
288
  return this.call("proc.report", { workspace_id, ...report });
289
289
  }
290
- runApply(workspace_id, run_id, plan_digest, session_id) {
291
- return this.call("proc.apply", { workspace_id, run_id, plan_digest, ...session_id ? { session_id } : {} });
290
+ /** Take back what the run wrote: only the record that is current for its stage. When the outcome was changed since,
291
+ * nothing is written and the answer is `status: "needs_confirm"` with what would be `lost`; again with `confirm`. */
292
+ runRollback(workspace_id, run_id, opts = {}) {
293
+ return this.call("proc.rollback", { workspace_id, run_id, ...opts.confirm ? { confirm: true } : {}, ...opts.session_id ? { session_id: opts.session_id } : {} });
292
294
  }
293
295
  runCancel(workspace_id, run_id) {
294
296
  return this.call("proc.cancel", { workspace_id, run_id });
@@ -2232,4 +2234,4 @@ export {
2232
2234
  ymdOf as y,
2233
2235
  zonedParts as z
2234
2236
  };
2235
- //# sourceMappingURL=aiws_bind-3b874f77.mjs.map
2237
+ //# sourceMappingURL=aiws_bind-0885ff99.mjs.map