@openfairygui/backend 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,16 @@
1
+ ---
2
+ name: openfairygui
3
+ description: Navigate an installed OpenFairyGUI SDK, CLI or MCP server for FairyGUI project inspection, precise queries, revision-checked authoring and diagnosis. Use the installed version's offline documentation and generated schemas before constructing operations.
4
+ ---
5
+
6
+ # OpenFairyGUI installed-version navigation
7
+
8
+ Use this skill for OpenFairyGUI project workflows, not unrelated GUI frameworks.
9
+
10
+ 1. Locate the intended project's installed `ofgui` binary (local `node_modules/.bin/ofgui`, `ofgui.cmd` on Windows) or its configured MCP server. Do not use `npx`, install, upgrade, or fall back to a global executable automatically. If missing, report the missing installation and ask the host to choose it.
11
+ 2. Read `ofgui --version` and `ofgui docs ls --json`; compare the CLI and documentation package versions. In MCP, read `openfairygui://docs/index` and the server's version. Report mismatches before authoring; do not use online latest-version docs as the installed contract.
12
+ 3. Read `ofgui docs cat workflow` or the index's workflow URI. Use `docs find`, `docs schema <kind>`, `docs cat methods/<method>` and `docs diagnostic <code>` (or the listed MCP URIs) for exact current inputs and recovery boundaries. Never copy or guess operation grammar from this skill.
13
+ 4. Follow outline → exact query → plan → preflight → authorized apply → validate → authorized save → reread. Revision changes require refreshing and replanning, not blind retries. Read-only requests do not authorize opening locked file sessions, mutations or repairs.
14
+ 5. Use `ofgui doctor [project] --json` for read-only installation/project diagnosis. Missing bytes/decoders and path/session failures may require host action. Preserve unsaved work and report incomplete checks honestly.
15
+
16
+ The commands above navigate this installed corpus; they do not grant permission to change projects, install dependencies or widen filesystem access.
@@ -0,0 +1,50 @@
1
+ # Installed OpenFairyGUI workflow
2
+
3
+ This is a minimal offline companion, not the full website. Read `ofgui docs ls --json` for the installed package version, contract version, capability schema version and digest. Use the project's installed `ofgui`/`ofgui-mcp`, not a global executable or an online latest-version lookup. A mismatched installation must be reconciled by the host before editing.
4
+
5
+ ## Discover the current contract
6
+
7
+ - `ofgui docs find "selector" --json` searches this installed corpus.
8
+ - `ofgui docs cat contracts --json` lists Core operations and Backend/MCP mappings.
9
+ - `ofgui docs schema setDisplayNodeProps --json` reads one self-contained operation schema.
10
+ - `ofgui docs schema cli/validate --json` reads the installed CLI output schema; `cli/docs cat` is a valid exact document ID for the nested command.
11
+ - `ofgui docs cat methods/queryEntity --json` reads precise input/output wire schemas.
12
+ - `ofgui docs diagnostic stale_write --json` reads recovery guidance.
13
+ - MCP `resources/read` at `openfairygui://docs/index` provides the same index and content URIs. MCP is local stdio, not an assumed HTTP port.
14
+
15
+ The generated schemas describe JSON wire structure and input budgets, not semantic validity. Native SDK byte fields remain Uint8Array; MCP transports declared byte fields as integer arrays. Arbitrary extension data is not converted. Host objects/functions are omitted from MCP wire schemas; use SDK declarations for host injection, not guessed JSON fields.
16
+
17
+ All CLI JSON uses `{schemaVersion:1,command,success:true,result}` or `{schemaVersion:1,command,success:false,error:{code,message},result?}`. Documentation version/index/body fields are inside `result`; read `result.text` for document content. Invalid/incomplete validate and doctor responses retain their full report under `result`. Help/version are text; other JSON-mode stdout contains exactly one document and human logs use stderr. Exit codes: 0 success, 1 workflow failure, 2 arguments, 3 incomplete validation. CLI owns envelopes, not new workflow semantics.
18
+
19
+ ## Edit safely
20
+
21
+ 1. Read capabilities. Existing projects use openSession (with host authorization and a lifetime lock); openProjectSession accepts a host-supplied authoritative UAM, not a shortcut around lossy file-session guards.
22
+ 2. Read getProjectOutline to discover exact identities, then queryEntity for the relevant current properties and actual revision. Capabilities list the supported read.entityQuery.kinds: project, package, resource, component, displayNode, controller and transition. Project queries use target {kind:"project"} without a selector; package queries use {kind:"package",selector:{packageId}}. Both return identity and complete entity.properties.settings. Controllers use packageId + componentResourceId + controllerName; transitions use packageId + componentResourceId + transitionName. Names are exact and component-scoped; duplicates fail as ambiguous. Controller snapshots include pages/actions; transition snapshots include items. Gears are already included in displayNode snapshots. Fixed projections exclude source bytes; budget failures require host inspection.
23
+ 3. Read the operation and method schemas. Plan the smallest authorized batch using current identifiers and expectedRevision.
24
+ 4. preflightTransaction executes on an isolated snapshot and discards it. Inspect projectedRevision, impact.entities (exact identities and changed fields, including reference normalization), impact.files (ProjectWriter model diff, not a disk write plan) and persistence.nextAction. The diff starts at the current revision, not the last save. It contains no source bytes. Summary overflow or serialization failure returns transaction_preview_failed without a partial result. No revision is reserved; writeVerified is always false. It does not save files or guarantee later apply/save/publish.
25
+ 5. Only when authorized, applyTransaction with the planned batch and expectedRevision. On stale_write, refresh and replan; never blindly substitute a newer revision.
26
+ 6. validateSession checks the new authoritative state. A successful response can contain an invalid or incomplete validation report; require status valid and complete true before treating validation as passed.
27
+ 7. When authorized, saveSession checks revision independently and writes the original project only. Keep path policy, UAM fidelity and rollback guards. Close the session only after handling unsaved changes. Read saved output again when disk round-trip is part of acceptance.
28
+
29
+ updateProjectSettings and updatePackageSettings replace complete settings snapshots. Copy the corresponding query's entity.properties.settings, change only requested fields, retain other nested settings and optional fields, and submit the complete settings with the queried revision. Package updates also require the original packageId selector. Settings queries share the same response budgets as other entity kinds.
30
+
31
+ updateController and updateTransition replace complete snapshots, not partial patches. Copy the queried entity.properties, change only the requested fields, preserve page IDs/remarks/actions, item order/targets, settings and references, and submit the original selector with the queried revision. A stale_write requires refreshing and replanning the full snapshot for all these replacement operations. Querying does not validate references or grant permission to edit them.
32
+
33
+ ## Diagnose without repair
34
+
35
+ `ofgui doctor --json` checks installed CLI/documentation versions, the Node Backend capability snapshot, in-memory Sharp PNG/JPEG encoding and pixel decoding, and temporary-directory access flags. `ofgui doctor <project-directory-or-fairy-file> --json` additionally runs existing Node project validation, including source reads and available image decoding. Optional `--output-dir <directory>` checks an explicit destination or its nearest existing ancestor, without creating it. Directory checks return the absolute requested `path`, link-resolved `inspectedPath` and `exists` (null when unknown); files, dangling links and access errors fail. The temporary directory must exist. It opens no Backend session, creates no lock, installs nothing, writes no probe files and changes no configuration.
36
+
37
+ Exit 0 means the requested checks completed; exit 1 means a detected error; exit 2 means invalid arguments; exit 3 means native image capability is unavailable/failed or project validation is incomplete. Inspect result.checks, result.errors and result.project. Without a project, its source bytes are not checked. Access flags do not prove effective ACL permissions, available space, later writes/rename/rollback or continued access. The capability manifest remains a declaration; a successful doctor does not prove publish/restore or runtime rendering. Plugins and configured output destinations are not executed or checked automatically; only explicit --output-dir is inspected. This product doctor does not inspect Git, pnpm, repository builds or fixture submodules; maintainers use pnpm repo:doctor for those.
38
+
39
+ Read diagnostic guides for ownership and recovery boundaries. Every formal Core/Backend diagnostic code is covered; shared codes list all `owners`, while response `owner` identifies the actual source. Missing bytes/decoders, rejected paths and expired sessions require host action; do not invent repair/hydration tools, widen roots, discard unsaved work, or turn incomplete validation into success. Invalid/unsupported operations require schema-based replanning, live locks cannot be removed, and write failures require preserving dirty state and inspecting actual files.
40
+
41
+ ## Publish and recover trusted local artifacts
42
+
43
+ Publishing and restoration are external Node-hosted workflows, not Backend session methods or general MCP editing tools. The host must authorize input and output directories independently. They require the native image capability; do not rename binary extensions to imitate a different target profile.
44
+
45
+ - `ofgui publish <project> --output <release-directory> --project-type layabox --json` publishes the current saved project. `--output` overrides runtime artifact destinations; configured code generation still uses its own destinations and project plugins run as trusted local code.
46
+ - The JSON document is `{schemaVersion:1,command:"publish",success:true,result:{files:[{path,size}]}}`. Paths are final absolute paths and sizes are bytes. The Node SDK `publishNode()` returns the same `result`. The manifest records actual successful filesystem/atlas writes, including code written through the supplied publish filesystem; it excludes pre-existing untouched files, deletions and arbitrary plugin I/O outside that filesystem. It is not an inventory of everything in the output directory. Explicit runtime output is staged and rolled back on failure; separately configured code outputs and arbitrary plugin effects are not covered by that directory transaction.
47
+ - `ofgui restore <trusted-release-directory> --output <separate-project-directory> --project-type layabox --json` returns `{schemaVersion:1,command:"restore",success:true,result:{projectPath,packages:[{id,name}],warnings:[]}}`. Warnings are not a validation pass. Reread the returned projectPath and run `ofgui validate <projectPath> --json`; require valid and complete validation.
48
+ - Both artifact commands exit 0 on workflow success, 1 on workflow failure, and 2 on command syntax errors. Errors are `{schemaVersion:1,command,success:false,error:{code,message}}`, with `publish_failed`, `restore_failed` or `invalid_arguments`. In JSON mode stdout contains only this document; human/plugin output goes to stderr. Help remains human-readable. Errors do not include a claimed successful file manifest.
49
+ - Restore requires a separate directory, not a `.fairy` file. Do not force overwrite by default. `--force` replaces an existing nonempty target only after complete staged recovery; parse/image failures retain the previous target. Only trusted local artifacts are supported, not arbitrary third-party imports.
50
+ - Read `ofgui docs cat restore-limits --json` or MCP resource `openfairygui://docs/restore-limits` for the installed version's full recovery boundary. Accept readable, structurally valid supported semantics and decoded assets, not original project IDs, workspace state, unpublished resources, original filenames/extensions, controller editor selection/export flags, float32 text precision or byte-identical XML.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfairygui/backend",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "FairyGUI Headless Authoring SDK — stateful backend runtime and session services.",
5
5
  "author": "OpenFairyGUI Contributors",
