@arke-institute/sdk 0.1.3 → 2.1.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.
Files changed (66) hide show
  1. package/README.md +222 -176
  2. package/dist/crypto-CQnwqWQn.d.ts +459 -0
  3. package/dist/crypto-iYgzUi77.d.cts +459 -0
  4. package/dist/generated/index.cjs +19 -0
  5. package/dist/generated/index.cjs.map +1 -0
  6. package/dist/generated/index.d.cts +6545 -0
  7. package/dist/generated/index.d.ts +6545 -0
  8. package/dist/generated/index.js +1 -0
  9. package/dist/generated/index.js.map +1 -0
  10. package/dist/index.cjs +725 -4248
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +62 -7
  13. package/dist/index.d.ts +62 -7
  14. package/dist/index.js +706 -4221
  15. package/dist/index.js.map +1 -1
  16. package/dist/operations/index.cjs +806 -0
  17. package/dist/operations/index.cjs.map +1 -0
  18. package/dist/operations/index.d.cts +157 -0
  19. package/dist/operations/index.d.ts +157 -0
  20. package/dist/operations/index.js +759 -0
  21. package/dist/operations/index.js.map +1 -0
  22. package/openapi/spec.json +8648 -0
  23. package/openapi/version.json +7 -0
  24. package/package.json +51 -52
  25. package/dist/client-dAk3E64p.d.cts +0 -183
  26. package/dist/client-dAk3E64p.d.ts +0 -183
  27. package/dist/collections/index.cjs +0 -233
  28. package/dist/collections/index.cjs.map +0 -1
  29. package/dist/collections/index.d.cts +0 -9
  30. package/dist/collections/index.d.ts +0 -9
  31. package/dist/collections/index.js +0 -205
  32. package/dist/collections/index.js.map +0 -1
  33. package/dist/content/index.cjs +0 -591
  34. package/dist/content/index.cjs.map +0 -1
  35. package/dist/content/index.d.cts +0 -516
  36. package/dist/content/index.d.ts +0 -516
  37. package/dist/content/index.js +0 -558
  38. package/dist/content/index.js.map +0 -1
  39. package/dist/edit/index.cjs +0 -1503
  40. package/dist/edit/index.cjs.map +0 -1
  41. package/dist/edit/index.d.cts +0 -78
  42. package/dist/edit/index.d.ts +0 -78
  43. package/dist/edit/index.js +0 -1447
  44. package/dist/edit/index.js.map +0 -1
  45. package/dist/errors-3L7IiHcr.d.cts +0 -480
  46. package/dist/errors-BTe8GKRQ.d.ts +0 -480
  47. package/dist/errors-CT7yzKkU.d.cts +0 -874
  48. package/dist/errors-CT7yzKkU.d.ts +0 -874
  49. package/dist/graph/index.cjs +0 -427
  50. package/dist/graph/index.cjs.map +0 -1
  51. package/dist/graph/index.d.cts +0 -485
  52. package/dist/graph/index.d.ts +0 -485
  53. package/dist/graph/index.js +0 -396
  54. package/dist/graph/index.js.map +0 -1
  55. package/dist/query/index.cjs +0 -356
  56. package/dist/query/index.cjs.map +0 -1
  57. package/dist/query/index.d.cts +0 -636
  58. package/dist/query/index.d.ts +0 -636
  59. package/dist/query/index.js +0 -328
  60. package/dist/query/index.js.map +0 -1
  61. package/dist/upload/index.cjs +0 -1634
  62. package/dist/upload/index.cjs.map +0 -1
  63. package/dist/upload/index.d.cts +0 -150
  64. package/dist/upload/index.d.ts +0 -150
  65. package/dist/upload/index.js +0 -1597
  66. package/dist/upload/index.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/edit/types.ts","../../src/edit/errors.ts","../../src/edit/client.ts","../../src/edit/diff.ts","../../src/edit/prompts.ts","../../src/edit/session.ts"],"sourcesContent":["/**\n * Arke SDK - Edit Package Type Definitions\n *\n * Types for write operations against the IPFS Wrapper API.\n * Based on the arke/eidos@v1 schema.\n */\n\n// ============================================================================\n// Network Types\n// ============================================================================\n\n/** Network type for API requests */\nexport type Network = 'main' | 'test';\n\n// ============================================================================\n// Entity Types (arke/eidos@v1 aligned)\n// ============================================================================\n\n/**\n * Full entity manifest from IPFS Wrapper\n */\nexport interface Entity {\n /** Entity identifier (ULID or test ID with II prefix) */\n id: string;\n /** Entity type (e.g., \"PI\", \"person\", \"place\", \"concept\", \"document\") */\n type: string;\n /** Creation timestamp (immutable, set at v1) */\n created_at: string;\n /** Display name */\n label?: string;\n /** Human-readable description */\n description?: string;\n /** Version number */\n ver: number;\n /** Timestamp when this version was created */\n ts: string;\n /** CID of this manifest */\n manifest_cid: string;\n /** CID of the previous version (null for version 1) */\n prev_cid: string | null;\n /** Map of component names to their CIDs */\n components: Record<string, string>;\n /** IDs of child entities */\n children_pi?: string[];\n /** ID of parent entity */\n parent_pi?: string;\n /** Provenance: which PI extracted this entity */\n source_pi?: string;\n /** IDs of entities that have been merged into this one */\n merged_entities?: string[];\n /** Change note for this version */\n note?: string;\n}\n\n/**\n * Summary entity info returned when listing entities\n */\nexport interface EntitySummary {\n /** Entity identifier */\n id: string;\n /** Tip CID (latest manifest) */\n tip: string;\n /** Entity type (if include_metadata=true) */\n type?: string;\n /** Display name (if include_metadata=true) */\n label?: string;\n /** Version number (if include_metadata=true) */\n ver?: number;\n /** Timestamp (if include_metadata=true) */\n ts?: string;\n /** Change note (if include_metadata=true) */\n note?: string;\n /** Number of components (if include_metadata=true) */\n component_count?: number;\n /** Number of children (if include_metadata=true) */\n children_count?: number;\n}\n\n/**\n * Version entry in version history\n */\nexport interface VersionHistoryItem {\n /** Version number */\n ver: number;\n /** CID of this version's manifest */\n cid: string;\n /** Timestamp when this version was created */\n ts: string;\n /** Change note for this version */\n note?: string;\n}\n\n// ============================================================================\n// Relationship Types (arke/relationships@v1)\n// ============================================================================\n\n/**\n * A single relationship edge in the semantic graph\n */\nexport interface Relationship {\n /** Relationship predicate (e.g., \"authored_by\", \"mentions\", \"located_in\") */\n predicate: string;\n /** Type of target */\n target_type: 'pi' | 'entity';\n /** Target entity identifier */\n target_id: string;\n /** Display label for the target (e.g., \"Alice Austen\") */\n target_label: string;\n /** Target entity type (e.g., \"person\", \"place\") - only if target is entity */\n target_entity_type?: string;\n /** Optional metadata on the relationship edge */\n properties?: Record<string, unknown>;\n}\n\n// ============================================================================\n// Create Entity\n// ============================================================================\n\n/**\n * Request to create a new entity\n */\nexport interface CreateEntityRequest {\n /** Entity ID (optional - server generates ULID if omitted) */\n id?: string;\n /** Entity type (required, e.g., \"PI\", \"person\", \"place\") */\n type: string;\n /** Components map: label → CID */\n components: Record<string, string>;\n /** Display name */\n label?: string;\n /** Human-readable description */\n description?: string;\n /** Parent entity ID (auto-updates parent's children_pi) */\n parent_pi?: string;\n /** Child entity IDs */\n children_pi?: string[];\n /** Provenance: which PI extracted this entity */\n source_pi?: string;\n /** Initial properties (will be stored as component) */\n properties?: Record<string, unknown>;\n /** Initial relationships (will be stored as component) */\n relationships?: Relationship[];\n /** Change note */\n note?: string;\n}\n\n/**\n * Response from creating an entity\n */\nexport interface CreateEntityResponse {\n /** Entity identifier */\n id: string;\n /** Entity type */\n type: string;\n /** Version number (always 1 for new entities) */\n ver: number;\n /** CID of the manifest */\n manifest_cid: string;\n /** Tip CID (same as manifest_cid for new entities) */\n tip: string;\n}\n\n// ============================================================================\n// Update Entity (Append Version)\n// ============================================================================\n\n/**\n * Request to append a new version to an entity\n */\nexport interface UpdateEntityRequest {\n /** Current tip CID (CAS guard - required) */\n expect_tip: string;\n /** Change entity type */\n type?: string;\n /** Update display name */\n label?: string;\n /** Update description */\n description?: string;\n /** Components to add/update: label → CID */\n components?: Record<string, string>;\n /** Component labels to remove */\n components_remove?: string[];\n /** Child IDs to add (max 100, auto-updates children's parent_pi) */\n children_pi_add?: string[];\n /** Child IDs to remove (max 100, auto-updates children's parent_pi) */\n children_pi_remove?: string[];\n /** Replace entire properties object */\n properties?: Record<string, unknown>;\n /** Replace entire relationships array */\n relationships?: Relationship[];\n /** Change note */\n note?: string;\n}\n\n/**\n * Response from updating an entity\n */\nexport interface UpdateEntityResponse {\n /** Entity identifier */\n id: string;\n /** Entity type */\n type: string;\n /** New version number */\n ver: number;\n /** CID of the new manifest */\n manifest_cid: string;\n /** New tip CID */\n tip: string;\n}\n\n// ============================================================================\n// List Entities\n// ============================================================================\n\n/**\n * Options for listing entities\n */\nexport interface ListEntitiesOptions {\n /** Maximum entities to return (1-1000, default: 100) */\n limit?: number;\n /** Pagination cursor from next_cursor */\n cursor?: string;\n /** Include full metadata for each entity */\n include_metadata?: boolean;\n}\n\n/**\n * Response from listing entities\n */\nexport interface ListEntitiesResponse {\n /** List of entity summaries */\n entities: EntitySummary[];\n /** Limit used */\n limit: number;\n /** Cursor for next page (null if no more) */\n next_cursor: string | null;\n}\n\n// ============================================================================\n// Version Operations\n// ============================================================================\n\n/**\n * Options for listing versions\n */\nexport interface ListVersionsOptions {\n /** Maximum versions to return (1-1000, default: 50) */\n limit?: number;\n /** Pagination cursor (manifest CID) */\n cursor?: string;\n}\n\n/**\n * Response from listing versions\n */\nexport interface ListVersionsResponse {\n /** List of versions (newest first) */\n items: VersionHistoryItem[];\n /** Cursor for next page (null if reached genesis) */\n next_cursor: string | null;\n}\n\n/**\n * Response from resolving an ID to tip\n */\nexport interface ResolveResponse {\n /** Entity identifier */\n id: string;\n /** Tip CID (latest manifest) */\n tip: string;\n}\n\n// ============================================================================\n// Hierarchy Operations\n// ============================================================================\n\n/**\n * Request to update parent-child hierarchy\n */\nexport interface UpdateHierarchyRequest {\n /** Parent entity ID */\n parent_id: string;\n /** Current parent tip CID (CAS guard) */\n expect_tip: string;\n /** Child IDs to add (max 100) */\n add_children?: string[];\n /** Child IDs to remove (max 100) */\n remove_children?: string[];\n /** Change note */\n note?: string;\n}\n\n/**\n * Response from updating hierarchy\n */\nexport interface UpdateHierarchyResponse {\n /** Parent entity ID */\n parent_pi: string;\n /** New parent version */\n parent_ver: number;\n /** New parent tip CID */\n parent_tip: string;\n /** Number of children successfully updated */\n children_updated: number;\n /** Number of children that failed to update */\n children_failed: number;\n}\n\n// ============================================================================\n// Merge Operations\n// ============================================================================\n\n/**\n * Request to merge source entity into target\n */\nexport interface MergeEntityRequest {\n /** Target entity ID (entity to merge into) */\n target_id: string;\n /** Current target tip CID (CAS guard) */\n expect_target_tip: string;\n /** Reason for merge */\n note?: string;\n /** Skip index-sync callback (internal use) */\n skip_sync?: boolean;\n}\n\n/**\n * Response from merging entities\n */\nexport interface MergeEntityResponse {\n /** Source entity ID (now a tombstone) */\n source_id: string;\n /** Target entity ID */\n target_id: string;\n /** New target version */\n target_ver: number;\n /** New target tip CID */\n target_tip: string;\n /** CID of the tombstone manifest */\n tombstone_cid: string;\n}\n\n/**\n * Request to unmerge (restore) a previously merged entity\n */\nexport interface UnmergeEntityRequest {\n /** Target entity ID (entity it was merged into) */\n target_id: string;\n /** Current target tip CID (CAS guard) */\n expect_target_tip: string;\n /** Reason for unmerge */\n note?: string;\n /** Skip index-sync callback (internal use) */\n skip_sync?: boolean;\n}\n\n/**\n * Response from unmerging entity\n */\nexport interface UnmergeEntityResponse {\n /** Restored source entity ID */\n source_id: string;\n /** New source version */\n source_ver: number;\n /** New source tip CID */\n source_tip: string;\n /** Target entity ID */\n target_id: string;\n /** New target version */\n target_ver: number;\n /** New target tip CID */\n target_tip: string;\n}\n\n// ============================================================================\n// Delete Operations\n// ============================================================================\n\n/**\n * Request to soft delete an entity\n */\nexport interface DeleteEntityRequest {\n /** Current tip CID (CAS guard) */\n expect_tip: string;\n /** Reason for deletion */\n note?: string;\n}\n\n/**\n * Response from deleting an entity\n */\nexport interface DeleteEntityResponse {\n /** Entity ID */\n id: string;\n /** Version number of the tombstone */\n deleted_ver: number;\n /** Timestamp of deletion */\n deleted_at: string;\n /** CID of the tombstone manifest */\n deleted_manifest_cid: string;\n /** Previous version number (before deletion) */\n previous_ver: number;\n /** CID of the previous manifest */\n prev_cid: string;\n}\n\n/**\n * Request to restore a deleted entity\n */\nexport interface UndeleteEntityRequest {\n /** Current tip CID (tombstone CID, CAS guard) */\n expect_tip: string;\n /** Reason for restoration */\n note?: string;\n}\n\n/**\n * Response from restoring a deleted entity\n */\nexport interface UndeleteEntityResponse {\n /** Entity ID */\n id: string;\n /** New version number after restoration */\n restored_ver: number;\n /** Version number that was restored from */\n restored_from_ver: number;\n /** CID of the new manifest */\n new_manifest_cid: string;\n}\n\n// ============================================================================\n// Upload Operations\n// ============================================================================\n\n/**\n * Response from uploading files\n */\nexport interface UploadResponse {\n /** Original filename */\n name: string;\n /** CID of the uploaded content */\n cid: string;\n /** Size in bytes */\n size: number;\n}\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\nexport type EditMode = 'ai-prompt' | 'manual-with-review' | 'manual-only';\n\nexport interface EditSessionConfig {\n mode: EditMode;\n aiReviewEnabled?: boolean; // Default: true for manual modes\n}\n\n// ============================================================================\n// Edit Types (for UI/workflow)\n// ============================================================================\n\nexport type RegeneratableComponent = 'pinax' | 'description' | 'cheimarros';\n\nexport interface EditScope {\n components: RegeneratableComponent[]; // Which components to regenerate\n cascade: boolean; // Propagate changes up the tree?\n stopAtPi?: string; // Stop cascade at this ancestor PI\n}\n\nexport interface Correction {\n original: string;\n corrected: string;\n sourceFile?: string;\n context?: string; // Surrounding text for context\n}\n\n// ============================================================================\n// Diff Types\n// ============================================================================\n\nexport type DiffType = 'addition' | 'deletion' | 'change' | 'unchanged';\n\nexport interface TextDiff {\n type: DiffType;\n original?: string;\n modified?: string;\n lineNumber?: number;\n context?: string;\n}\n\nexport interface ComponentDiff {\n componentName: string;\n diffs: TextDiff[];\n summary: string; // Human-readable summary\n hasChanges: boolean;\n}\n\n// ============================================================================\n// Prompt Types\n// ============================================================================\n\nexport type PromptTarget = RegeneratableComponent | 'general' | 'reorganization';\n\nexport interface EntityContext {\n pi: string;\n ver: number;\n parentPi?: string;\n childrenCount: number;\n currentContent: Record<string, string>;\n}\n\nexport interface CascadeContext {\n path: string[]; // PIs from current to root\n depth: number;\n stopAtPi?: string;\n}\n\n// ============================================================================\n// Reprocess Types\n// ============================================================================\n\nexport interface CustomPrompts {\n general?: string;\n pinax?: string;\n description?: string;\n cheimarros?: string;\n reorganization?: string;\n}\n\nexport interface ReprocessRequest {\n pi: string;\n phases: RegeneratableComponent[];\n cascade: boolean;\n options?: {\n stop_at_pi?: string;\n custom_prompts?: CustomPrompts;\n custom_note?: string; // Custom version note (overrides default phase notes)\n };\n}\n\nexport interface ReprocessResult {\n batch_id: string;\n entities_queued: number;\n entity_pis: string[];\n status_url: string;\n}\n\nexport type ReprocessPhase =\n | 'QUEUED'\n | 'DISCOVERY'\n | 'OCR_IN_PROGRESS'\n | 'REORGANIZATION'\n | 'PINAX_EXTRACTION'\n | 'CHEIMARROS_EXTRACTION'\n | 'DESCRIPTION'\n | 'DONE'\n | 'ERROR';\n\nexport interface ReprocessProgress {\n directories_total: number;\n directories_pinax_complete: number;\n directories_cheimarros_complete: number;\n directories_description_complete: number;\n}\n\nexport interface ReprocessStatus {\n batch_id: string;\n status: ReprocessPhase;\n progress: ReprocessProgress;\n root_pi?: string;\n error?: string;\n started_at?: string;\n completed_at?: string;\n}\n\n// ============================================================================\n// Result Types\n// ============================================================================\n\nexport interface SaveResult {\n pi: string;\n newVersion: number;\n newTip: string;\n}\n\nexport interface EditResult {\n // Phase 1: Save results (if manual edits were made)\n saved?: SaveResult;\n\n // Phase 2: Reprocess results (if regeneration requested)\n reprocess?: ReprocessResult;\n}\n\nexport type EditPhase = 'idle' | 'saving' | 'reprocessing' | 'complete' | 'error';\n\nexport interface EditStatus {\n phase: EditPhase;\n saveComplete: boolean;\n reprocessStatus?: ReprocessStatus;\n error?: string;\n}\n\nexport interface PollOptions {\n intervalMs?: number; // Default: 2000\n timeoutMs?: number; // Default: 300000 (5 min)\n onProgress?: (status: EditStatus) => void;\n}\n\n// ============================================================================\n// Change Summary\n// ============================================================================\n\nexport interface ChangeSummary {\n mode: EditMode;\n hasManualEdits: boolean;\n editedComponents: string[];\n corrections: Correction[];\n prompts: Record<string, string>;\n scope: EditScope;\n willRegenerate: RegeneratableComponent[];\n willCascade: boolean;\n willSave: boolean;\n willReprocess: boolean;\n}\n\n// ============================================================================\n// Retry Configuration\n// ============================================================================\n\n/**\n * Configuration for retry behavior on transient errors\n */\nexport interface RetryConfig {\n /** Maximum retry attempts (default: 10) */\n maxRetries: number;\n /** Base delay in ms (default: 100) */\n baseDelay: number;\n /** Maximum delay in ms (default: 5000) */\n maxDelay: number;\n /** Jitter factor 0-1 (default: 0.3) */\n jitterFactor: number;\n}\n\n/**\n * Default retry configuration based on API spec recommendations\n */\nexport const DEFAULT_RETRY_CONFIG: RetryConfig = {\n maxRetries: 10,\n baseDelay: 100,\n maxDelay: 5000,\n jitterFactor: 0.3,\n};\n","/**\n * Error classes for edit operations\n */\n\n/**\n * Base error class for edit operations\n */\nexport class EditError extends Error {\n constructor(\n message: string,\n public code: string = 'UNKNOWN_ERROR',\n public details?: unknown\n ) {\n super(message);\n this.name = 'EditError';\n }\n}\n\n/**\n * Thrown when an entity is not found\n */\nexport class EntityNotFoundError extends EditError {\n constructor(id: string) {\n super(`Entity not found: ${id}`, 'ENTITY_NOT_FOUND', { id });\n this.name = 'EntityNotFoundError';\n }\n}\n\n/**\n * Thrown when a CAS (Compare-And-Swap) conflict occurs\n * This means the entity was modified since it was last read\n */\nexport class CASConflictError extends EditError {\n constructor(id: string, expectedTip: string, actualTip: string) {\n super(\n `CAS conflict: entity ${id} was modified (expected ${expectedTip}, got ${actualTip})`,\n 'CAS_CONFLICT',\n { id, expectedTip, actualTip }\n );\n this.name = 'CASConflictError';\n }\n}\n\n/**\n * Thrown when an entity ID already exists (on create)\n */\nexport class EntityExistsError extends EditError {\n constructor(id: string) {\n super(`Entity already exists: ${id}`, 'ENTITY_EXISTS', { id });\n this.name = 'EntityExistsError';\n }\n}\n\n/**\n * Thrown when a merge operation fails\n */\nexport class MergeError extends EditError {\n constructor(message: string, sourceId?: string, targetId?: string) {\n super(message, 'MERGE_ERROR', { sourceId, targetId });\n this.name = 'MergeError';\n }\n}\n\n/**\n * Thrown when an unmerge operation fails\n */\nexport class UnmergeError extends EditError {\n constructor(message: string, sourceId?: string, targetId?: string) {\n super(message, 'UNMERGE_ERROR', { sourceId, targetId });\n this.name = 'UnmergeError';\n }\n}\n\n/**\n * Thrown when a delete operation fails\n */\nexport class DeleteError extends EditError {\n constructor(message: string, id?: string) {\n super(message, 'DELETE_ERROR', { id });\n this.name = 'DeleteError';\n }\n}\n\n/**\n * Thrown when an undelete operation fails\n */\nexport class UndeleteError extends EditError {\n constructor(message: string, id?: string) {\n super(message, 'UNDELETE_ERROR', { id });\n this.name = 'UndeleteError';\n }\n}\n\n/**\n * Thrown when reprocessing fails\n */\nexport class ReprocessError extends EditError {\n constructor(message: string, batchId?: string) {\n super(message, 'REPROCESS_ERROR', { batchId });\n this.name = 'ReprocessError';\n }\n}\n\n/**\n * Thrown when request validation fails\n */\nexport class ValidationError extends EditError {\n constructor(message: string, field?: string) {\n super(message, 'VALIDATION_ERROR', { field });\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Thrown when the user doesn't have permission\n */\nexport class PermissionError extends EditError {\n constructor(message: string, id?: string) {\n super(message, 'PERMISSION_DENIED', { id });\n this.name = 'PermissionError';\n }\n}\n\n/**\n * Thrown when a network error occurs\n */\nexport class NetworkError extends EditError {\n constructor(message: string, statusCode?: number) {\n super(message, 'NETWORK_ERROR', { statusCode });\n this.name = 'NetworkError';\n }\n}\n\n/**\n * Thrown when content is not found by CID\n */\nexport class ContentNotFoundError extends EditError {\n constructor(cid: string) {\n super(`Content not found: ${cid}`, 'CONTENT_NOT_FOUND', { cid });\n this.name = 'ContentNotFoundError';\n }\n}\n\n/**\n * Thrown when the IPFS backend has an error\n */\nexport class IPFSError extends EditError {\n constructor(message: string) {\n super(message, 'IPFS_ERROR');\n this.name = 'IPFSError';\n }\n}\n\n/**\n * Thrown when the backend API has an error\n */\nexport class BackendError extends EditError {\n constructor(message: string) {\n super(message, 'BACKEND_ERROR');\n this.name = 'BackendError';\n }\n}\n","/**\n * EditClient - Complete API client for Arke edit operations\n *\n * Provides full access to IPFS Wrapper write operations:\n * - Entity CRUD (create, read, update, delete)\n * - Version management\n * - Hierarchy operations\n * - Merge/unmerge operations\n * - Content upload\n * - Reprocessing\n *\n * Routes through the gateway:\n * - /api/* -> IPFS Wrapper (entities, content, uploads)\n * - /reprocess/* -> Reprocess API\n */\n\nimport type {\n Network,\n Entity,\n CreateEntityRequest,\n CreateEntityResponse,\n UpdateEntityRequest,\n UpdateEntityResponse,\n ListEntitiesOptions,\n ListEntitiesResponse,\n ListVersionsOptions,\n ListVersionsResponse,\n ResolveResponse,\n UpdateHierarchyRequest,\n UpdateHierarchyResponse,\n MergeEntityRequest,\n MergeEntityResponse,\n UnmergeEntityRequest,\n UnmergeEntityResponse,\n DeleteEntityRequest,\n DeleteEntityResponse,\n UndeleteEntityRequest,\n UndeleteEntityResponse,\n UploadResponse,\n ReprocessRequest,\n ReprocessResult,\n ReprocessStatus,\n RetryConfig,\n} from './types.js';\nimport { DEFAULT_RETRY_CONFIG } from './types.js';\nimport {\n EditError,\n EntityNotFoundError,\n EntityExistsError,\n CASConflictError,\n MergeError,\n UnmergeError,\n DeleteError,\n UndeleteError,\n ReprocessError,\n PermissionError,\n ValidationError,\n NetworkError,\n ContentNotFoundError,\n IPFSError,\n BackendError,\n} from './errors.js';\n\n/** Configuration for EditClient */\nexport interface EditClientConfig {\n /** Gateway URL (e.g., https://gateway.arke.io) or direct API URL */\n gatewayUrl: string;\n /** JWT auth token */\n authToken?: string;\n /** Network to use (default: 'main') */\n network?: Network;\n /** User ID for permission checks */\n userId?: string;\n /** Retry configuration */\n retryConfig?: Partial<RetryConfig>;\n /** Optional transform for status URLs (e.g., for CORS proxy) */\n statusUrlTransform?: (url: string) => string;\n /**\n * API prefix for IPFS wrapper routes (default: '/api').\n * Set to '' (empty string) when using direct API URL like https://api.arke.institute\n */\n apiPrefix?: string;\n}\n\n/** Retry status codes */\nconst RETRYABLE_STATUS_CODES = [409, 503];\n\n/** Retry error messages */\nconst RETRYABLE_ERRORS = ['ECONNRESET', 'ETIMEDOUT', 'fetch failed'];\n\nexport class EditClient {\n private gatewayUrl: string;\n private authToken?: string;\n private network: Network;\n private userId?: string;\n private retryConfig: RetryConfig;\n private statusUrlTransform?: (url: string) => string;\n private apiPrefix: string;\n\n constructor(config: EditClientConfig) {\n this.gatewayUrl = config.gatewayUrl.replace(/\\/$/, '');\n this.authToken = config.authToken;\n this.network = config.network || 'main';\n this.userId = config.userId;\n this.retryConfig = { ...DEFAULT_RETRY_CONFIG, ...config.retryConfig };\n this.statusUrlTransform = config.statusUrlTransform;\n this.apiPrefix = config.apiPrefix ?? '/api';\n }\n\n // ===========================================================================\n // Configuration Methods\n // ===========================================================================\n\n /**\n * Update the auth token (useful for token refresh)\n */\n setAuthToken(token: string): void {\n this.authToken = token;\n }\n\n /**\n * Set the network (main or test)\n */\n setNetwork(network: Network): void {\n this.network = network;\n }\n\n /**\n * Set the user ID for permission checks\n */\n setUserId(userId: string): void {\n this.userId = userId;\n }\n\n // ===========================================================================\n // Internal Helpers\n // ===========================================================================\n\n /**\n * Build URL with API prefix\n */\n private buildUrl(path: string): string {\n return `${this.gatewayUrl}${this.apiPrefix}${path}`;\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n private getHeaders(contentType: string | null = 'application/json'): HeadersInit {\n const headers: HeadersInit = {};\n if (contentType) {\n headers['Content-Type'] = contentType;\n }\n if (this.authToken) {\n headers['Authorization'] = `Bearer ${this.authToken}`;\n }\n headers['X-Arke-Network'] = this.network;\n if (this.userId) {\n headers['X-User-Id'] = this.userId;\n }\n return headers;\n }\n\n private calculateDelay(attempt: number): number {\n const { baseDelay, maxDelay, jitterFactor } = this.retryConfig;\n const exponentialDelay = baseDelay * Math.pow(2, attempt);\n const cappedDelay = Math.min(exponentialDelay, maxDelay);\n const jitter = cappedDelay * jitterFactor * (Math.random() * 2 - 1);\n return Math.max(0, cappedDelay + jitter);\n }\n\n private isRetryableStatus(status: number): boolean {\n return RETRYABLE_STATUS_CODES.includes(status);\n }\n\n private isRetryableError(error: Error): boolean {\n const message = error.message.toLowerCase();\n return RETRYABLE_ERRORS.some((e) => message.includes(e.toLowerCase()));\n }\n\n /**\n * Execute a fetch with exponential backoff retry on transient errors\n */\n private async fetchWithRetry(\n url: string,\n options: RequestInit,\n context: string\n ): Promise<Response> {\n let lastError: Error | null = null;\n\n for (let attempt = 0; attempt <= this.retryConfig.maxRetries; attempt++) {\n try {\n const response = await fetch(url, options);\n\n // Check for retryable status codes\n if (this.isRetryableStatus(response.status) && attempt < this.retryConfig.maxRetries) {\n const delay = this.calculateDelay(attempt);\n lastError = new Error(`${context}: ${response.status} ${response.statusText}`);\n await this.sleep(delay);\n continue;\n }\n\n return response;\n } catch (error) {\n lastError = error as Error;\n if (this.isRetryableError(lastError) && attempt < this.retryConfig.maxRetries) {\n const delay = this.calculateDelay(attempt);\n await this.sleep(delay);\n continue;\n }\n throw new NetworkError(lastError.message);\n }\n }\n\n throw lastError || new NetworkError('Request failed after retries');\n }\n\n /**\n * Handle common error responses and throw appropriate error types\n */\n private async handleErrorResponse(response: Response, context: string): Promise<never> {\n let errorData: { error?: string; message?: string; details?: unknown } = {};\n try {\n errorData = await response.json();\n } catch {\n // Response may not be JSON\n }\n\n const message = errorData.message || `${context}: ${response.statusText}`;\n const errorCode = errorData.error || '';\n\n switch (response.status) {\n case 400:\n throw new ValidationError(message);\n case 403:\n throw new PermissionError(message);\n case 404:\n throw new EntityNotFoundError(message);\n case 409:\n if (errorCode === 'CAS_FAILURE') {\n const details = errorData.details as { actual?: string; expect?: string } | undefined;\n throw new CASConflictError(\n context,\n details?.expect || 'unknown',\n details?.actual || 'unknown'\n );\n }\n if (errorCode === 'CONFLICT') {\n throw new EntityExistsError(message);\n }\n throw new EditError(message, errorCode, errorData.details);\n case 503:\n if (errorCode === 'IPFS_ERROR') {\n throw new IPFSError(message);\n }\n if (errorCode === 'BACKEND_ERROR') {\n throw new BackendError(message);\n }\n throw new NetworkError(message, response.status);\n default:\n throw new EditError(message, errorCode || 'API_ERROR', { status: response.status });\n }\n }\n\n // ===========================================================================\n // Entity CRUD Operations\n // ===========================================================================\n\n /**\n * Create a new entity\n */\n async createEntity(request: CreateEntityRequest): Promise<CreateEntityResponse> {\n const url = this.buildUrl('/entities');\n const response = await this.fetchWithRetry(\n url,\n {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify(request),\n },\n 'Create entity'\n );\n\n if (!response.ok) {\n await this.handleErrorResponse(response, 'Create entity');\n }\n\n return response.json();\n }\n\n /**\n * Get an entity by ID\n */\n async getEntity(id: string): Promise<Entity> {\n const url = this.buildUrl(`/entities/${encodeURIComponent(id)}`);\n const response = await this.fetchWithRetry(\n url,\n { headers: this.getHeaders() },\n `Get entity ${id}`\n );\n\n if (!response.ok) {\n await this.handleErrorResponse(response, `Get entity ${id}`);\n }\n\n return response.json();\n }\n\n /**\n * List entities with pagination\n */\n async listEntities(options: ListEntitiesOptions = {}): Promise<ListEntitiesResponse> {\n const params = new URLSearchParams();\n if (options.limit) params.set('limit', options.limit.toString());\n if (options.cursor) params.set('cursor', options.cursor);\n if (options.include_metadata) params.set('include_metadata', 'true');\n\n const queryString = params.toString();\n const url = this.buildUrl(`/entities${queryString ? `?${queryString}` : ''}`);\n\n const response = await this.fetchWithRetry(url, { headers: this.getHeaders() }, 'List entities');\n\n if (!response.ok) {\n await this.handleErrorResponse(response, 'List entities');\n }\n\n return response.json();\n }\n\n /**\n * Update an entity (append new version)\n */\n async updateEntity(id: string, update: UpdateEntityRequest): Promise<UpdateEntityResponse> {\n const url = this.buildUrl(`/entities/${encodeURIComponent(id)}/versions`);\n const response = await this.fetchWithRetry(\n url,\n {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify(update),\n },\n `Update entity ${id}`\n );\n\n if (!response.ok) {\n await this.handleErrorResponse(response, `Update entity ${id}`);\n }\n\n return response.json();\n }\n\n // ===========================================================================\n // Version Operations\n // ===========================================================================\n\n /**\n * List version history for an entity\n */\n async listVersions(id: string, options: ListVersionsOptions = {}): Promise<ListVersionsResponse> {\n const params = new URLSearchParams();\n if (options.limit) params.set('limit', options.limit.toString());\n if (options.cursor) params.set('cursor', options.cursor);\n\n const queryString = params.toString();\n const url = this.buildUrl(`/entities/${encodeURIComponent(id)}/versions${queryString ? `?${queryString}` : ''}`);\n\n const response = await this.fetchWithRetry(url, { headers: this.getHeaders() }, `List versions for ${id}`);\n\n if (!response.ok) {\n await this.handleErrorResponse(response, `List versions for ${id}`);\n }\n\n return response.json();\n }\n\n /**\n * Get a specific version of an entity\n */\n async getVersion(id: string, selector: string): Promise<Entity> {\n const url = this.buildUrl(`/entities/${encodeURIComponent(id)}/versions/${encodeURIComponent(selector)}`);\n const response = await this.fetchWithRetry(\n url,\n { headers: this.getHeaders() },\n `Get version ${selector} for ${id}`\n );\n\n if (!response.ok) {\n await this.handleErrorResponse(response, `Get version ${selector} for ${id}`);\n }\n\n return response.json();\n }\n\n /**\n * Resolve an entity ID to its current tip CID (fast lookup)\n */\n async resolve(id: string): Promise<ResolveResponse> {\n const url = this.buildUrl(`/resolve/${encodeURIComponent(id)}`);\n const response = await this.fetchWithRetry(\n url,\n { headers: this.getHeaders() },\n `Resolve ${id}`\n );\n\n if (!response.ok) {\n await this.handleErrorResponse(response, `Resolve ${id}`);\n }\n\n return response.json();\n }\n\n // ===========================================================================\n // Hierarchy Operations\n // ===========================================================================\n\n /**\n * Update parent-child hierarchy relationships\n */\n async updateHierarchy(request: UpdateHierarchyRequest): Promise<UpdateHierarchyResponse> {\n const apiRequest = {\n parent_pi: request.parent_id,\n expect_tip: request.expect_tip,\n add_children: request.add_children,\n remove_children: request.remove_children,\n note: request.note,\n };\n\n const url = this.buildUrl('/hierarchy');\n const response = await this.fetchWithRetry(\n url,\n {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify(apiRequest),\n },\n `Update hierarchy for ${request.parent_id}`\n );\n\n if (!response.ok) {\n await this.handleErrorResponse(response, `Update hierarchy for ${request.parent_id}`);\n }\n\n return response.json();\n }\n\n // ===========================================================================\n // Merge Operations\n // ===========================================================================\n\n /**\n * Merge source entity into target entity\n */\n async mergeEntity(sourceId: string, request: MergeEntityRequest): Promise<MergeEntityResponse> {\n const url = this.buildUrl(`/entities/${encodeURIComponent(sourceId)}/merge`);\n const response = await this.fetchWithRetry(\n url,\n {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify(request),\n },\n `Merge ${sourceId} into ${request.target_id}`\n );\n\n if (!response.ok) {\n try {\n const error = await response.json();\n throw new MergeError(\n error.message || `Merge failed: ${response.statusText}`,\n sourceId,\n request.target_id\n );\n } catch (e) {\n if (e instanceof MergeError) throw e;\n await this.handleErrorResponse(response, `Merge ${sourceId}`);\n }\n }\n\n return response.json();\n }\n\n /**\n * Unmerge (restore) a previously merged entity\n */\n async unmergeEntity(sourceId: string, request: UnmergeEntityRequest): Promise<UnmergeEntityResponse> {\n const url = this.buildUrl(`/entities/${encodeURIComponent(sourceId)}/unmerge`);\n const response = await this.fetchWithRetry(\n url,\n {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify(request),\n },\n `Unmerge ${sourceId}`\n );\n\n if (!response.ok) {\n try {\n const error = await response.json();\n throw new UnmergeError(\n error.message || `Unmerge failed: ${response.statusText}`,\n sourceId,\n request.target_id\n );\n } catch (e) {\n if (e instanceof UnmergeError) throw e;\n await this.handleErrorResponse(response, `Unmerge ${sourceId}`);\n }\n }\n\n return response.json();\n }\n\n // ===========================================================================\n // Delete Operations\n // ===========================================================================\n\n /**\n * Soft delete an entity (creates tombstone, preserves history)\n */\n async deleteEntity(id: string, request: DeleteEntityRequest): Promise<DeleteEntityResponse> {\n const url = this.buildUrl(`/entities/${encodeURIComponent(id)}/delete`);\n const response = await this.fetchWithRetry(\n url,\n {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify(request),\n },\n `Delete ${id}`\n );\n\n if (!response.ok) {\n try {\n const error = await response.json();\n throw new DeleteError(error.message || `Delete failed: ${response.statusText}`, id);\n } catch (e) {\n if (e instanceof DeleteError) throw e;\n await this.handleErrorResponse(response, `Delete ${id}`);\n }\n }\n\n return response.json();\n }\n\n /**\n * Restore a deleted entity\n */\n async undeleteEntity(id: string, request: UndeleteEntityRequest): Promise<UndeleteEntityResponse> {\n const url = this.buildUrl(`/entities/${encodeURIComponent(id)}/undelete`);\n const response = await this.fetchWithRetry(\n url,\n {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify(request),\n },\n `Undelete ${id}`\n );\n\n if (!response.ok) {\n try {\n const error = await response.json();\n throw new UndeleteError(error.message || `Undelete failed: ${response.statusText}`, id);\n } catch (e) {\n if (e instanceof UndeleteError) throw e;\n await this.handleErrorResponse(response, `Undelete ${id}`);\n }\n }\n\n return response.json();\n }\n\n // ===========================================================================\n // Content Operations\n // ===========================================================================\n\n /**\n * Upload files to IPFS\n */\n async upload(files: File | Blob | File[] | Blob[] | FormData): Promise<UploadResponse[]> {\n let formData: FormData;\n\n if (files instanceof FormData) {\n formData = files;\n } else {\n formData = new FormData();\n const fileArray = Array.isArray(files) ? files : [files];\n for (const file of fileArray) {\n if (file instanceof File) {\n formData.append('file', file, file.name);\n } else {\n formData.append('file', file, 'file');\n }\n }\n }\n\n const url = this.buildUrl('/upload');\n const response = await this.fetchWithRetry(\n url,\n {\n method: 'POST',\n headers: this.getHeaders(null), // No Content-Type for multipart\n body: formData,\n },\n 'Upload files'\n );\n\n if (!response.ok) {\n await this.handleErrorResponse(response, 'Upload files');\n }\n\n return response.json();\n }\n\n /**\n * Upload text content and return CID\n */\n async uploadContent(content: string, filename: string): Promise<string> {\n const blob = new Blob([content], { type: 'text/plain' });\n const file = new File([blob], filename, { type: 'text/plain' });\n const [result] = await this.upload(file);\n return result.cid;\n }\n\n /**\n * Download file content by CID\n */\n async getContent(cid: string): Promise<string> {\n const url = this.buildUrl(`/cat/${encodeURIComponent(cid)}`);\n const response = await this.fetchWithRetry(\n url,\n { headers: this.getHeaders() },\n `Get content ${cid}`\n );\n\n if (response.status === 404) {\n throw new ContentNotFoundError(cid);\n }\n\n if (!response.ok) {\n await this.handleErrorResponse(response, `Get content ${cid}`);\n }\n\n return response.text();\n }\n\n /**\n * Download a DAG node (JSON) by CID\n */\n async getDag<T = unknown>(cid: string): Promise<T> {\n const url = this.buildUrl(`/dag/${encodeURIComponent(cid)}`);\n const response = await this.fetchWithRetry(\n url,\n { headers: this.getHeaders() },\n `Get DAG ${cid}`\n );\n\n if (response.status === 404) {\n throw new ContentNotFoundError(cid);\n }\n\n if (!response.ok) {\n await this.handleErrorResponse(response, `Get DAG ${cid}`);\n }\n\n return response.json();\n }\n\n // ===========================================================================\n // Arke Origin Operations\n // ===========================================================================\n\n /**\n * Get the Arke origin block (genesis entity)\n */\n async getArke(): Promise<Entity> {\n const url = this.buildUrl('/arke');\n const response = await this.fetchWithRetry(\n url,\n { headers: this.getHeaders() },\n 'Get Arke'\n );\n\n if (!response.ok) {\n await this.handleErrorResponse(response, 'Get Arke');\n }\n\n return response.json();\n }\n\n /**\n * Initialize the Arke origin block (creates if doesn't exist)\n */\n async initArke(): Promise<CreateEntityResponse> {\n const url = this.buildUrl('/arke/init');\n const response = await this.fetchWithRetry(\n url,\n {\n method: 'POST',\n headers: this.getHeaders(),\n },\n 'Init Arke'\n );\n\n if (!response.ok) {\n await this.handleErrorResponse(response, 'Init Arke');\n }\n\n return response.json();\n }\n\n // ===========================================================================\n // Reprocess API Operations (via /reprocess/*)\n // ===========================================================================\n\n /**\n * Trigger reprocessing for an entity\n */\n async reprocess(request: ReprocessRequest): Promise<ReprocessResult> {\n const response = await this.fetchWithRetry(\n `${this.gatewayUrl}/reprocess/reprocess`,\n {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify({\n pi: request.pi,\n phases: request.phases,\n cascade: request.cascade,\n options: request.options,\n }),\n },\n `Reprocess ${request.pi}`\n );\n\n if (response.status === 403) {\n const error = await response.json().catch(() => ({}));\n throw new PermissionError(\n error.message || `Permission denied to reprocess ${request.pi}`,\n request.pi\n );\n }\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new ReprocessError(error.message || `Reprocess failed: ${response.statusText}`);\n }\n\n return response.json();\n }\n\n /**\n * Get reprocessing status by batch ID\n */\n async getReprocessStatus(statusUrl: string, isFirstPoll = false): Promise<ReprocessStatus> {\n const fetchUrl = this.statusUrlTransform ? this.statusUrlTransform(statusUrl) : statusUrl;\n\n const delay = isFirstPoll ? 3000 : this.retryConfig.baseDelay;\n if (isFirstPoll) {\n await this.sleep(delay);\n }\n\n const response = await this.fetchWithRetry(\n fetchUrl,\n { headers: this.getHeaders() },\n 'Get reprocess status'\n );\n\n if (!response.ok) {\n throw new EditError(\n `Failed to fetch reprocess status: ${response.statusText}`,\n 'STATUS_ERROR',\n { status: response.status }\n );\n }\n\n return response.json();\n }\n\n // ===========================================================================\n // Utility Methods\n // ===========================================================================\n\n /**\n * Execute an operation with automatic CAS retry\n */\n async withCAS<T>(\n id: string,\n operation: (entity: Entity) => Promise<T>,\n maxRetries = 3\n ): Promise<T> {\n let lastError: Error | null = null;\n\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n try {\n const entity = await this.getEntity(id);\n return await operation(entity);\n } catch (error) {\n if (error instanceof CASConflictError && attempt < maxRetries - 1) {\n lastError = error;\n const delay = this.calculateDelay(attempt);\n await this.sleep(delay);\n continue;\n }\n throw error;\n }\n }\n\n throw lastError || new EditError('withCAS failed after retries');\n }\n}\n","/**\n * DiffEngine - Text comparison and diff formatting\n */\n\nimport * as Diff from 'diff';\nimport type { TextDiff, ComponentDiff, Correction } from './types';\n\nexport class DiffEngine {\n /**\n * Compute diff between two strings\n */\n static diff(original: string, modified: string): TextDiff[] {\n const changes = Diff.diffLines(original, modified);\n const diffs: TextDiff[] = [];\n let lineNumber = 1;\n\n for (const change of changes) {\n if (change.added) {\n diffs.push({\n type: 'addition',\n modified: change.value.trimEnd(),\n lineNumber,\n });\n } else if (change.removed) {\n diffs.push({\n type: 'deletion',\n original: change.value.trimEnd(),\n lineNumber,\n });\n } else {\n // Track line numbers for unchanged content\n const lines = change.value.split('\\n').length - 1;\n lineNumber += lines;\n }\n\n // Update line number for added content\n if (change.added) {\n lineNumber += change.value.split('\\n').length - 1;\n }\n }\n\n return diffs;\n }\n\n /**\n * Compute word-level diff for more granular changes\n */\n static diffWords(original: string, modified: string): TextDiff[] {\n const changes = Diff.diffWords(original, modified);\n const diffs: TextDiff[] = [];\n\n for (const change of changes) {\n if (change.added) {\n diffs.push({\n type: 'addition',\n modified: change.value,\n });\n } else if (change.removed) {\n diffs.push({\n type: 'deletion',\n original: change.value,\n });\n }\n }\n\n return diffs;\n }\n\n /**\n * Create a ComponentDiff from original and modified content\n */\n static createComponentDiff(\n componentName: string,\n original: string,\n modified: string\n ): ComponentDiff {\n const diffs = this.diff(original, modified);\n const hasChanges = diffs.length > 0;\n\n let summary: string;\n if (!hasChanges) {\n summary = 'No changes';\n } else {\n const additions = diffs.filter((d) => d.type === 'addition').length;\n const deletions = diffs.filter((d) => d.type === 'deletion').length;\n const parts: string[] = [];\n if (additions > 0) parts.push(`${additions} addition${additions > 1 ? 's' : ''}`);\n if (deletions > 0) parts.push(`${deletions} deletion${deletions > 1 ? 's' : ''}`);\n summary = parts.join(', ');\n }\n\n return {\n componentName,\n diffs,\n summary,\n hasChanges,\n };\n }\n\n /**\n * Format diffs for AI prompt consumption\n */\n static formatForPrompt(diffs: TextDiff[]): string {\n if (diffs.length === 0) {\n return 'No changes detected.';\n }\n\n const lines: string[] = [];\n\n for (const diff of diffs) {\n const linePrefix = diff.lineNumber ? `Line ${diff.lineNumber}: ` : '';\n\n if (diff.type === 'addition') {\n lines.push(`${linePrefix}+ ${diff.modified}`);\n } else if (diff.type === 'deletion') {\n lines.push(`${linePrefix}- ${diff.original}`);\n } else if (diff.type === 'change') {\n lines.push(`${linePrefix}\"${diff.original}\" → \"${diff.modified}\"`);\n }\n }\n\n return lines.join('\\n');\n }\n\n /**\n * Format component diffs for AI prompt\n */\n static formatComponentDiffsForPrompt(componentDiffs: ComponentDiff[]): string {\n const sections: string[] = [];\n\n for (const cd of componentDiffs) {\n if (!cd.hasChanges) continue;\n\n sections.push(`## Changes to ${cd.componentName}:`);\n sections.push(this.formatForPrompt(cd.diffs));\n sections.push('');\n }\n\n return sections.join('\\n');\n }\n\n /**\n * Create a unified diff view\n */\n static unifiedDiff(\n original: string,\n modified: string,\n options?: { filename?: string; context?: number }\n ): string {\n const filename = options?.filename || 'content';\n const patch = Diff.createPatch(filename, original, modified, '', '', {\n context: options?.context ?? 3,\n });\n return patch;\n }\n\n /**\n * Extract corrections from diffs (specific text replacements)\n */\n static extractCorrections(\n original: string,\n modified: string,\n sourceFile?: string\n ): Correction[] {\n const wordDiffs = Diff.diffWords(original, modified);\n const corrections: Correction[] = [];\n\n let i = 0;\n while (i < wordDiffs.length) {\n const current = wordDiffs[i];\n\n // Look for removal followed by addition (a replacement)\n if (current.removed && i + 1 < wordDiffs.length && wordDiffs[i + 1].added) {\n const removed = current.value.trim();\n const added = wordDiffs[i + 1].value.trim();\n\n if (removed && added && removed !== added) {\n corrections.push({\n original: removed,\n corrected: added,\n sourceFile,\n });\n }\n i += 2;\n } else {\n i++;\n }\n }\n\n return corrections;\n }\n\n /**\n * Check if two strings are meaningfully different\n * (ignoring whitespace differences)\n */\n static hasSignificantChanges(original: string, modified: string): boolean {\n const normalizedOriginal = original.replace(/\\s+/g, ' ').trim();\n const normalizedModified = modified.replace(/\\s+/g, ' ').trim();\n return normalizedOriginal !== normalizedModified;\n }\n}\n","/**\n * PromptBuilder - Context-aware AI prompt construction\n */\n\nimport { DiffEngine } from './diff';\nimport type {\n RegeneratableComponent,\n EntityContext,\n CascadeContext,\n ComponentDiff,\n Correction,\n} from './types';\n\nexport class PromptBuilder {\n /**\n * Build prompt for AI-first mode (user provides instructions)\n */\n static buildAIPrompt(\n userPrompt: string,\n component: RegeneratableComponent,\n entityContext: EntityContext,\n currentContent?: string\n ): string {\n const sections: string[] = [];\n\n // User instruction\n sections.push(`## Instructions for ${component}`);\n sections.push(userPrompt);\n sections.push('');\n\n // Entity context\n sections.push('## Entity Context');\n sections.push(`- PI: ${entityContext.pi}`);\n sections.push(`- Current version: ${entityContext.ver}`);\n if (entityContext.parentPi) {\n sections.push(`- Parent: ${entityContext.parentPi}`);\n }\n if (entityContext.childrenCount > 0) {\n sections.push(`- Children: ${entityContext.childrenCount}`);\n }\n sections.push('');\n\n // Current content reference\n if (currentContent) {\n sections.push(`## Current ${component} content for reference:`);\n sections.push('```');\n sections.push(currentContent.slice(0, 2000)); // Truncate if very long\n if (currentContent.length > 2000) {\n sections.push('... [truncated]');\n }\n sections.push('```');\n }\n\n return sections.join('\\n');\n }\n\n /**\n * Build prompt incorporating manual edits and diffs\n */\n static buildEditReviewPrompt(\n componentDiffs: ComponentDiff[],\n corrections: Correction[],\n component: RegeneratableComponent,\n userInstructions?: string\n ): string {\n const sections: string[] = [];\n\n sections.push('## Manual Edits Made');\n sections.push('');\n sections.push('The following manual edits were made to this entity:');\n sections.push('');\n\n // Show diffs\n const diffContent = DiffEngine.formatComponentDiffsForPrompt(componentDiffs);\n if (diffContent) {\n sections.push(diffContent);\n }\n\n // Show corrections\n if (corrections.length > 0) {\n sections.push('## Corrections Identified');\n sections.push('');\n for (const correction of corrections) {\n const source = correction.sourceFile ? ` (in ${correction.sourceFile})` : '';\n sections.push(`- \"${correction.original}\" → \"${correction.corrected}\"${source}`);\n }\n sections.push('');\n }\n\n // User instructions\n sections.push('## Instructions');\n if (userInstructions) {\n sections.push(userInstructions);\n } else {\n sections.push(\n `Update the ${component} to accurately reflect these changes. ` +\n 'Ensure any corrections are incorporated and the content is consistent.'\n );\n }\n sections.push('');\n\n // Specific guidance per component\n sections.push('## Guidance');\n switch (component) {\n case 'pinax':\n sections.push(\n 'Update metadata fields to reflect any corrections. Pay special attention to dates, ' +\n 'names, and other factual information that may have been corrected.'\n );\n break;\n case 'description':\n sections.push(\n 'Regenerate the description incorporating the changes. Maintain the overall tone ' +\n 'and structure while ensuring accuracy based on the corrections.'\n );\n break;\n case 'cheimarros':\n sections.push(\n 'Update the knowledge graph to reflect any new or corrected entities, relationships, ' +\n 'and facts identified in the changes.'\n );\n break;\n }\n\n return sections.join('\\n');\n }\n\n /**\n * Build cascade-aware prompt additions\n */\n static buildCascadePrompt(basePrompt: string, cascadeContext: CascadeContext): string {\n const sections: string[] = [basePrompt];\n\n sections.push('');\n sections.push('## Cascade Context');\n sections.push('');\n sections.push(\n 'This edit is part of a cascading update. After updating this entity, ' +\n 'parent entities will also be updated to reflect these changes.'\n );\n sections.push('');\n\n if (cascadeContext.path.length > 1) {\n sections.push(`Cascade path: ${cascadeContext.path.join(' → ')}`);\n sections.push(`Depth: ${cascadeContext.depth}`);\n }\n\n if (cascadeContext.stopAtPi) {\n sections.push(`Cascade will stop at: ${cascadeContext.stopAtPi}`);\n }\n\n sections.push('');\n sections.push(\n 'Ensure the content accurately represents the source material so parent ' +\n 'aggregations will be correct.'\n );\n\n return sections.join('\\n');\n }\n\n /**\n * Build a general prompt combining multiple instructions\n */\n static buildCombinedPrompt(\n generalPrompt: string | undefined,\n componentPrompt: string | undefined,\n component: RegeneratableComponent\n ): string {\n const sections: string[] = [];\n\n if (generalPrompt) {\n sections.push('## General Instructions');\n sections.push(generalPrompt);\n sections.push('');\n }\n\n if (componentPrompt) {\n sections.push(`## Specific Instructions for ${component}`);\n sections.push(componentPrompt);\n sections.push('');\n }\n\n if (sections.length === 0) {\n return `Regenerate the ${component} based on the current entity content.`;\n }\n\n return sections.join('\\n');\n }\n\n /**\n * Build prompt for correction-based updates\n */\n static buildCorrectionPrompt(corrections: Correction[]): string {\n if (corrections.length === 0) {\n return '';\n }\n\n const sections: string[] = [];\n\n sections.push('## Corrections Applied');\n sections.push('');\n sections.push('The following corrections were made to the source content:');\n sections.push('');\n\n for (const correction of corrections) {\n const source = correction.sourceFile ? ` in ${correction.sourceFile}` : '';\n sections.push(`- \"${correction.original}\" was corrected to \"${correction.corrected}\"${source}`);\n if (correction.context) {\n sections.push(` Context: ${correction.context}`);\n }\n }\n\n sections.push('');\n sections.push(\n 'Update the metadata and description to reflect these corrections. ' +\n 'Previous content may have contained errors based on the incorrect text.'\n );\n\n return sections.join('\\n');\n }\n\n /**\n * Get component-specific regeneration guidance\n */\n static getComponentGuidance(component: RegeneratableComponent): string {\n switch (component) {\n case 'pinax':\n return (\n 'Extract and structure metadata including: institution, creator, title, ' +\n 'date range, subjects, type, and other relevant fields. Ensure accuracy ' +\n 'based on the source content.'\n );\n case 'description':\n return (\n 'Generate a clear, informative description that summarizes the entity content. ' +\n 'Focus on what the material contains, its historical significance, and context. ' +\n 'Write for a general audience unless otherwise specified.'\n );\n case 'cheimarros':\n return (\n 'Extract entities (people, places, organizations, events) and their relationships. ' +\n 'Build a knowledge graph that captures the key facts and connections in the content.'\n );\n default:\n return '';\n }\n }\n}\n","/**\n * EditSession - Stateful session managing an edit workflow\n */\n\nimport { EditClient } from './client';\nimport { DiffEngine } from './diff';\nimport { PromptBuilder } from './prompts';\nimport type {\n Entity,\n EditMode,\n EditSessionConfig,\n EditScope,\n Correction,\n ComponentDiff,\n RegeneratableComponent,\n PromptTarget,\n ChangeSummary,\n EditResult,\n EditStatus,\n PollOptions,\n CustomPrompts,\n} from './types';\nimport { ValidationError } from './errors';\n\nconst DEFAULT_SCOPE: EditScope = {\n components: [],\n cascade: false,\n};\n\nconst DEFAULT_POLL_OPTIONS: Required<Omit<PollOptions, 'onProgress'>> = {\n intervalMs: 2000,\n timeoutMs: 300000, // 5 minutes\n};\n\nexport class EditSession {\n readonly pi: string;\n readonly mode: EditMode;\n readonly aiReviewEnabled: boolean;\n\n private client: EditClient;\n private entity: Entity | null = null;\n private loadedComponents: Record<string, string> = {};\n\n // AI mode state\n private prompts: Record<string, string> = {};\n\n // Manual mode state\n private editedContent: Record<string, string> = {};\n private corrections: Correction[] = [];\n\n // Scope\n private scope: EditScope = { ...DEFAULT_SCOPE };\n\n // Execution state\n private submitting = false;\n private result: EditResult | null = null;\n private statusUrl: string | null = null;\n\n constructor(client: EditClient, pi: string, config?: EditSessionConfig) {\n this.client = client;\n this.pi = pi;\n this.mode = config?.mode ?? 'ai-prompt';\n this.aiReviewEnabled = config?.aiReviewEnabled ?? true;\n }\n\n // ===========================================================================\n // Loading\n // ===========================================================================\n\n /**\n * Load the entity and its key components\n */\n async load(): Promise<void> {\n this.entity = await this.client.getEntity(this.pi);\n\n // Load key components that are commonly edited\n const priorityComponents = ['description.md', 'pinax.json', 'cheimarros.json'];\n\n await Promise.all(\n priorityComponents.map(async (name) => {\n const cid = this.entity!.components[name];\n if (cid) {\n try {\n this.loadedComponents[name] = await this.client.getContent(cid);\n } catch {\n // Component may not exist, that's ok\n }\n }\n })\n );\n }\n\n /**\n * Load a specific component on demand\n */\n async loadComponent(name: string): Promise<string | undefined> {\n if (this.loadedComponents[name]) {\n return this.loadedComponents[name];\n }\n\n if (!this.entity) {\n throw new ValidationError('Session not loaded');\n }\n\n const cid = this.entity.components[name];\n if (!cid) {\n return undefined;\n }\n\n const content = await this.client.getContent(cid);\n this.loadedComponents[name] = content;\n return content;\n }\n\n /**\n * Get the loaded entity\n */\n getEntity(): Entity {\n if (!this.entity) {\n throw new ValidationError('Session not loaded. Call load() first.');\n }\n return this.entity;\n }\n\n /**\n * Get loaded component content\n */\n getComponents(): Record<string, string> {\n return { ...this.loadedComponents };\n }\n\n // ===========================================================================\n // AI Prompt Mode\n // ===========================================================================\n\n /**\n * Set a prompt for AI regeneration\n */\n setPrompt(target: PromptTarget, prompt: string): void {\n if (this.mode === 'manual-only') {\n throw new ValidationError('Cannot set prompts in manual-only mode');\n }\n this.prompts[target] = prompt;\n }\n\n /**\n * Get all prompts\n */\n getPrompts(): Record<string, string> {\n return { ...this.prompts };\n }\n\n /**\n * Clear a prompt\n */\n clearPrompt(target: PromptTarget): void {\n delete this.prompts[target];\n }\n\n // ===========================================================================\n // Manual Edit Mode\n // ===========================================================================\n\n /**\n * Set edited content for a component\n */\n setContent(componentName: string, content: string): void {\n if (this.mode === 'ai-prompt') {\n throw new ValidationError('Cannot set content in ai-prompt mode');\n }\n this.editedContent[componentName] = content;\n }\n\n /**\n * Get all edited content\n */\n getEditedContent(): Record<string, string> {\n return { ...this.editedContent };\n }\n\n /**\n * Clear edited content for a component\n */\n clearContent(componentName: string): void {\n delete this.editedContent[componentName];\n }\n\n /**\n * Add a correction (for OCR fixes, etc.)\n */\n addCorrection(original: string, corrected: string, sourceFile?: string): void {\n this.corrections.push({ original, corrected, sourceFile });\n }\n\n /**\n * Get all corrections\n */\n getCorrections(): Correction[] {\n return [...this.corrections];\n }\n\n /**\n * Clear corrections\n */\n clearCorrections(): void {\n this.corrections = [];\n }\n\n // ===========================================================================\n // Scope Configuration\n // ===========================================================================\n\n /**\n * Set the edit scope\n */\n setScope(scope: Partial<EditScope>): void {\n this.scope = { ...this.scope, ...scope };\n }\n\n /**\n * Get the current scope\n */\n getScope(): EditScope {\n return { ...this.scope };\n }\n\n // ===========================================================================\n // Preview & Summary\n // ===========================================================================\n\n /**\n * Get diffs for manual changes\n */\n getDiff(): ComponentDiff[] {\n const diffs: ComponentDiff[] = [];\n\n for (const [name, edited] of Object.entries(this.editedContent)) {\n const original = this.loadedComponents[name] || '';\n if (DiffEngine.hasSignificantChanges(original, edited)) {\n diffs.push(DiffEngine.createComponentDiff(name, original, edited));\n }\n }\n\n return diffs;\n }\n\n /**\n * Preview what prompts will be sent to AI\n */\n previewPrompt(): Record<RegeneratableComponent, string> {\n const result: Record<string, string> = {};\n\n if (!this.entity) return result as Record<RegeneratableComponent, string>;\n\n const entityContext = {\n pi: this.entity.id,\n ver: this.entity.ver,\n parentPi: this.entity.parent_pi,\n childrenCount: this.entity.children_pi?.length ?? 0,\n currentContent: this.loadedComponents,\n };\n\n for (const component of this.scope.components) {\n let prompt: string;\n\n if (this.mode === 'ai-prompt') {\n // AI prompt mode: use user's prompt\n const componentPrompt = this.prompts[component];\n const generalPrompt = this.prompts['general'];\n const combined = PromptBuilder.buildCombinedPrompt(generalPrompt, componentPrompt, component);\n prompt = PromptBuilder.buildAIPrompt(\n combined,\n component,\n entityContext,\n this.loadedComponents[`${component}.json`] || this.loadedComponents[`${component}.md`]\n );\n } else {\n // Manual mode: build from diffs and corrections\n const diffs = this.getDiff();\n const userInstructions = this.prompts['general'] || this.prompts[component];\n prompt = PromptBuilder.buildEditReviewPrompt(diffs, this.corrections, component, userInstructions);\n }\n\n // Add cascade context if applicable\n if (this.scope.cascade) {\n prompt = PromptBuilder.buildCascadePrompt(prompt, {\n path: [this.entity.id, this.entity.parent_pi || 'root'].filter(Boolean) as string[],\n depth: 0,\n stopAtPi: this.scope.stopAtPi,\n });\n }\n\n result[component] = prompt;\n }\n\n return result as Record<RegeneratableComponent, string>;\n }\n\n /**\n * Get a summary of pending changes\n */\n getChangeSummary(): ChangeSummary {\n const diffs = this.getDiff();\n const hasManualEdits = diffs.some((d) => d.hasChanges);\n\n return {\n mode: this.mode,\n hasManualEdits,\n editedComponents: Object.keys(this.editedContent),\n corrections: [...this.corrections],\n prompts: { ...this.prompts },\n scope: { ...this.scope },\n willRegenerate: [...this.scope.components],\n willCascade: this.scope.cascade,\n willSave: hasManualEdits,\n willReprocess: this.scope.components.length > 0,\n };\n }\n\n // ===========================================================================\n // Execution\n // ===========================================================================\n\n /**\n * Submit changes (saves first if manual edits, then reprocesses)\n */\n async submit(note: string): Promise<EditResult> {\n if (this.submitting) {\n throw new ValidationError('Submit already in progress');\n }\n if (!this.entity) {\n throw new ValidationError('Session not loaded. Call load() first.');\n }\n\n this.submitting = true;\n this.result = {};\n\n try {\n // Phase 1: Save manual edits if any\n const diffs = this.getDiff();\n const hasManualEdits = diffs.some((d) => d.hasChanges);\n\n if (hasManualEdits) {\n // Upload edited components and collect CIDs\n const componentUpdates: Record<string, string> = {};\n\n for (const [name, content] of Object.entries(this.editedContent)) {\n const original = this.loadedComponents[name] || '';\n if (DiffEngine.hasSignificantChanges(original, content)) {\n const cid = await this.client.uploadContent(content, name);\n componentUpdates[name] = cid;\n }\n }\n\n // Update entity\n const version = await this.client.updateEntity(this.pi, {\n expect_tip: this.entity.manifest_cid,\n components: componentUpdates,\n note,\n });\n\n this.result.saved = {\n pi: version.id,\n newVersion: version.ver,\n newTip: version.tip,\n };\n\n // Update our entity reference\n this.entity.manifest_cid = version.tip;\n this.entity.ver = version.ver;\n }\n\n // Phase 2: Trigger reprocessing if components selected\n if (this.scope.components.length > 0) {\n const customPrompts = this.buildCustomPrompts();\n\n const reprocessResult = await this.client.reprocess({\n pi: this.pi,\n phases: this.scope.components,\n cascade: this.scope.cascade,\n options: {\n stop_at_pi: this.scope.stopAtPi,\n custom_prompts: customPrompts,\n custom_note: note,\n },\n });\n\n this.result.reprocess = reprocessResult;\n this.statusUrl = reprocessResult.status_url;\n }\n\n return this.result;\n } finally {\n this.submitting = false;\n }\n }\n\n /**\n * Wait for reprocessing to complete\n */\n async waitForCompletion(options?: PollOptions): Promise<EditStatus> {\n const opts = { ...DEFAULT_POLL_OPTIONS, ...options };\n\n if (!this.statusUrl) {\n return {\n phase: 'complete',\n saveComplete: true,\n };\n }\n\n const startTime = Date.now();\n let isFirstPoll = true;\n\n while (true) {\n // Pass isFirstPoll flag - the client will use longer retry delays on first poll\n // since the orchestrator often needs time to initialize after reprocess is triggered\n const status = await this.client.getReprocessStatus(this.statusUrl, isFirstPoll);\n isFirstPoll = false;\n\n const editStatus: EditStatus = {\n phase: status.status === 'DONE' ? 'complete' : status.status === 'ERROR' ? 'error' : 'reprocessing',\n saveComplete: true,\n reprocessStatus: status,\n error: status.error,\n };\n\n if (opts.onProgress) {\n opts.onProgress(editStatus);\n }\n\n if (status.status === 'DONE' || status.status === 'ERROR') {\n return editStatus;\n }\n\n if (Date.now() - startTime > opts.timeoutMs) {\n return {\n phase: 'error',\n saveComplete: true,\n reprocessStatus: status,\n error: 'Timeout waiting for reprocessing to complete',\n };\n }\n\n await new Promise((resolve) => setTimeout(resolve, opts.intervalMs));\n }\n }\n\n /**\n * Get current status without waiting\n */\n async getStatus(): Promise<EditStatus> {\n if (!this.statusUrl) {\n return {\n phase: this.result?.saved ? 'complete' : 'idle',\n saveComplete: !!this.result?.saved,\n };\n }\n\n const status = await this.client.getReprocessStatus(this.statusUrl);\n\n return {\n phase: status.status === 'DONE' ? 'complete' : status.status === 'ERROR' ? 'error' : 'reprocessing',\n saveComplete: true,\n reprocessStatus: status,\n error: status.error,\n };\n }\n\n // ===========================================================================\n // Private Helpers\n // ===========================================================================\n\n private buildCustomPrompts(): CustomPrompts {\n const custom: CustomPrompts = {};\n\n // In AI prompt mode, prompts go directly to reprocess API\n if (this.mode === 'ai-prompt') {\n if (this.prompts['general']) custom.general = this.prompts['general'];\n if (this.prompts['pinax']) custom.pinax = this.prompts['pinax'];\n if (this.prompts['description']) custom.description = this.prompts['description'];\n if (this.prompts['cheimarros']) custom.cheimarros = this.prompts['cheimarros'];\n } else {\n // Manual mode: build prompts from diffs, corrections, and user instructions\n const diffs = this.getDiff();\n const diffContext = DiffEngine.formatComponentDiffsForPrompt(diffs);\n const correctionContext = PromptBuilder.buildCorrectionPrompt(this.corrections);\n\n // Combine all context: diffs + corrections + user instructions\n const basePrompt = [diffContext, correctionContext, this.prompts['general']]\n .filter(Boolean)\n .join('\\n\\n');\n\n if (basePrompt) {\n custom.general = basePrompt;\n }\n\n // Component-specific prompts\n if (this.prompts['pinax']) custom.pinax = this.prompts['pinax'];\n if (this.prompts['description']) custom.description = this.prompts['description'];\n if (this.prompts['cheimarros']) custom.cheimarros = this.prompts['cheimarros'];\n }\n\n return custom;\n }\n}\n"],"mappings":";AAsoBO,IAAM,uBAAoC;AAAA,EAC/C,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,UAAU;AAAA,EACV,cAAc;AAChB;;;ACpoBO,IAAM,YAAN,cAAwB,MAAM;AAAA,EACnC,YACE,SACO,OAAe,iBACf,SACP;AACA,UAAM,OAAO;AAHN;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,sBAAN,cAAkC,UAAU;AAAA,EACjD,YAAY,IAAY;AACtB,UAAM,qBAAqB,EAAE,IAAI,oBAAoB,EAAE,GAAG,CAAC;AAC3D,SAAK,OAAO;AAAA,EACd;AACF;AAMO,IAAM,mBAAN,cAA+B,UAAU;AAAA,EAC9C,YAAY,IA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