6
6
  "license": "MIT",
@@ -11,7 +11,10 @@
11
11
  },
12
12
  "homepage": "https://github.com/OpenFairyGUI/OpenFairyGUI#readme",
13
13
  "bugs": {
14
- "url": "https://github.com/OpenFairyGUI/OpenFairYGUI/issues"
14
+ "url": "https://github.com/OpenFairyGUI/OpenFairyGUI/issues"
15
+ },
16
+ "engines": {
17
+ "node": ">=22"
15
18
  },
16
19
  "type": "module",
17
20
  "sideEffects": false,
@@ -29,6 +32,16 @@
29
32
  "default": "./dist/index.mjs"
30
33
  }
31
34
  },
35
+ "./docs": {
36
+ "require": {
37
+ "types": "./dist/docs.d.cts",
38
+ "default": "./dist/docs.cjs"
39
+ },
40
+ "default": {
41
+ "types": "./dist/docs.d.mts",
42
+ "default": "./dist/docs.mjs"
43
+ }
44
+ },
32
45
  "./node": {
33
46
  "require": {
34
47
  "types": "./dist/node.d.cts",
@@ -41,6 +54,7 @@
41
54
  }
42
55
  },
43
56
  "files": [
57
+ "docs/",
44
58
  "dist/",
45
59
  "src/"
46
60
  ],
@@ -52,13 +66,13 @@
52
66
  "runtime"
53
67
  ],
54
68
  "dependencies": {
55
- "@openfairygui/functions": "0.3.0",
56
- "@openfairygui/core": "0.3.0"
69
+ "@openfairygui/functions": "0.4.0",
70
+ "@openfairygui/core": "0.4.0"
57
71
  },
58
72
  "devDependencies": {
59
73
  "ava": "^7.0.0",
60
74
  "tsx": "^4.0.0",
61
- "@openfairygui/test-utils": "0.2.0-alpha.10"
75
+ "@openfairygui/test-utils": "0.3.0"
62
76
  },
63
77
  "scripts": {
64
78
  "build": "tsdown",
package/src/contracts.ts CHANGED
@@ -1,5 +1,9 @@
1
- export const BACKEND_CONTRACT_VERSION = '1.1.0-p2' as const;
2
- export const BACKEND_CAPABILITY_SCHEMA_VERSION = 3 as const;
1
+ import type { ProjectDiagnosticCode } from '@openfairygui/core';
2
+ import type { UamTransactionSupportIssueCode } from '@openfairygui/core/uam';
3
+ import type { BackendError } from './runtime.js';
4
+
5
+ export const BACKEND_CONTRACT_VERSION = '2.0.0-p2' as const;
6
+ export const BACKEND_CAPABILITY_SCHEMA_VERSION = 10 as const;
3
7
  export const BACKEND_COMPATIBILITY_POLICY = {
4
8
  incompatibleChange: 'requires contractVersion bump',
5
9
  capabilitySchemaChange: 'requires capabilitySchemaVersion bump',
@@ -13,8 +17,11 @@ export interface BackendMessage {
13
17
  message: string;
14
18
  }
15
19
 
20
+ export type BackendDiagnosticCode = BackendError['code'] | UamTransactionSupportIssueCode | ProjectDiagnosticCode;
21
+ export type BackendDiagnosticOwner = 'backend' | 'core.transaction' | 'core.validation';
22
+
16
23
  export interface BackendDiagnostic {
17
- code: string;
24
+ code: BackendDiagnosticCode;
18
25
  message: string;
19
26
  severity: 'info' | 'warning' | 'error';
20
27
  path?: string;
@@ -25,6 +32,17 @@ export interface BackendDiagnostic {
25
32
  operationKind?: string;
26
33
  opIndex?: number;
27
34
  opId?: string;
35
+ /** Present for catalogued diagnostics only; original codes and classification are preserved. */
36
+ owner?: BackendDiagnosticOwner;
37
+ docsUri?: string;
38
+ remediation?: BackendDiagnosticRemediation;
39
+ }
40
+
41
+ export interface BackendDiagnosticRemediation {
42
+ kind: 'refresh-and-replan' | 'revise-selector' | 'revise-operation' | 'host-action';
43
+ message: string;
44
+ /** A read-only starting point, never permission to retry or mutate. */
45
+ read?: { method: 'getProjectOutline'; input: { sessionId: string } };
28
46
  }
29
47
 
30
48
  export interface BackendResponseMeta {
@@ -0,0 +1,181 @@
1
+ import type { BackendDiagnostic, BackendDiagnosticCode, BackendDiagnosticOwner, BackendDiagnosticRemediation } from './contracts.js';
2
+
3
+ /** Shared codes list all canonical owners; responses preserve the actual reporting owner. */
4
+ export interface BackendDiagnosticGuide {
5
+ code: BackendDiagnosticCode;
6
+ owners: readonly BackendDiagnosticOwner[];
7
+ remediation: Omit<BackendDiagnosticRemediation, 'read'>;
8
+ }
9
+
10
+ const selector = {
11
+ kind: 'revise-selector',
12
+ message: 'Read the current outline and query the relevant entity. Use its exact identifiers, inspect the reported selector path, then rebuild and preflight the transaction. Do not guess identifiers or retry the unchanged transaction.',
13
+ } as const;
14
+ const source = {
15
+ kind: 'host-action',
16
+ message: 'Ask the host to inspect the reported source and hydrate its bytes through project I/O or import. Preserve unsaved work; reopening disk state can discard it. No session hydration/repair API is exposed. Revalidate and replan after the host has supplied a complete project.',
17
+ } as const;
18
+ const path = {
19
+ kind: 'host-action',
20
+ message: 'Ask the host to review the attempted path and authorized project root. saveSession only writes the original project; it is not Save As. Do not widen allowed roots or bypass path checks. A separately authorized export may use materializeSession.',
21
+ } as const;
22
+
23
+ const unsupported = { kind: 'revise-operation', message: "Read the operation schema, capabilities and reported target kind/field. Stop unsupported work or replan using supported operations with equivalent intended semantics. Never silently drop fields or objects to make a transaction pass." } as const;
24
+ const payload = { kind: 'revise-operation', message: "Inspect the diagnostic path and current operation schema or UAM issues. Correct values, required fields and indices against exact queried entities, then preflight. Do not invent defaults or coerce away invalid data." } as const;
25
+ const unchanged = { kind: 'refresh-and-replan', message: "Query current settings/entity and compare with the request. If already satisfied, report no change; otherwise replan from the current revision. Do not manufacture a mutation or resubmit the same no-op." } as const;
26
+ const duplicate = { kind: 'revise-operation', message: "Query current entities and resolve the conflicting ID, name or page explicitly. Choose an unused value only when authorized by the intended edit, then preflight. Never overwrite or delete an existing entity to clear the conflict." } as const;
27
+ const references = { kind: 'revise-operation', message: "Query affected entities and references before editing, moving or removing anything. Replan intended dependent changes together and preflight. Do not delete dependent objects or strip references without authorization." } as const;
28
+ const project = { kind: 'host-action', message: "Inspect the project path and validation diagnostics with the host. Correct source XML/settings or unsupported geometry using authoritative project data; preserve originals and unsaved work before reopening or validating. Do not guess missing structure or discard rejected content." } as const;
29
+ const capability = { kind: 'host-action', message: "Read capability/error details. Ask the host to provide the required filesystem, decoder or complete UAM adapter. Preserve the session and unsaved work; do not substitute a lossy path or bypass checks." } as const;
30
+ const write = { kind: 'host-action', message: "Preserve the dirty session and inspect the error, actual target files and permissions with the host. Partial writes may have changed files: verify or recover them before a newly authorized save. Do not clear dirty state, discard memory or blindly retry." } as const;
31
+ const execution = { kind: 'host-action', message: "Inspect the execution/cache failure and current session/revision. Preserve sources and unsaved work and report the cause to the host. Replan after resolution; failed execution or cache work is not a completed edit." } as const;
32
+ const job = { kind: 'host-action', message: "Inspect the job ID and status with getJob/listJobs. Do not fabricate, restart or force-cancel a missing, terminal or non-cancellable job. Ask the host before scheduling new work; cancellation is not success." } as const;
33
+
34
+ /** Exhaustiveness and exact ownership are checked against the canonical unions. */
35
+ export const BACKEND_DIAGNOSTIC_GUIDES = [
36
+ { code: 'transaction_preview_failed', owners: ['backend'], remediation: {
37
+ kind: 'host-action',
38
+ message: 'No complete preview is available. Inspect error.reason with the host: response_budget_exceeded requires a smaller independently meaningful authorized batch; projection_failed requires inspecting the project serialization failure. Preserve the session and never treat a missing or truncated impact as approval to apply or save.',
39
+ } },
40
+ { code: 'stale_write', owners: ['backend'], remediation: {
41
+ kind: 'refresh-and-replan',
42
+ message: 'Refresh the outline and affected entities, then replan from their current revision and preflight again. A preview reserves no revision. Never replace expectedRevision and blindly retry the original transaction or save.',
43
+ } },
44
+ { code: 'entity_query_failed', owners: ['backend'], remediation: {
45
+ kind: 'host-action',
46
+ message: 'Inspect error.reason: invalid_query requires correcting the target; not_found/ambiguous requires current exact identifiers; response_budget_exceeded/non_json_value requires host inspection of the entity. Do not broaden queries or mutate data to evade the response limits.',
47
+ } },
48
+ { code: 'session_not_found', owners: ['backend'], remediation: {
49
+ kind: 'host-action',
50
+ message: 'Ask the host to confirm the runtime and project, recover any unsaved state, then explicitly open a new session if appropriate. Session IDs are runtime-local. Read its new revision and replan; never reuse an expired session or assume disk contains unsaved changes.',
51
+ } },
52
+ { code: 'path_policy_violation', owners: ['backend'], remediation: path },
53
+ { code: 'project_root_not_allowed', owners: ['backend'], remediation: path },
54
+ { code: 'invalid_package_selector', owners: ['core.transaction'], remediation: selector },
55
+ { code: 'invalid_component_selector', owners: ['core.transaction'], remediation: selector },
56
+ { code: 'invalid_resource_selector', owners: ['core.transaction'], remediation: selector },
57
+ { code: 'invalid_display_node_selector', owners: ['core.transaction'], remediation: selector },
58
+ { code: 'invalid_resource_folder_selector', owners: ['core.transaction'], remediation: selector },
59
+ { code: 'invalid_branch_selector', owners: ['core.transaction'], remediation: selector },
60
+ { code: 'invalid_gear_selector', owners: ['core.transaction'], remediation: selector },
61
+ { code: 'invalid_look_gear_selector', owners: ['core.transaction'], remediation: selector },
62
+ { code: 'selector_ambiguity', owners: ['core.transaction'], remediation: selector },
63
+ { code: 'unavailable_resource_source_bytes', owners: ['core.transaction'], remediation: source },
64
+ { code: 'missing_source', owners: ['core.validation'], remediation: source },
65
+ { code: 'unreadable_source', owners: ['core.validation'], remediation: source },
66
+ { code: 'decode_capability_unavailable', owners: ['core.validation'], remediation: {
67
+ kind: 'host-action',
68
+ message: 'Validation is incomplete, not passed. Inspect whether source bytes are unloaded or a decoder is unavailable. Ask the host to hydrate sources or provide the required decoder (Node image validation uses optional Sharp), then validate again. Do not install dependencies or change the project automatically.',
69
+ } },
70
+ { code: 'session_id_conflict', owners: ['backend'], remediation: { kind: 'host-action', message: "Use getSession to inspect the existing session. Reuse it only for the intended project, or choose a new session ID; do not close another owner\\u0027s session to make room." } },
71
+ { code: 'lock_conflict', owners: ['backend'], remediation: { kind: 'host-action', message: "Another owner holds the project lock. Preserve unsaved work and ask that owner to close its session, then explicitly reopen. Never remove a live lock, force-close a peer, or bypass locking." } },
72
+ { code: 'event_cursor_invalid', owners: ['backend'], remediation: { kind: 'refresh-and-replan', message: "Read the error and getEvents cursor bounds. Request a fresh bounded event page without the invalid cursor and refresh the current outline before replanning; missing retained history is not evidence that nothing changed." } },
73
+ { code: 'corrupt_source', owners: ["core.validation"], remediation: source },
74
+ { code: 'unsupported_operation', owners: ["core.transaction"], remediation: unsupported },
75
+ { code: 'transaction_unsupported', owners: ["core.transaction"], remediation: unsupported },
76
+ { code: 'unsupported_display_node_kind', owners: ["core.transaction"], remediation: unsupported },
77
+ { code: 'unsupported_cross_package_image_ref', owners: ["core.transaction"], remediation: unsupported },
78
+ { code: 'unsupported_gear_kind', owners: ["core.transaction"], remediation: unsupported },
79
+ { code: 'unsupported_resource_mutation', owners: ["core.transaction"], remediation: unsupported },
80
+ { code: 'unsupported_display_node_mutation', owners: ["core.transaction"], remediation: unsupported },
81
+ { code: 'unsupported_text_field_target', owners: ["core.transaction"], remediation: unsupported },
82
+ { code: 'unsupported_display_node_field', owners: ["core.transaction"], remediation: unsupported },
83
+ { code: 'unsupported_operation_batch', owners: ["core.transaction"], remediation: unsupported },
84
+ { code: 'unsupported_resource_kind', owners: ["core.transaction","core.validation"], remediation: unsupported },
85
+ { code: 'invalid_project_settings', owners: ["core.transaction"], remediation: payload },
86
+ { code: 'invalid_package_settings', owners: ["core.transaction"], remediation: payload },
87
+ { code: 'invalid_display_node_payload', owners: ["core.transaction"], remediation: payload },
88
+ { code: 'invalid_resource_name', owners: ["core.transaction"], remediation: payload },
89
+ { code: 'invalid_resource_path', owners: ["core.transaction"], remediation: payload },
90
+ { code: 'invalid_resource_folder_path', owners: ["core.transaction"], remediation: payload },
91
+ { code: 'invalid_resource_folder_atlas', owners: ["core.transaction"], remediation: payload },
92
+ { code: 'invalid_attach_index', owners: ["core.transaction"], remediation: payload },
93
+ { code: 'invalid_controller_payload', owners: ["core.transaction"], remediation: payload },
94
+ { code: 'invalid_transition_payload', owners: ["core.transaction"], remediation: payload },
95
+ { code: 'invalid_look_gear_payload', owners: ["core.transaction"], remediation: payload },
96
+ { code: 'invalid_gear_payload', owners: ["core.transaction"], remediation: payload },
97
+ { code: 'invalid_resource_payload', owners: ["core.transaction"], remediation: payload },
98
+ { code: 'invalid_resource_bytes', owners: ["core.transaction"], remediation: payload },
99
+ { code: 'invalid_movie_clip_jta', owners: ["core.transaction"], remediation: payload },
100
+ { code: 'invalid_resource_index', owners: ["core.transaction"], remediation: payload },
101
+ { code: 'invalid_branch_name', owners: ["core.transaction"], remediation: payload },
102
+ { code: 'invalid_package_payload', owners: ["core.transaction"], remediation: payload },
103
+ { code: 'invalid_package_index', owners: ["core.transaction"], remediation: payload },
104
+ { code: 'invalid_component_payload', owners: ["core.transaction"], remediation: payload },
105
+ { code: 'invalid_component_index', owners: ["core.transaction"], remediation: payload },
106
+ { code: 'invalid_component_move', owners: ["core.transaction"], remediation: payload },
107
+ { code: 'invalid_uam', owners: ["core.transaction","core.validation"], remediation: payload },
108
+ { code: 'project_settings_unchanged', owners: ["core.transaction"], remediation: unchanged },
109
+ { code: 'package_settings_unchanged', owners: ["core.transaction"], remediation: unchanged },
110
+ { code: 'display_node_props_unchanged', owners: ["core.transaction"], remediation: unchanged },
111
+ { code: 'resource_folder_atlas_unchanged', owners: ["core.transaction"], remediation: unchanged },
112
+ { code: 'duplicate_look_gear_controller', owners: ["core.transaction"], remediation: duplicate },
113
+ { code: 'duplicate_transition_name', owners: ["core.transaction"], remediation: duplicate },
114
+ { code: 'duplicate_look_gear_state_page', owners: ["core.transaction"], remediation: duplicate },
115
+ { code: 'duplicate_gear_controller', owners: ["core.transaction"], remediation: duplicate },
116
+ { code: 'duplicate_gear_state_page', owners: ["core.transaction"], remediation: duplicate },
117
+ { code: 'duplicate_branch_name', owners: ["core.transaction"], remediation: duplicate },
118
+ { code: 'duplicate_component_id', owners: ["core.transaction"], remediation: duplicate },
119
+ { code: 'resource_folder_conflict', owners: ["core.transaction"], remediation: duplicate },
120
+ { code: 'duplicate_resource_id', owners: ["core.transaction","core.validation"], remediation: duplicate },
121
+ { code: 'duplicate_package_id', owners: ["core.transaction","core.validation"], remediation: duplicate },
122
+ { code: 'duplicate_package_name', owners: ["core.transaction","core.validation"], remediation: duplicate },
123
+ { code: 'resource_folder_not_empty', owners: ["core.transaction"], remediation: references },
124
+ { code: 'branch_not_empty', owners: ["core.transaction"], remediation: references },
125
+ { code: 'branch_referenced', owners: ["core.transaction"], remediation: references },
126
+ { code: 'invalid_resource_reference', owners: ["core.transaction"], remediation: references },
127
+ { code: 'invalid_component_reference', owners: ["core.transaction"], remediation: references },
128
+ { code: 'invalid_group_reference', owners: ["core.transaction"], remediation: references },
129
+ { code: 'package_referenced', owners: ["core.transaction"], remediation: references },
130
+ { code: 'component_referenced', owners: ["core.transaction"], remediation: references },
131
+ { code: 'component_has_package_dependencies', owners: ["core.transaction"], remediation: references },
132
+ { code: 'dangling_resource_reference', owners: ["core.validation"], remediation: references },
133
+ { code: 'invalid_project_xml', owners: ["core.validation"], remediation: project },
134
+ { code: 'invalid_package_xml', owners: ["core.validation"], remediation: project },
135
+ { code: 'invalid_branch_package_xml', owners: ["core.validation"], remediation: project },
136
+ { code: 'invalid_component_xml', owners: ["core.validation"], remediation: project },
137
+ { code: 'invalid_project_value', owners: ["core.validation"], remediation: project },
138
+ { code: 'desktop_incompatible_geometry', owners: ["core.validation"], remediation: project },
139
+ { code: 'invalid_settings_json', owners: ["core.validation"], remediation: project },
140
+ { code: 'path_collision', owners: ["core.validation"], remediation: path },
141
+ { code: 'unsafe_path', owners: ["core.validation"], remediation: path },
142
+ { code: 'capability_unavailable', owners: ["backend"], remediation: capability },
143
+ { code: 'uam_fidelity_unsupported', owners: ["backend"], remediation: capability },
144
+ { code: 'save_partial_failure', owners: ["backend"], remediation: write },
145
+ { code: 'write_failed', owners: ["backend"], remediation: write },
146
+ { code: 'project_open_failed', owners: ["backend"], remediation: project },
147
+ { code: 'materialize_validation_failed', owners: ["backend"], remediation: project },
148
+ { code: 'execution_failure', owners: ["core.transaction"], remediation: execution },
149
+ { code: 'cache_refresh_failed', owners: ["backend"], remediation: execution },
150
+ { code: 'job_not_found', owners: ["backend"], remediation: job },
151
+ { code: 'job_not_cancellable', owners: ["backend"], remediation: job },
152
+ { code: 'job_cancelled', owners: ["backend"], remediation: job },
153
+ ] as const satisfies readonly BackendDiagnosticGuide[];
154
+
155
+ export const BACKEND_DIAGNOSTICS_URI = 'openfairygui://docs/diagnostics';
156
+ export const BACKEND_DIAGNOSTIC_TEMPLATE = `${BACKEND_DIAGNOSTICS_URI}/{code}`;
157
+
158
+ export function getBackendDiagnosticCatalog() {
159
+ return BACKEND_DIAGNOSTIC_GUIDES.map((guide) => ({ ...structuredClone(guide), docsUri: `${BACKEND_DIAGNOSTICS_URI}/${guide.code}` }));
160
+ }
161
+
162
+ export function getBackendDiagnosticGuide(code: string) {
163
+ const guide = getBackendDiagnosticCatalog().find((entry) => entry.code === code);
164
+ if (!guide) throw new RangeError(`No recovery guide for diagnostic: ${code}`);
165
+ return guide;
166
+ }
167
+
168
+ export function enrichBackendDiagnostic(diagnostic: BackendDiagnostic, sessionId?: string): BackendDiagnostic {
169
+ const guide = BACKEND_DIAGNOSTIC_GUIDES.find((entry) => entry.code === diagnostic.code);
170
+ if (!guide) return { ...diagnostic };
171
+ return {
172
+ ...diagnostic,
173
+ owner: diagnostic.owner ?? guide.owners[0],
174
+ docsUri: `${BACKEND_DIAGNOSTICS_URI}/${guide.code}`,
175
+ remediation: {
176
+ ...guide.remediation,
177
+ ...(sessionId && guide.remediation.kind !== 'host-action'
178
+ ? { read: { method: 'getProjectOutline' as const, input: { sessionId } } } : {}),
179
+ },
180
+ };
181
+ }
package/src/docs.ts ADDED
@@ -0,0 +1,109 @@
1
+ import { getBackendDiagnosticCatalog, getBackendDiagnosticGuide, type BackendDiagnosticGuide } from './diagnostics.js';
2
+ import { CONTRACT_SNAPSHOT } from './generated/contracts.js';
3
+ import { INSTALLED_DOCS } from './generated/docs.js';
4
+
5
+ /** JSON Schema data, not another validator or operation grammar. */
6
+ export interface ContractSchema { $ref?: string; [keyword: string]: unknown }
7
+ export interface ContractSnapshot {
8
+ digest: string;
9
+ schemaVersion: number;
10
+ versions: { BACKEND_CONTRACT_VERSION: string; BACKEND_CAPABILITY_SCHEMA_VERSION: number };
11
+ operations: Record<string, ContractSchema>;
12
+ tools: Record<string, { input: ContractSchema; output: ContractSchema; bytePaths: string[][]; [metadata: string]: unknown }>;
13
+ cli: Record<string, ContractSchema>;
14
+ $defs: Record<string, ContractSchema>;
15
+ diagnostics: BackendDiagnosticGuide[];
16
+ }
17
+
18
+ export const OPENFAIRYGUI_DOCS_INDEX_URI = 'openfairygui://docs/index';
19
+ export const OPENFAIRYGUI_OPERATION_CATALOG_URI = 'openfairygui://contracts/operations';
20
+ export const OPENFAIRYGUI_OPERATION_SCHEMA_TEMPLATE = `${OPENFAIRYGUI_OPERATION_CATALOG_URI}/{kind}`;
21
+
22
+ /** Detached copy for wire adapters; documentation and adapters share one generated snapshot. */
23
+ export function getInstalledContractSnapshot(): ContractSnapshot { return structuredClone(CONTRACT_SNAPSHOT); }
24
+
25
+ export function getInstalledDocumentationVersion() {
26
+ return { ...INSTALLED_DOCS.version, ...CONTRACT_SNAPSHOT.versions, contractDigest: CONTRACT_SNAPSHOT.digest };
27
+ }
28
+
29
+ export function getOpenFairyGuiOperationCatalog() {
30
+ return {
31
+ digest: CONTRACT_SNAPSHOT.digest, schemaVersion: CONTRACT_SNAPSHOT.schemaVersion,
32
+ ...CONTRACT_SNAPSHOT.versions,
33
+ operations: Object.keys(CONTRACT_SNAPSHOT.operations).map((kind) => ({ kind, schemaUri: `${OPENFAIRYGUI_OPERATION_CATALOG_URI}/${kind}` })),
34
+ };
35
+ }
36
+
37
+ /** Include only reachable definitions, so an individual schema works fully offline. */
38
+ function standaloneSchema(schema: ContractSchema): ContractSchema {
39
+ const definitions: Record<string, ContractSchema> = {};
40
+ function visit(value: unknown): void {
41
+ if (!value || typeof value !== 'object') return;
42
+ const ref = (value as ContractSchema).$ref;
43
+ if (ref) {
44
+ const key = ref.slice('#/$defs/'.length);
45
+ if (Object.hasOwn(definitions, key)) return;
46
+ definitions[key] = CONTRACT_SNAPSHOT.$defs[key];
47
+ visit(definitions[key]);
48
+ } else for (const child of Object.values(value)) visit(child);
49
+ }
50
+ visit(schema);
51
+ return structuredClone({ $schema: 'https://json-schema.org/draft/2020-12/schema', ...schema, $defs: definitions });
52
+ }
53
+
54
+ export function getOpenFairyGuiOperationSchema(kind: string): ContractSchema {
55
+ if (!Object.hasOwn(CONTRACT_SNAPSHOT.operations, kind)) throw new RangeError(`Unknown UAM operation: ${kind}`);
56
+ return standaloneSchema(CONTRACT_SNAPSHOT.operations[kind]);
57
+ }
58
+
59
+ export function getInstalledDocumentationIndex() {
60
+ return {
61
+ ...getInstalledDocumentationVersion(),
62
+ documents: [
63
+ { id: 'workflow', title: 'Safe editing workflow and installation checks', uri: 'openfairygui://docs/workflow' },
64
+ { id: 'restore-limits', title: 'Trusted artifact recovery scope and unrecoverable editor information', uri: 'openfairygui://docs/restore-limits' },
65
+ { id: 'skill', title: 'Thin installed-version navigation skill', uri: 'openfairygui://docs/skill' },
66
+ { id: 'contracts', title: 'Operation catalog and Backend/MCP method mapping', uri: 'openfairygui://docs/contracts' },
67
+ ...Object.keys(CONTRACT_SNAPSHOT.operations).map((kind) => ({ id: `operations/${kind}`, title: `UAM operation: ${kind}`, uri: `${OPENFAIRYGUI_OPERATION_CATALOG_URI}/${kind}` })),
68
+ ...Object.keys(CONTRACT_SNAPSHOT.tools).map((method) => ({ id: `methods/${method}`, title: `Backend/MCP wire method: ${method}`, uri: `openfairygui://docs/methods/${method}` })),
69
+ ...Object.keys(CONTRACT_SNAPSHOT.cli).map((command) => ({ id: `cli/${command}`, title: `CLI JSON output: ${command}`, uri: `openfairygui://docs/cli/${encodeURIComponent(command)}` })),
70
+ ...getBackendDiagnosticCatalog().map((guide) => ({ id: `diagnostics/${guide.code}`, title: `Recovery: ${guide.code}`, uri: guide.docsUri })),
71
+ ],
72
+ };
73
+ }
74
+
75
+ /** IDs come from the index, never filesystem paths or remote URLs. */
76
+ export function readInstalledDocumentation(id: string) {
77
+ const entry = getInstalledDocumentationIndex().documents.find((document) => document.id === id);
78
+ if (!entry) throw new RangeError(`Unknown installed documentation ID: ${id}`);
79
+ let content: unknown;
80
+ if (id === 'workflow') content = INSTALLED_DOCS.workflow;
81
+ else if (id === 'restore-limits') content = INSTALLED_DOCS.restoreLimits;
82
+ else if (id === 'skill') content = INSTALLED_DOCS.skill;
83
+ else if (id === 'contracts') content = {
84
+ ...getOpenFairyGuiOperationCatalog(),
85
+ methods: Object.entries(CONTRACT_SNAPSHOT.tools).map(([method, { input, output, bytePaths, ...metadata }]) => ({ method, ...metadata, docsUri: `openfairygui://docs/methods/${method}` })),
86
+ cli: Object.keys(CONTRACT_SNAPSHOT.cli).map((command) => ({ command, docsUri: `openfairygui://docs/cli/${encodeURIComponent(command)}` })),
87
+ };
88
+ else if (id.startsWith('operations/')) content = getOpenFairyGuiOperationSchema(id.slice('operations/'.length));
89
+ else if (id.startsWith('diagnostics/')) content = getBackendDiagnosticGuide(id.slice('diagnostics/'.length));
90
+ else if (id.startsWith('cli/')) content = standaloneSchema(CONTRACT_SNAPSHOT.cli[id.slice('cli/'.length)]);
91
+ else {
92
+ const tool = CONTRACT_SNAPSHOT.tools[id.slice('methods/'.length)];
93
+ content = { ...tool, input: standaloneSchema(tool.input), output: standaloneSchema(tool.output) };
94
+ }
95
+ return {
96
+ ...getInstalledDocumentationVersion(), ...entry,
97
+ mimeType: typeof content === 'string' ? 'text/markdown' : 'application/json',
98
+ text: typeof content === 'string' ? content : JSON.stringify(content, null, 2),
99
+ };
100
+ }
101
+
102
+ export function findInstalledDocumentation(query: string) {
103
+ const term = query.trim().toLowerCase();
104
+ if (!term) throw new RangeError('Documentation search must not be empty');
105
+ const index = getInstalledDocumentationIndex();
106
+ // ponytail: linear search is sufficient for this small installed corpus; index only if it grows materially.
107
+ return { ...index, documents: index.documents.filter((entry) =>
108
+ `${entry.id}\n${entry.title}\n${readInstalledDocumentation(entry.id).text}`.toLowerCase().includes(term)) };
109
+ }