@granular-software/sdk 0.4.80 → 0.4.81

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.
@@ -271,6 +271,347 @@ declare class EventsFeed {
271
271
  }
272
272
  declare function eventsFeedSearch(filter: EventsFeedFilter): string;
273
273
 
274
+ /** Versioned JSON contract: no Effect values, Error instances, or credentials. */
275
+ type VersionToken = string | number;
276
+ type MutationResource = {
277
+ resource: string;
278
+ key: string;
279
+ };
280
+ type MutationConcurrency = (MutationResource | {
281
+ resources: MutationResource[];
282
+ }) & {
283
+ scope?: "environment" | "sandbox";
284
+ };
285
+ /** Trusted provider contract: compare the precondition and mutate/store this receipt atomically. */
286
+ type MutationReceipt<A = unknown> = {
287
+ protocol: "granular.mutation.v1";
288
+ operationId: string;
289
+ terminal: true;
290
+ precondition: VersionToken;
291
+ } & ({
292
+ outcome: "committed";
293
+ result: A;
294
+ } | {
295
+ outcome: "not_committed";
296
+ fenced: true;
297
+ fenceToken: string;
298
+ reason: "VersionConflict" | "FencedOperation";
299
+ } | {
300
+ outcome: "not_committed";
301
+ fenced: true;
302
+ fenceToken: string;
303
+ reason: "Rejected";
304
+ failure: {
305
+ code: "PolicyDenied" | "InvalidInput" | "ProviderFailure";
306
+ message: string;
307
+ ruleIds?: string[];
308
+ declaredTag?: string;
309
+ };
310
+ });
311
+ type FailureCode = "BudgetExceeded" | "JobTypeError" | "VersionConflict" | "FencedOperation" | "ConcurrentMutation" | "RetryBlocked" | "OperationKeyMismatch" | "PolicyDenied" | "ApprovalRequired" | "InvalidInput" | "ProviderFailure" | "TransportFailure" | "PostconditionFailed" | "JobLogicFailure" | "RuntimeDefect" | "JobDefect" | "Interrupted";
312
+ interface JobFailureDetails {
313
+ sourceDiagnostics?: Array<{
314
+ code: number;
315
+ message: string;
316
+ line?: number;
317
+ column?: number;
318
+ }>;
319
+ id: string;
320
+ message: string;
321
+ /** Guest defect stack, bounded and diagnostic only. */
322
+ stack?: string;
323
+ declaredTag?: string;
324
+ origin: "safety" | "policy" | "validation" | "provider" | "transport" | "verification" | "runtime" | "job";
325
+ kind: "expected" | "defect" | "interruption";
326
+ operationId?: string;
327
+ relatedOperationId?: string;
328
+ operation?: string;
329
+ ruleIds?: string[];
330
+ causedBy?: string[];
331
+ commit: "not_started" | "unknown" | "committed";
332
+ authority: "host" | "guest";
333
+ }
334
+ type JobFailure = {
335
+ [Code in FailureCode]: JobFailureDetails & {
336
+ code: Code;
337
+ _tag: Code;
338
+ };
339
+ }[FailureCode];
340
+ /** Expected invocation failures; defects and interruption use Effect Cause. */
341
+ type DomainFailure = Exclude<JobFailure, {
342
+ _tag: "JobTypeError" | "JobDefect" | "RuntimeDefect" | "Interrupted" | "JobLogicFailure";
343
+ }>;
344
+ interface FailureHandling {
345
+ failureId: string;
346
+ action: "caught" | "retry" | "propagated";
347
+ outcome?: "recovered" | "failed";
348
+ causedFailureIds?: string[];
349
+ }
350
+ interface InvocationResolution {
351
+ operationId: string;
352
+ outcome: "committed" | "not_committed";
353
+ source: "provider_ack" | "reconciliation";
354
+ at: number;
355
+ }
356
+ interface JobDiagnostics {
357
+ version: 1;
358
+ resolutions?: InvocationResolution[];
359
+ failures: JobFailure[];
360
+ handling: FailureHandling[];
361
+ unresolved: string[];
362
+ steering: Array<{
363
+ failureId: string;
364
+ action: "coordinate" | "refresh" | "respect_policy" | "request_approval" | "repair_input" | "reconcile" | "recover_verification" | "repair_code" | "inspect_failure" | "stop";
365
+ message: string;
366
+ }>;
367
+ truncated?: boolean;
368
+ }
369
+ declare class JobExecutionError extends Error {
370
+ readonly diagnostics?: JobDiagnostics | undefined;
371
+ constructor(message: string, diagnostics?: JobDiagnostics | undefined);
372
+ }
373
+
374
+ /** Redacted query shapes and observed stage counts, never predicate/search values. */
375
+ interface QueryPredicate {
376
+ field: string;
377
+ operator: string;
378
+ location: "graph" | "runtime";
379
+ }
380
+ interface QueryStage {
381
+ queryId: string;
382
+ stage: "graph.selection" | "host.search" | "runtime.filter" | "pagination";
383
+ location: "graph" | "host" | "runtime" | "graph+host";
384
+ measurement: "separate_counts" | "batch" | "slice";
385
+ before?: number;
386
+ after: number;
387
+ /** Separate-count graph measurements are observed reductions, not atomic per-record rejections. */
388
+ rejected?: number;
389
+ field?: string;
390
+ operator?: string;
391
+ page?: number;
392
+ complete: boolean;
393
+ phase?: "count" | "fetch";
394
+ }
395
+ interface QueryObservation {
396
+ id: string;
397
+ parentId?: string | null;
398
+ className: string;
399
+ operation: string;
400
+ search: boolean;
401
+ predicates: QueryPredicate[];
402
+ predicatesTruncated?: boolean;
403
+ stages: QueryStage[];
404
+ status: string;
405
+ }
406
+ interface ExecutionEvent {
407
+ sequence: number;
408
+ kind: "structure.start" | "structure.end" | "source.open" | "source.close" | "source.page" | "invocation.attempt" | "query.plan" | "query.stage" | "query.end";
409
+ queryId?: string;
410
+ search?: boolean;
411
+ predicatesTruncated?: boolean;
412
+ predicates?: QueryPredicate[];
413
+ queryStage?: QueryStage;
414
+ evaluated?: number;
415
+ accepted?: number;
416
+ rejected?: number;
417
+ predicateFailed?: number;
418
+ pending?: number;
419
+ at: number;
420
+ id?: string;
421
+ parent?: string | null;
422
+ fiber?: number;
423
+ structure?: string;
424
+ site?: string;
425
+ status?: string;
426
+ operationId?: string;
427
+ attemptId?: string;
428
+ operation?: string;
429
+ className?: string;
430
+ page?: number;
431
+ returned?: number;
432
+ totalCount?: number;
433
+ emitted?: number;
434
+ iterations?: number;
435
+ }
436
+ interface ExecutionCapture {
437
+ events: ExecutionEvent[];
438
+ complete: boolean;
439
+ truncated: boolean;
440
+ gaps: boolean;
441
+ invalid?: boolean;
442
+ }
443
+ interface ExecutionNode {
444
+ attempts?: Array<{
445
+ attemptId: string;
446
+ at: number;
447
+ }>;
448
+ id: string;
449
+ parentId: string | null;
450
+ kind: string;
451
+ label: string;
452
+ fiber?: number;
453
+ operationId?: string;
454
+ status: string;
455
+ startedAt: number;
456
+ durationMs?: number;
457
+ iterations?: number;
458
+ metrics?: {
459
+ pages?: number;
460
+ read?: number;
461
+ emitted?: number;
462
+ source?: string;
463
+ evaluated?: number;
464
+ accepted?: number;
465
+ rejected?: number;
466
+ predicateFailed?: number;
467
+ pending?: number;
468
+ };
469
+ }
470
+ interface BehaviorFinding {
471
+ id: string;
472
+ code: string;
473
+ severity: "info" | "warning" | "blocked";
474
+ authority: "host" | "guest";
475
+ message: string;
476
+ action: string;
477
+ operationId?: string;
478
+ count?: number;
479
+ }
480
+ interface HostExecutionEvidence {
481
+ version: 1;
482
+ calls: number;
483
+ reads: number;
484
+ /** Admitted write attempts, including provider refusals; not a count of committed mutations. */
485
+ writes: number;
486
+ inFlight: number;
487
+ peakInFlight: number;
488
+ denials: number;
489
+ findings: BehaviorFinding[];
490
+ truncated?: boolean;
491
+ }
492
+ /** Host-recorded advisory semantic judgment; never authorization to mutate. */
493
+ interface ResolutionSteering {
494
+ action: "use_candidate" | "ask_user" | "review_creation" | "agent_resolve";
495
+ reason: "clear_match" | "uncertain_match" | "incomplete_candidates" | "no_match" | "insufficient_information" | "assessment_unavailable" | "zero_candidates" | "source_unverified" | "agent_context_required";
496
+ policyVersion: "granular.record-routing.v1" | "granular.record-routing.v2" | "granular.record-routing.v3" | "granular.record-routing.v4";
497
+ threshold?: number;
498
+ candidateId?: string;
499
+ probability?: number;
500
+ }
501
+ interface ResolutionAssessmentEvidence {
502
+ id: string;
503
+ authority: "host";
504
+ at: number;
505
+ durationMs: number;
506
+ input: {
507
+ state: Record<string, unknown>;
508
+ candidates: Array<Record<string, unknown>>;
509
+ };
510
+ result: {
511
+ probabilities: Record<string, number>;
512
+ metadata: {
513
+ source: "typesafe_choice" | "unavailable" | "agent_context";
514
+ calibrated: false;
515
+ semantics: "choice_over_returned_candidates" | "agent_resolves_returned_candidates";
516
+ questionVersion: string;
517
+ model?: string;
518
+ reason?: string;
519
+ outcome?: "candidate" | "no_match" | "insufficient_information";
520
+ recommendedId?: string;
521
+ noMatchProbability?: number;
522
+ insufficientInformationProbability?: number;
523
+ confidence?: number;
524
+ durationMs: number;
525
+ inputTokens?: number;
526
+ outputTokens?: number;
527
+ evidenceId?: string;
528
+ steering?: ResolutionSteering;
529
+ };
530
+ };
531
+ }
532
+ /** Ordered receipt-time journal. Guest structure remains reported evidence. */
533
+ interface JobEvent {
534
+ version: 1;
535
+ id: string;
536
+ jobId: string;
537
+ sequence: number;
538
+ at: number;
539
+ kind: "lifecycle" | "operation" | "failure" | "handling" | "decision" | "prompt" | "user_decision" | "finding" | "assessment" | "capture" | "commit" | "logs" | "coverage";
540
+ authority: "host" | "guest" | "user";
541
+ summary: string;
542
+ refs: {
543
+ callId?: string;
544
+ operationId?: string;
545
+ relatedOperationId?: string;
546
+ failureId?: string;
547
+ promptId?: string;
548
+ evidenceId?: string;
549
+ commitId?: string;
550
+ causedBy?: string[];
551
+ };
552
+ data: Record<string, string | number | boolean | null | string[] | undefined>;
553
+ }
554
+ interface JobEventPage {
555
+ jobId: string;
556
+ status: string;
557
+ available: boolean;
558
+ lastSequence: number;
559
+ dropped: number;
560
+ gap: boolean;
561
+ items: JobEvent[];
562
+ }
563
+ interface JobEventStream {
564
+ version: 1;
565
+ lastSequence: number;
566
+ dropped: number;
567
+ gap: boolean;
568
+ items: JobEvent[];
569
+ }
570
+ interface JobExecutionReport {
571
+ version: 1;
572
+ jobId: string;
573
+ status: string;
574
+ outcome: "succeeded" | "failed" | "running" | "unknown";
575
+ eventStream?: JobEventStream;
576
+ /** Durable diagnostic prefix; a synchronous console call alone is not an acknowledgement. */
577
+ liveTelemetry?: {
578
+ authority: "guest";
579
+ persistedThrough: number;
580
+ dropped: number;
581
+ logsTruncated: boolean;
582
+ complete: boolean;
583
+ unacknowledgedTail: "none" | "unknown after abrupt loss";
584
+ };
585
+ validation: Record<string, unknown> | null;
586
+ diagnostics: JobDiagnostics | null;
587
+ host: HostExecutionEvidence | null;
588
+ capture: {
589
+ state: "complete" | "partial" | "unavailable";
590
+ events: number;
591
+ scope: "instrumented_control_flow";
592
+ authority: "guest";
593
+ blindSpots: string[];
594
+ };
595
+ nodes: ExecutionNode[];
596
+ queries?: QueryObservation[];
597
+ resolutions?: {
598
+ items: ResolutionAssessmentEvidence[];
599
+ skippedCount: number;
600
+ };
601
+ findings: BehaviorFinding[];
602
+ /** Most recently verified canonical receipt snapshots; inspection refreshes a bounded set. */
603
+ commits?: Array<{
604
+ commitId: string;
605
+ product: {
606
+ status: "committed";
607
+ version?: string;
608
+ };
609
+ agent: {
610
+ status: string;
611
+ };
612
+ }>;
613
+ }
614
+
274
615
  type PolicyOutcome = "allow" | "confirm" | "deny";
275
616
  type PolicySource = "manifest" | "permissionProfile" | "builtin";
276
617
  type PolicyPredicateSource = "input" | "object" | "stateMachine";
@@ -427,6 +768,11 @@ interface DefineRelationshipOptions {
427
768
  * fields are updated in place; otherwise a new instance is created.
428
769
  */
429
770
  interface RecordObjectOptions {
771
+ /** Complete source snapshot, ordered by the declared source revision. */
772
+ projection?: {
773
+ source: string;
774
+ revision: number;
775
+ };
430
776
  /** The class to instantiate (e.g., "author") */
431
777
  className: string;
432
778
  /**
@@ -505,6 +851,11 @@ type EnvironmentStateProxy = {
505
851
  * Return value from `recordObject()`
506
852
  */
507
853
  interface RecordObjectResult {
854
+ projection?: {
855
+ outcome: "applied" | "unchanged" | "superseded";
856
+ revision: number;
857
+ source: string;
858
+ };
508
859
  /** The internal graph path (e.g., "author__tolkien") */
509
860
  path: string;
510
861
  /** The real-world object ID as provided by the caller (e.g., "tolkien") */
@@ -533,6 +884,7 @@ interface RecordObjectsChunkInfo {
533
884
  * Optional tuning for `recordObjects()` — batching, parallelism, and progress hooks.
534
885
  */
535
886
  interface RecordObjectsOptions {
887
+ signal?: AbortSignal;
536
888
  /**
537
889
  * Max records per HTTP POST to the control-plane batch endpoint. Default 100.
538
890
  * Smaller values: more round trips and finer `onChunkComplete` updates.
@@ -923,6 +1275,20 @@ interface SemanticVersionDiff {
923
1275
  entries: SemanticVersionDiffEntry[];
924
1276
  }
925
1277
 
1278
+ interface CustomerSkillIdentity {
1279
+ identityId: string;
1280
+ providerSubject: string;
1281
+ displayName: string;
1282
+ }
1283
+ interface CustomerSkillAuthorization {
1284
+ /** Reuse the product's ordinary server-session check. Return null after logout. */
1285
+ authenticate(request: Request): CustomerSkillIdentity | null | Promise<CustomerSkillIdentity | null>;
1286
+ loginUrl: string;
1287
+ /** Server-held, model-specific channel credential issued/configured by Granular. */
1288
+ serviceToken: string;
1289
+ fetch?: typeof fetch;
1290
+ }
1291
+
926
1292
  /** Public installation metadata is separate from product-owned customer authority. */
927
1293
  interface CustomerSkillRegistration {
928
1294
  productModelId: string;
@@ -935,10 +1301,12 @@ interface CustomerSkillOptions {
935
1301
  runtimeOrigin: string;
936
1302
  /** Resolve an existing product-authorized one-use launch for the signed-in customer.
937
1303
  * The callback owns ordinary product session checks. Never use a developer test ticket. */
938
- resolveLaunch(request: Request): Promise<{
1304
+ resolveLaunch?(request: Request): Promise<{
939
1305
  launch: string;
940
1306
  productModelId: string;
941
1307
  } | Response | null>;
1308
+ /** Standard setup flow using the product's existing server-session check. */
1309
+ customerSession?: CustomerSkillAuthorization;
942
1310
  }
943
1311
  declare function customerSkillSlug(name: string): string;
944
1312
  declare function customerSkillOrigin(value: string): string;
@@ -1765,1775 +2133,1881 @@ interface ArtifactApprovalDecisionResult {
1765
2133
  alreadyDecided?: boolean;
1766
2134
  }
1767
2135
 
1768
- interface ObjectReference {
1769
- className: string;
1770
- id: string;
1771
- /** Canonical graph path, when already known. */
1772
- path?: string;
1773
- }
1774
- interface SourceAcknowledgement {
1775
- /** Stable product-side operation or record reference. */
1776
- reference: string;
1777
- /** Monotonic product version, causal token, or serialized adapter sequence. */
1778
- version?: string;
1779
- /**
1780
- * Declares what the version orders. `global` may safely order every target
1781
- * in one atomic projection; `target` (and omission) is scoped to each
1782
- * affected target and cannot bridge missing target watermarks.
1783
- */
1784
- versionScope?: "global" | "target";
1785
- }
1786
- interface CommitSafeError {
1787
- code: string;
1788
- message: string;
1789
- retryable: boolean;
1790
- fieldPath?: string;
1791
- }
1792
- interface TransitionOutcomeProjection {
1793
- /** Authored source outcome key, mapped by the active transition declaration. */
1794
- key: string;
1795
- error?: CommitSafeError;
2136
+ type FeedSourceActor = "user" | "agent" | "system" | "customer_method";
2137
+ interface FeedSource {
2138
+ actor: FeedSourceActor;
2139
+ clientId?: string;
2140
+ /** Stable authored handle for a transient producer, when available. */
2141
+ operationId?: string;
2142
+ jobId?: string;
2143
+ turnId?: string;
2144
+ method?: string;
1796
2145
  }
1797
- interface CanonicalProjectedRecord {
2146
+ type FeedIconToken = "neutral" | "info" | "database" | "search" | "clock" | "sparkles" | "check" | "warning" | "error";
2147
+ type FeedFeedbackTone = "info" | "working" | "awaiting" | "success" | "warning" | "error";
2148
+ /** Tones that describe live state; terminal success belongs in durable history. */
2149
+ type FeedTransientFeedbackTone = Exclude<FeedFeedbackTone, "success">;
2150
+ type FeedItemKind = "message" | "feedback" | "objects" | "table" | "artifact" | "file" | "action_suggestion" | "prompt";
2151
+ interface FeedTarget {
1798
2152
  className: string;
1799
2153
  id: string;
1800
2154
  label?: string;
1801
- fields: Record<string, string | number | boolean | null>;
1802
2155
  }
1803
- type ObjectProjectionChange = {
1804
- kind: "object";
1805
- operation: "created" | "updated";
1806
- record: CanonicalProjectedRecord;
1807
- } | {
1808
- kind: "object";
1809
- operation: "deleted";
1810
- target: ObjectReference;
1811
- };
1812
- interface RelationshipProjectionChange {
1813
- kind: "relationship";
1814
- operation: "connected" | "disconnected";
1815
- relationship: string;
1816
- from: ObjectReference;
1817
- to: ObjectReference;
2156
+ interface FeedItemBase {
2157
+ id: string;
2158
+ sequence: number;
2159
+ occurredAt: number;
2160
+ kind: FeedItemKind;
2161
+ operationId: string;
2162
+ batchIndex: number;
2163
+ source?: FeedSource;
1818
2164
  }
1819
- interface StateObservationProjectionChange {
1820
- kind: "state_observation";
1821
- target: ObjectReference;
1822
- machine: string;
1823
- state: string;
2165
+ interface MessageFeedItem extends FeedItemBase {
2166
+ kind: "message";
2167
+ payload: {
2168
+ role: "user" | "assistant" | "system";
2169
+ text: string;
2170
+ format?: "plain_text" | "markdown";
2171
+ target?: FeedTarget;
2172
+ inReplyToPromptId?: string;
2173
+ answer?: string | number | boolean | null;
2174
+ answerDisplay?: string;
2175
+ };
1824
2176
  }
1825
- type ProjectionChange = ObjectProjectionChange | RelationshipProjectionChange | StateObservationProjectionChange;
1826
- interface BaseProjectionResult {
1827
- source: SourceAcknowledgement;
1828
- primaryTarget?: ObjectReference;
1829
- changes: ProjectionChange[];
1830
- safeSummary?: Record<string, string | number | boolean | null>;
2177
+ interface FeedbackFeedItem extends FeedItemBase {
2178
+ kind: "feedback";
2179
+ payload: {
2180
+ text: string;
2181
+ icon?: FeedIconToken;
2182
+ tone: FeedFeedbackTone;
2183
+ audience: "customer";
2184
+ action?: {
2185
+ actionId: string;
2186
+ kind: "frontend" | "backend" | "system";
2187
+ label: string;
2188
+ status: "queued" | "done" | "failed";
2189
+ };
2190
+ code?: string;
2191
+ };
1831
2192
  }
1832
- type EffectProjectionResult = BaseProjectionResult & {
1833
- outcome?: never;
1834
- };
1835
- type TransitionProjectionResult = BaseProjectionResult & {
1836
- outcome: TransitionOutcomeProjection;
1837
- };
1838
- type ProjectionResult = EffectProjectionResult | TransitionProjectionResult;
1839
- type ProjectionMapper<TResult, TProjection extends ProjectionResult = ProjectionResult> = (result: Readonly<TResult>) => TProjection;
1840
- type CommitDeclaration<TResult = any> = {
1841
- kind: "effect";
1842
- project: ProjectionMapper<TResult, EffectProjectionResult>;
2193
+ type FeedObjectReference = {
2194
+ type: "entry";
2195
+ path: string;
1843
2196
  } | {
1844
- kind: "transition";
1845
- project: ProjectionMapper<TResult, TransitionProjectionResult>;
1846
- /** Automatic snapshot mappers select by product state; custom mappers select an explicit key. */
1847
- outcomeSelection?: "explicit" | "product_state";
2197
+ type: "list";
2198
+ name: string;
2199
+ } | {
2200
+ type: "variable";
2201
+ name: string;
1848
2202
  };
1849
- type AgentCommitStatus = "not_requested" | "pending" | "syncing" | "synced" | "failed" | "reconciling";
1850
- interface CommitChangeReceipt {
1851
- changeId: string;
1852
- kind: ProjectionChange["kind"] | "state_transition";
1853
- operation: string;
1854
- target: ObjectReference;
1855
- label?: string;
1856
- path?: string;
1857
- status: "pending" | "applied" | "already_applied" | "failed";
1858
- error?: CommitSafeError;
2203
+ interface ObjectsFeedItem extends FeedItemBase {
2204
+ kind: "objects";
2205
+ payload: {
2206
+ label?: string;
2207
+ refs: FeedObjectReference[];
2208
+ fallback?: Array<{
2209
+ className?: string;
2210
+ id: string;
2211
+ label?: string;
2212
+ }>;
2213
+ };
1859
2214
  }
1860
- interface CommitTransitionReceipt {
1861
- machine: string;
1862
- transition: string;
1863
- from: string;
1864
- outcome: string;
1865
- to: string;
1866
- disposition: "continue" | "error";
2215
+ type FeedTableCell = string | number | boolean | null | {
2216
+ kind: "relative_time" | "date";
2217
+ value: string | number;
2218
+ };
2219
+ interface FeedTableColumn {
2220
+ id: string;
2221
+ label: string;
1867
2222
  }
1868
- interface CommitReceipt {
1869
- commitId: string;
1870
- kind: "effect" | "transition";
1871
- deduplicated: boolean;
1872
- product: {
1873
- status: "committed";
1874
- reference: string;
1875
- version?: string;
1876
- };
1877
- agent: {
1878
- status: AgentCommitStatus;
1879
- environmentId?: string;
1880
- };
1881
- primaryTarget?: ObjectReference;
1882
- affected: CommitChangeReceipt[];
1883
- transition?: CommitTransitionReceipt;
1884
- createdAt: string;
1885
- updatedAt: string;
2223
+ interface FeedTableRowReference {
2224
+ entryPath?: string;
2225
+ className?: string;
2226
+ id?: string;
2227
+ label?: string;
1886
2228
  }
1887
- interface ExternalCommitOptions {
1888
- /** Stable product webhook or change-log event identity. */
1889
- sourceEventId?: string;
2229
+ interface FeedTableRow {
2230
+ id: string;
2231
+ reference?: FeedTableRowReference;
2232
+ cells: FeedTableCell[];
1890
2233
  }
1891
- interface ObservationReceipt {
1892
- observationId: string;
1893
- deduplicated: boolean;
1894
- source: SourceAcknowledgement;
1895
- agent: {
1896
- status: AgentCommitStatus;
1897
- environmentId: string;
1898
- };
1899
- affected: CommitChangeReceipt[];
1900
- createdAt: string;
1901
- updatedAt: string;
2234
+ interface FeedTableProjection {
2235
+ id: string;
2236
+ label?: string;
2237
+ source?: string;
2238
+ columns: FeedTableColumn[];
2239
+ rows: FeedTableRow[];
1902
2240
  }
1903
- /** Payload-free evidence from retained session run reports. */
1904
- interface SessionHistoryRunEvidence {
1905
- source: "retained_run_report";
1906
- goalDecision: {
1907
- source: "harness_goal_evaluation";
1908
- decision: "satisfied" | "partial" | "confirmation_denied" | "blocked_by_policy" | "impossible" | "interrupted" | "blocked_by_missing_capability" | "await_user" | "continue" | "no_progress" | "repair_code" | "retry_job" | "retry_prepared" | null;
1909
- criteria: {
1910
- passed: number;
1911
- failed: number;
1912
- notApplicable: number;
1913
- unknown: number;
1914
- } | null;
2241
+ interface TableFeedItem extends FeedItemBase {
2242
+ kind: "table";
2243
+ payload: {
2244
+ tableId: string;
2245
+ label?: string;
2246
+ columns: FeedTableColumn[];
2247
+ rows: FeedTableRow[];
2248
+ truncated?: boolean;
1915
2249
  };
1916
- approval: "not_recorded";
1917
- actor: "not_recorded";
1918
- build: "not_recorded";
1919
- }
1920
- /** Persisted ledger facts; missing fields must remain unknown for old records. */
1921
- interface SessionMutationEvidence {
1922
- source: "commit_ledger";
1923
- invocationStatus: "reserved" | "running" | "failed" | "unknown" | "mapping_failed" | "committed";
1924
- ontologyBuildId?: string;
1925
- /** False means no correlated retained commit, not proof that the product was unchanged. */
1926
- productCommitRecorded: boolean;
1927
- /** Agent projection attempts, distinct from product execution attempts. */
1928
- agentAttempts?: number;
1929
- committedAt?: string;
1930
- completedAt?: string;
1931
- approval: "not_recorded";
1932
- actor: "not_recorded";
1933
2250
  }
1934
- /** A recorded human answer; it does not establish product execution or commit. */
1935
- interface SessionPolicyDecisionReceipt {
1936
- schemaVersion: 1;
1937
- source: "persisted_human_prompt";
1938
- promptId: string;
1939
- artifactId: string;
1940
- jobId: string;
1941
- decision: "approved" | "denied";
1942
- answeredAt: number;
1943
- recordedAt: number;
1944
- executionScope?: {
1945
- attemptId: string;
1946
- effectKey: string;
2251
+ interface ArtifactFeedItem extends FeedItemBase {
2252
+ kind: "artifact";
2253
+ payload: {
2254
+ artifactId: string;
2255
+ fallback: {
2256
+ kind: "effect" | "batch" | "state_path";
2257
+ label: string;
2258
+ status?: string;
2259
+ description?: string;
2260
+ target?: FeedTarget;
2261
+ };
1947
2262
  };
1948
2263
  }
1949
- interface SessionHistoryArtifactExecutionLink {
1950
- source: "session_artifact_execution";
1951
- artifactId: string;
1952
- jobId: string | null;
1953
- attemptId: string;
1954
- invocationId: string;
1955
- effectKey: string;
1956
- /** Artifact attempt start, not proof of physical product dispatch. */
1957
- startedAt: number;
1958
- approval: "recorded" | "not_recorded";
1959
- policyDecision?: SessionPolicyDecisionReceipt;
1960
- commit: "recorded" | "not_recorded";
1961
- commitId?: string;
1962
- committedAt?: string;
1963
- commitRecordedAt?: number;
2264
+ type FeedFileSource = "dock" | "sdk" | "agent" | "runtime" | "processor" | "library" | "imported";
2265
+ interface FileFeedItem extends FeedItemBase {
2266
+ kind: "file";
2267
+ payload: {
2268
+ fileId: string;
2269
+ fallback: {
2270
+ filename: string;
2271
+ contentType?: string;
2272
+ byteLength?: number;
2273
+ status?: string;
2274
+ source?: FeedFileSource;
2275
+ };
2276
+ };
1964
2277
  }
1965
- interface SessionHistoryArtifactEvidence {
1966
- source: "session_artifact_timeline";
1967
- policyDecision: "recorded" | "not_recorded";
1968
- policyDecisions: SessionPolicyDecisionReceipt[];
1969
- executionLinks?: SessionHistoryArtifactExecutionLink[];
1970
- actor: "not_recorded";
1971
- completeness: "retained_only";
2278
+ /**
2279
+ * The bounded subset needed to create an artifact from a suggestion.
2280
+ *
2281
+ * This is deliberately data-only. It must never contain executable UI or
2282
+ * callback values.
2283
+ */
2284
+ interface NormalizedSuggestedArtifact {
2285
+ version?: 1;
2286
+ kind: "effect" | "batch" | "state_path";
2287
+ label: string;
2288
+ description?: string;
2289
+ status?: string;
2290
+ target?: FeedTarget;
2291
+ inputSchema?: Record<string, unknown>;
2292
+ inputValues?: Record<string, unknown>;
2293
+ relationships?: Record<string, string | string[] | null>;
2294
+ policy?: Record<string, unknown>;
2295
+ statePlan?: Record<string, unknown>;
2296
+ metadata?: Record<string, unknown>;
1972
2297
  }
1973
- interface SessionMutationView {
1974
- evidence?: SessionMutationEvidence;
1975
- invocationId: string;
1976
- commitId?: string;
1977
- jobId?: string;
1978
- artifactId?: string;
1979
- kind: "effect" | "transition";
1980
- operationLabel: string;
1981
- phase: "updating_product" | "checking_product_outcome" | "product_failed" | "updating_agent" | "ready" | "attention";
1982
- product: {
1983
- displayName: string;
1984
- status: "pending" | "updated" | "failed" | "checking";
1985
- };
1986
- agent: {
1987
- displayName: string;
1988
- status: "not_needed" | "pending" | "updating" | "ready" | "failed";
2298
+ interface ActionSuggestionFeedItem extends FeedItemBase {
2299
+ kind: "action_suggestion";
2300
+ payload: {
2301
+ suggestionId: string;
2302
+ label: string;
2303
+ description?: string;
2304
+ target?: FeedTarget;
2305
+ proposedArtifact?: NormalizedSuggestedArtifact;
1989
2306
  };
1990
- primaryTarget?: ObjectReference;
1991
- affected: CommitChangeReceipt[];
1992
- transition?: CommitTransitionReceipt;
1993
- error?: CommitSafeError;
1994
- createdAt: string;
1995
- updatedAt: string;
1996
2307
  }
1997
- interface CommitTransitionOutcomeDeclaration {
1998
- label?: string;
1999
- to: string | "$current";
2000
- primary?: boolean;
2001
- disposition: "continue" | "error";
2308
+ interface PromptFeedItem extends FeedItemBase {
2309
+ kind: "prompt";
2310
+ payload: {
2311
+ promptId: string;
2312
+ type: "choice" | "confirm" | "input";
2313
+ title: string;
2314
+ message: string;
2315
+ options?: Array<{
2316
+ value: string;
2317
+ label: string;
2318
+ }>;
2319
+ placeholder?: string;
2320
+ defaultValue?: string | boolean | null;
2321
+ allowEmpty?: boolean;
2322
+ openedAt: number;
2323
+ };
2002
2324
  }
2003
- interface CommitTransitionInvocation {
2004
- className: string;
2005
- objectId: string;
2006
- objectPath?: string;
2007
- machine: string;
2008
- transition: string;
2009
- from: string;
2010
- outcomes: Record<string, CommitTransitionOutcomeDeclaration>;
2011
- fencingToken?: string;
2012
- /** Internal coordinator identity used to hold one lock across a state goal. */
2013
- lockOwnerId?: string;
2325
+ type FeedItem = MessageFeedItem | FeedbackFeedItem | ObjectsFeedItem | TableFeedItem | ArtifactFeedItem | FileFeedItem | ActionSuggestionFeedItem | PromptFeedItem;
2326
+ interface TransientFeedItemBase {
2327
+ id: string;
2328
+ ordinal: number;
2329
+ revision: number;
2330
+ createdAt: number;
2331
+ updatedAt: number;
2332
+ expiresAt?: number;
2333
+ source?: Omit<FeedSource, "actor" | "clientId"> & {
2334
+ actor: Exclude<FeedSourceActor, "user">;
2335
+ promptId?: string;
2336
+ };
2014
2337
  }
2015
- interface EffectCommitContext {
2016
- effect(productResult: unknown): Promise<CommitReceipt>;
2017
- transition(productResult: unknown): Promise<CommitReceipt>;
2338
+ interface TransientMessageFeedItem extends TransientFeedItemBase {
2339
+ kind: "message";
2340
+ producerRevision: number;
2341
+ payload: {
2342
+ role: "assistant";
2343
+ text: string;
2344
+ format?: "plain_text" | "markdown";
2345
+ };
2018
2346
  }
2019
- /** Wire-safe payload produced after a local declaration mapper runs. */
2020
- interface EffectCommitRequest {
2021
- kind: "effect" | "transition";
2022
- effectKey: string;
2023
- effectName: string;
2024
- operationLabel: string;
2025
- invocationId: string;
2026
- idempotencyKey: string;
2027
- sandboxId: string;
2028
- environmentId: string;
2029
- sessionId?: string;
2030
- jobId?: string;
2031
- artifactId?: string;
2032
- buildId?: string;
2033
- projection: ProjectionResult;
2034
- transition?: CommitTransitionInvocation;
2035
- }
2036
-
2037
- interface WSDisconnectInfo {
2038
- code?: number;
2039
- reason?: string;
2040
- wasClean?: boolean;
2041
- unexpected: boolean;
2042
- timestamp: number;
2043
- reconnectScheduled: boolean;
2044
- reconnectDelayMs?: number;
2347
+ interface TransientFeedbackFeedItem extends TransientFeedItemBase {
2348
+ kind: "feedback";
2349
+ payload: {
2350
+ text: string;
2351
+ icon?: FeedIconToken;
2352
+ tone: FeedTransientFeedbackTone;
2353
+ audience: "customer";
2354
+ };
2045
2355
  }
2046
- interface WSReconnectErrorInfo {
2047
- sessionId: string;
2048
- error: string;
2049
- timestamp: number;
2050
- terminal: boolean;
2356
+ type TransientFeedItem = TransientMessageFeedItem | TransientFeedbackFeedItem;
2357
+ interface FeedSnapshot {
2358
+ tail: FeedItem[];
2359
+ transients: TransientFeedItem[];
2360
+ revision: number;
2361
+ documentEpoch: number;
2362
+ documentRevision: number;
2363
+ lastSequence: number;
2364
+ archivedThroughSequence: number;
2365
+ hasOlder: boolean;
2366
+ isHydrated: boolean;
2367
+ isRepairing: boolean;
2368
+ error: Error | null;
2051
2369
  }
2052
- interface WSClientOptions {
2053
- url: string;
2054
- sessionId: string;
2055
- token: string;
2056
- initialDocumentSnapshot?: Record<string, unknown> | Uint8Array | null;
2057
- tokenProvider?: AccessTokenProvider;
2058
- WebSocketCtor?: any;
2059
- /** Maximum time for one socket open attempt before reconnect may continue. */
2060
- connectTimeoutMs?: number;
2061
- maxReconnectAttempts?: number;
2062
- reconnectDelayMs?: number;
2063
- onUnexpectedClose?: (info: WSDisconnectInfo) => void;
2064
- onReconnectError?: (info: WSReconnectErrorInfo) => void;
2370
+ interface FeedListOptions {
2371
+ afterSequence?: number;
2372
+ beforeSequence?: number;
2373
+ limit?: number;
2065
2374
  }
2066
- interface RPCRequest {
2067
- type: "rpc";
2068
- method: string;
2069
- params: unknown;
2070
- id: string;
2375
+ interface FeedPage {
2376
+ items: FeedItem[];
2377
+ firstSequence: number | null;
2378
+ lastSequence: number | null;
2379
+ hasMoreBefore: boolean;
2380
+ hasMoreAfter: boolean;
2071
2381
  }
2072
- interface RPCResponse {
2073
- type: "rpc_result" | "rpc_error";
2074
- id: string;
2075
- result?: unknown;
2076
- error?: {
2077
- code: number;
2078
- message: string;
2079
- data?: unknown;
2080
- };
2382
+ interface FeedSubscribeOptions {
2383
+ afterSequence?: number;
2081
2384
  }
2082
- interface SnapshotResetMessage {
2083
- type: "snapshot_reset";
2084
- documentEpoch: number;
2385
+ type FeedSubscriptionChange = {
2386
+ type: "append";
2387
+ items: FeedItem[];
2388
+ } | {
2389
+ type: "transients";
2390
+ items: TransientFeedItem[];
2391
+ revision: number;
2392
+ } | {
2393
+ type: "resource_refresh";
2085
2394
  documentRevision: number;
2086
- /** Legacy Automerge binary replacement payload. */
2087
- data?: number[];
2088
- /** Server-authoritative JSON replacement payload. */
2089
- document?: Record<string, unknown>;
2395
+ resourceIds?: string[];
2396
+ } | {
2397
+ type: "reset";
2398
+ snapshot: FeedSnapshot;
2399
+ };
2400
+ interface SessionFeedApi {
2401
+ getSnapshot(): FeedSnapshot;
2402
+ list(options?: FeedListOptions): Promise<FeedPage>;
2403
+ subscribe(listener: (change: FeedSubscriptionChange) => void, options?: FeedSubscribeOptions): () => void;
2090
2404
  }
2091
2405
  /**
2092
- * High-frequency job presentation update. It deliberately carries only the
2093
- * bounded trace for one job; it is not a canonical document revision and must
2094
- * not be treated as a replacement for the session snapshot.
2406
+ * Merge independently contiguous archive/live collections by authoritative
2407
+ * sequence. Expected overlap collapses by occurrence identity; conflicting
2408
+ * IDs or positions fail closed.
2095
2409
  */
2096
- interface JobActionTraceMessage {
2097
- type: "job_action_trace";
2098
- jobId: string;
2099
- documentEpoch: number;
2100
- documentRevision: number;
2101
- actionTrace: Array<Record<string, unknown>>;
2102
- actionSummary: string[];
2103
- actionSummaryText: string;
2104
- }
2410
+ declare function mergeFeedItemsBySequence(...collections: ReadonlyArray<readonly FeedItem[]>): FeedItem[];
2105
2411
  /**
2106
- * Bounded live-feed overlay update. It carries no canonical document
2107
- * revision: a transient is presentation state and must not create a full
2108
- * snapshot/history entry just because its text changed.
2412
+ * Select the newest revision of each transient and preserve server ordinal
2413
+ * order. Duplicate ordinal ownership is a chronology violation.
2109
2414
  */
2110
- interface FeedTransientPatchMessage {
2111
- type: "feed_transient_patch";
2112
- documentEpoch: number;
2113
- documentRevision: number;
2114
- feedRevision: number;
2115
- lastTransientOrdinal: number;
2116
- changes: Array<{
2117
- transientId: string;
2118
- item?: Record<string, unknown>;
2119
- removed?: boolean;
2120
- }>;
2121
- }
2122
- interface RPCRequestFromServer {
2123
- type: "rpc";
2124
- method: string;
2125
- params: unknown;
2126
- id: string;
2127
- }
2128
- interface ToolInvokeParams {
2129
- callId: string;
2130
- toolName: string;
2131
- input: unknown;
2132
- /** Server-derived execution metadata for the directed invocation context. */
2133
- jobId?: string;
2134
- sessionId?: string;
2135
- environmentId?: string;
2136
- sandboxId?: string;
2415
+ declare function orderTransientFeedItems(items: readonly TransientFeedItem[]): TransientFeedItem[];
2416
+ type FeedListTransport = (options: FeedListOptions) => Promise<FeedPage | Record<string, unknown>>;
2417
+ type FeedSnapshotRegressionReason = "canonical_deactivation" | "invalid_canonical_document" | "older_document_epoch" | "document_revision_regression" | "last_sequence_regression" | "last_sequence_without_revision" | "feed_revision_regression" | "identity_conflict";
2418
+ type FeedDiagnostic = {
2419
+ type: "gap_detected";
2420
+ expectedSequence: number;
2421
+ targetSequence: number;
2422
+ repairAvailable: boolean;
2423
+ } | {
2424
+ type: "gap_repair";
2425
+ outcome: "success" | "failure" | "cancelled";
2426
+ durationMs: number;
2427
+ pageCount: number;
2428
+ repairedThroughSequence: number;
2429
+ targetSequence: number;
2430
+ } | {
2431
+ type: "snapshot_regression_rejected";
2432
+ reason: FeedSnapshotRegressionReason;
2433
+ currentDocumentEpoch: number;
2434
+ incomingDocumentEpoch: number;
2435
+ currentDocumentRevision: number;
2436
+ incomingDocumentRevision: number;
2437
+ currentFeedRevision: number;
2438
+ incomingFeedRevision: number;
2439
+ currentLastSequence: number;
2440
+ incomingLastSequence: number;
2441
+ } | {
2442
+ type: "unknown_kind";
2443
+ kind: string;
2444
+ sequence: number;
2445
+ consumer?: "sdk" | "dock";
2446
+ };
2447
+ type FeedDiagnosticListener = (diagnostic: FeedDiagnostic) => void;
2448
+ declare const GRANULAR_FEED_DIAGNOSTIC_EVENT: "granular:feed-diagnostic";
2449
+ type FeedDiagnosticEventTarget = {
2450
+ dispatchEvent?: (event: unknown) => unknown;
2451
+ CustomEvent?: new (type: string, init: {
2452
+ detail: Readonly<FeedDiagnostic>;
2453
+ }) => unknown;
2454
+ };
2455
+ declare function normalizeFeedDiagnosticKind(kind: string): string;
2456
+ declare function normalizeFeedDiagnostic(diagnostic: FeedDiagnostic): FeedDiagnostic;
2457
+ /**
2458
+ * Dependency-free production sink for browser SDK and Dock diagnostics.
2459
+ *
2460
+ * Hosts can listen for `granular:feed-diagnostic` and forward the bounded
2461
+ * metadata to their telemetry provider. Server/customer payloads, operation
2462
+ * IDs, and resource IDs are not part of the diagnostic union.
2463
+ */
2464
+ declare function emitFeedDiagnosticToDefaultSink(diagnostic: FeedDiagnostic, target?: FeedDiagnosticEventTarget): void;
2465
+ declare function emitFeedDiagnostic(diagnostic: FeedDiagnostic, listener?: FeedDiagnosticListener | null): void;
2466
+ interface SessionFeedControllerOptions {
2467
+ listTransport?: FeedListTransport | null;
2468
+ isHydrated?: boolean;
2137
2469
  /**
2138
- * Opaque, invocation-scoped grant. Only directed calls receive one; clients
2139
- * must echo it to publish feedback or complete the invocation.
2470
+ * Receives chronology metadata only. Durable payloads, operation IDs, and
2471
+ * resource IDs are deliberately not included.
2140
2472
  */
2141
- feedbackCapability?: string;
2473
+ onDiagnostic?: FeedDiagnosticListener | null;
2474
+ /** Test-only clock seam for deterministic repair duration assertions. */
2475
+ now?: () => number;
2476
+ /** Test seam for deterministic quiet-feed repair retries. */
2477
+ scheduleRepairRetry?: (callback: () => void, delayMs: number) => unknown;
2478
+ /** Test seam paired with `scheduleRepairRetry`. */
2479
+ cancelRepairRetry?: (handle: unknown) => void;
2480
+ /** Initial archive repair retry delay. Defaults to 500ms. */
2481
+ initialRepairRetryDelayMs?: number;
2482
+ /** Maximum archive repair retry delay. Defaults to 10s. */
2483
+ maxRepairRetryDelayMs?: number;
2142
2484
  }
2143
- interface ToolResultParams {
2144
- callId: string;
2145
- /** Echo of a directed invocation's short-lived feedback grant. */
2146
- feedbackCapability?: string;
2147
- result?: unknown;
2148
- error?: string | {
2149
- code: string;
2150
- message: string;
2485
+ interface FeedDocumentState {
2486
+ schemaVersion: 1;
2487
+ activation: {
2488
+ mode: "canonical";
2489
+ activatedAt: number;
2151
2490
  };
2491
+ revision: number;
2492
+ lastSequence: number;
2493
+ archivedThroughSequence: number;
2494
+ tail: FeedItem[];
2495
+ transientById: Record<string, TransientFeedItem>;
2496
+ lastTransientOrdinal: number;
2152
2497
  }
2153
-
2154
- type EndpointMode = "auto" | "local" | "production";
2155
- interface GranularOptions {
2156
- /** Your Granular API key (for service/CLI auth; use with GRANULAR_API_KEY) */
2157
- apiKey?: string;
2158
- /** Application/session JWT (for user-context auth; use from simulator or getAccessToken) */
2159
- token?: string;
2160
- /** Optional provider used to refresh JWT before authenticated requests and WebSocket (re)connect attempts */
2161
- tokenProvider?: AccessTokenProvider;
2162
- /** Optional key per logical GraphQL request. Preserve the key when explicitly replaying a request; no automatic retry is added. */
2163
- graphqlIdempotencyKey?: (query: string, variables?: Record<string, unknown>) => string;
2164
- /** Optional API URL (for on-prem or testing) */
2165
- apiUrl?: string;
2166
- /** Optional live effect-host WebSocket/base URL override (for local/on-prem routing) */
2167
- effectHostUrl?: string;
2168
- /** Optional endpoint mode when apiUrl is not explicitly provided */
2169
- endpointMode?: EndpointMode;
2170
- /** Optional WebSocket constructor (for Node.js environments) */
2171
- WebSocketCtor?: any;
2172
- /**
2173
- * Optional callback invoked when a connected WebSocket closes unexpectedly.
2174
- * Useful for forwarding close diagnostics to monitoring (e.g., Sentry).
2175
- */
2176
- onUnexpectedClose?: (info: WSDisconnectInfo) => void;
2177
- /**
2178
- * Optional callback invoked when automatic reconnect fails.
2179
- * Useful to capture auth or gateway rejection causes.
2180
- */
2181
- onReconnectError?: (info: WSReconnectErrorInfo) => void;
2182
- }
2183
- /** Resolved auth credential: either apiKey or token must be provided */
2184
- type GranularAuth = string;
2185
-
2186
- /**
2187
- * A user/subject object returned from recordUser()
2188
- */
2189
- interface User {
2190
- /** Internal Granular user identifier */
2191
- granularId: string;
2192
- /** External user identifier from your app */
2193
- userId: string;
2194
- /** @deprecated Use `granularId` instead */
2195
- subjectId: string;
2196
- /** @deprecated Use `userId` instead */
2197
- identityId: string;
2198
- /** User's display name */
2199
- name?: string;
2200
- /** User's email */
2201
- email?: string;
2202
- /**
2203
- * Exact permission profile names or IDs requested when opening an
2204
- * environment. Unknown references fail closed; only the explicit
2205
- * `allow-all` compatibility profile may be provisioned automatically.
2206
- */
2207
- permissions: string[];
2208
- }
2498
+ declare function emptyFeedSnapshot(isHydrated?: boolean): FeedSnapshot;
2209
2499
  /**
2210
- * Options for recording a user
2500
+ * Canonical mode is selected solely by the irreversible activation marker.
2501
+ *
2502
+ * This is intentionally separate from document-shape validation. An activated
2503
+ * but temporarily partial/corrupt document must fail closed in canonical mode;
2504
+ * treating it as non-canonical would mix two mutually exclusive projections.
2211
2505
  */
2212
- interface RecordUserOptions {
2213
- /** External user/identity ID (e.g. your Auth0 or database user ID) */
2214
- userId: string;
2215
- /** User's display name */
2216
- name?: string;
2217
- /** User's email */
2218
- email?: string;
2219
- /**
2220
- * Exact permission profile names or IDs to carry into environment opening.
2221
- * Custom profiles must already be provisioned with `granular build` or
2222
- * `granular deploy`.
2223
- */
2224
- permissions?: string[];
2225
- }
2506
+ declare function hasCanonicalSessionFeedActivation(document: unknown): boolean;
2226
2507
  /**
2227
- * Subject as returned from the API
2508
+ * Capability predicate retained for SDK consumers. It answers whether the
2509
+ * session is canonical, not whether the current canonical payload is valid.
2228
2510
  */
2229
- interface Subject {
2230
- /** Internal Granular user identifier */
2231
- granularId: string;
2232
- /** External user identifier from your app */
2233
- userId: string;
2234
- subjectId: string;
2235
- tenantId: string;
2236
- identityId: string;
2237
- email?: string | null;
2238
- name?: string | null;
2239
- metadata?: Record<string, unknown>;
2240
- createdAt: number;
2241
- updatedAt: number;
2242
- }
2511
+ declare function isCanonicalSessionFeedDocument(document: unknown): boolean;
2512
+ declare function readSessionFeedSnapshot(document: unknown, options?: {
2513
+ isHydrated?: boolean;
2514
+ isRepairing?: boolean;
2515
+ error?: Error | null;
2516
+ }): FeedSnapshot;
2517
+ declare function normalizeFeedPage(value: unknown): FeedPage;
2518
+ type FeedSubscriber = (change: FeedSubscriptionChange) => void;
2243
2519
  /**
2244
- * Options for opening an ontology environment for one delegated subject.
2520
+ * Stateful bridge between replicated Automerge snapshots and the public feed.
2245
2521
  *
2246
- * This does not open a live runtime session. Use
2247
- * `environment.sessions.create()` or `granular.createSession({ environmentId })`
2248
- * when you need a conversation/session with jobs, prompts, heap, and effects.
2522
+ * It owns sequence deduplication, stale snapshot rejection and history repair.
2523
+ * UI consumers never merge raw websocket events with this stream.
2249
2524
  */
2250
- interface OpenEnvironmentOptions {
2251
- /** The ontology name or ID to open. */
2252
- ontology: string;
2253
- /** Version channel to follow, typically `dev` or `prod`. */
2254
- tag?: string;
2255
- /**
2256
- * External user identifier from your app.
2257
- *
2258
- * Exactly one of `userId`, `granularId`, or `user` should be provided.
2259
- */
2260
- userId?: string;
2525
+ declare class SessionFeedController implements SessionFeedApi {
2526
+ private snapshot;
2527
+ private canonical;
2528
+ private canonicalStructureValid;
2529
+ private deliveredThrough;
2530
+ private knownBySequence;
2531
+ private sequenceById;
2532
+ private subscribers;
2533
+ private listTransport;
2534
+ private repairGeneration;
2535
+ private repairPromise;
2536
+ private repairRetryHandle;
2537
+ private repairRetryToken;
2538
+ private repairFailureAttempt;
2539
+ private scheduleRepairRetryCallback;
2540
+ private cancelRepairRetryCallback;
2541
+ private initialRepairRetryDelayMs;
2542
+ private maxRepairRetryDelayMs;
2543
+ private disposed;
2544
+ private diagnosticListener;
2545
+ private diagnosticNow;
2546
+ private observedUnknownPositions;
2547
+ constructor(initialDocument: unknown, options?: SessionFeedControllerOptions);
2548
+ setListTransport(transport: FeedListTransport | null): void;
2549
+ getSnapshot(): FeedSnapshot;
2261
2550
  /**
2262
- * Internal Granular user identifier.
2263
- *
2264
- * Exactly one of `userId`, `granularId`, or `user` should be provided.
2551
+ * Stop background archive work when its owning Session is replaced or
2552
+ * explicitly disconnected. Late transport completions are quarantined by
2553
+ * the generation check and cannot update subscribers.
2265
2554
  */
2266
- granularId?: string;
2267
- /** Optional display name used when upserting the user. */
2268
- name?: string;
2269
- /** Optional email used when upserting the user. */
2270
- email?: string;
2555
+ dispose(): void;
2556
+ list(options?: FeedListOptions): Promise<FeedPage>;
2557
+ subscribe(listener: FeedSubscriber, options?: FeedSubscribeOptions): () => void;
2271
2558
  /**
2272
- * Exact permission profile names or IDs to resolve before opening the
2273
- * environment. Unknown references are rejected before assignment writes.
2274
- * The reserved `allow-all` name is the only profile the SDK may provision
2275
- * automatically for backwards compatibility; custom, `confirm-all`, and
2276
- * `deny-all` profiles must already be synced.
2277
- * Required at runtime when `assignmentMode` is omitted or set to `ensure`.
2278
- * Ignored by `require-existing`, which never mutates authorization records.
2559
+ * Accept the latest synced document. Calls may arrive out of order after a
2560
+ * reconnect; freshness watermarks prevent an older snapshot from regressing
2561
+ * durable positions or transient state.
2279
2562
  */
2280
- permissions?: string[];
2563
+ updateDocument(document: unknown, options?: {
2564
+ forceReset?: boolean;
2565
+ }): void;
2281
2566
  /**
2282
- * How the SDK should handle the subject's ontology assignment.
2567
+ * Quarantine a canonical replacement rejected by the document transport.
2568
+ * The notice deliberately contains no replacement document, so accepted
2569
+ * feed history remains the only data visible to subscribers during repair.
2283
2570
  *
2284
- * `ensure` preserves the historical behavior: permission profiles and the
2285
- * assignment are created or updated as needed. `require-existing` accepts
2286
- * only `granularId`, requires a current assignment, and never issues SDK
2287
- * authorization-setup writes for the selected subject, permission profile,
2288
- * or assignment. Managed opening can still write default tags,
2289
- * environments, activations, importer/setup state, sessions, and internal
2290
- * shared-mount subjects.
2291
- */
2292
- assignmentMode?: "ensure" | "require-existing";
2293
- /**
2294
- * Optional integrity guard for `require-existing`. Opening fails when the
2295
- * assignment read by the SDK does not use this permission profile ID. The
2296
- * control plane rechecks the same expectation while resolving an existing
2297
- * active environment and atomically when changing the active pointer.
2298
- */
2299
- expectedPermissionProfileId?: string;
2300
- /**
2301
- * When true, if the latest environment for this ontology/user/tag is marked
2302
- * outdated relative to the current tag target, create a fresh environment on
2303
- * the newest tag target instead of reusing the outdated one.
2304
- */
2305
- createFreshIfOutdated?: boolean;
2306
- /**
2307
- * Create a fresh environment on the current tag target. Reusing this key is
2308
- * safe: it returns the environment created by the original operation.
2571
+ * @internal
2309
2572
  */
2310
- resetKey?: string;
2311
- /** Canonical active-environment slot. Defaults to `default`. */
2312
- slot?: string;
2313
- /** Backwards-compatible user object returned from `recordUser()`. */
2314
- user?: User;
2573
+ quarantineCanonicalReplacement(quarantine: {
2574
+ documentEpoch: number;
2575
+ documentRevision: number;
2576
+ error: Error;
2577
+ }): void;
2578
+ private acceptReset;
2579
+ private emitDiagnostic;
2580
+ private rejectSnapshotRegression;
2581
+ private observeUnknownKinds;
2582
+ private selectNewerTransients;
2583
+ private remember;
2584
+ private findIdentityConflict;
2585
+ private drainContiguous;
2586
+ private startRepair;
2587
+ private cancelScheduledRepairRetry;
2588
+ private scheduleQuietRepairRetry;
2589
+ private repair;
2590
+ private emit;
2315
2591
  }
2316
- /**
2317
- * One-time administrative migration of a known existing environment into
2318
- * Granular's active-environment map. The environment id must be obtained from
2319
- * a reviewed baseline; this API intentionally has no name-based lookup.
2320
- */
2321
- interface AdoptEnvironmentOptions {
2322
- sandboxId: string;
2323
- tag: string;
2324
- userId: string;
2325
- environmentId: string;
2326
- slot?: string;
2592
+ interface PublishFeedbackOptions {
2593
+ icon?: FeedIconToken;
2594
+ tone?: FeedFeedbackTone;
2595
+ code?: string;
2596
+ operationId?: string;
2327
2597
  }
2328
- /**
2329
- * Deprecated compatibility alias for the legacy `connect()` entry point.
2330
- *
2331
- * `connect()` now resolves an environment handle and no longer opens a runtime
2332
- * session automatically. Prefer `openEnvironment()` for new code.
2333
- */
2334
- interface ConnectOptions extends OpenEnvironmentOptions {
2335
- /** @deprecated Legacy explicit environment slot name. Prefer `tag`. */
2336
- environment?: string;
2337
- /** @deprecated Legacy tag field. Prefer `tag`. */
2338
- tagName?: string;
2339
- /** @deprecated Ignored by `connect()` now that it no longer opens sessions. */
2340
- clientId?: string;
2341
- /**
2342
- * @deprecated Ignored by `connect()` now that it no longer opens sessions.
2343
- * Uses application record identity: class name plus the record id from the
2344
- * customer's own system. Granular resolves the internal graph path.
2345
- */
2346
- initialHeap?: Array<{
2347
- className: string;
2348
- id: string;
2349
- }>;
2598
+ interface PublishTransientFeedbackOptions {
2599
+ icon?: FeedIconToken;
2600
+ tone?: FeedTransientFeedbackTone;
2601
+ expiresAt?: number;
2602
+ operationId?: string;
2350
2603
  }
2351
- /**
2352
- * Options for creating a live runtime session from an opened environment.
2353
- */
2354
- interface CreateSessionOptions {
2355
- /** Optional stable client ID. Defaults to `client_${Date.now()}`. */
2356
- clientId?: string;
2357
- /**
2358
- * Optional application-owned history scope for this conversation.
2359
- *
2360
- * Use the same value when listing sessions or reading the materialized user
2361
- * environment state so unrelated product surfaces never share history.
2362
- */
2363
- sessionScope?: string;
2364
- /**
2365
- * Optional session heap seed. Each item uses application record identity:
2366
- * class name plus the record id from the customer's own system. Granular
2367
- * resolves and hydrates the corresponding internal graph record on connect.
2368
- */
2369
- initialHeap?: Array<{
2370
- className: string;
2371
- id: string;
2372
- }>;
2604
+ interface SettleTransientFeedbackOptions {
2605
+ icon?: FeedIconToken;
2606
+ tone?: FeedFeedbackTone;
2607
+ code?: string;
2608
+ operationId?: string;
2609
+ /** Set false to remove the live row without creating durable history. */
2610
+ durable?: boolean;
2611
+ }
2612
+ interface TransientFeedbackHandle {
2613
+ readonly id: string;
2614
+ readonly ordinal: number;
2615
+ readonly revision: number;
2616
+ update(text: string, options?: Omit<PublishTransientFeedbackOptions, "operationId"> & {
2617
+ operationId?: string;
2618
+ }): Promise<TransientFeedbackHandle>;
2619
+ settle(text?: string, options?: SettleTransientFeedbackOptions): Promise<FeedbackFeedItem | null>;
2373
2620
  }
2621
+ interface FeedPublisher {
2622
+ feedback(text: string, options?: PublishFeedbackOptions): Promise<FeedbackFeedItem>;
2623
+ transientFeedback(text: string, options?: PublishTransientFeedbackOptions): Promise<TransientFeedbackHandle>;
2624
+ }
2625
+ type FeedPublishTransport = (method: string, params: Record<string, unknown>) => Promise<unknown>;
2374
2626
  /**
2375
- * Control-plane session row: one real-time conversation thread with the agent for an environment.
2627
+ * Build customer-visible feedback helpers for a trusted, invocation-scoped
2628
+ * transport. This is infrastructure for effect/grounding execution hosts; it
2629
+ * is intentionally not attached to browser Session instances.
2376
2630
  */
2377
- interface ConversationSessionInfo {
2378
- sessionId: string;
2379
- tenantId?: string;
2380
- environmentId: string;
2381
- versionId?: string | null;
2382
- docId: string;
2383
- status: "active" | "closed" | "expired" | "failed" | "timeout";
2384
- createdAt: string;
2385
- lastSeenAt: string;
2386
- summary?: string | null;
2387
- summaryUpdatedAt?: string | null;
2388
- subjectId?: string | null;
2389
- sessionScope?: string | null;
2390
- jobCount?: number;
2391
- toolCallCount?: number;
2392
- }
2393
- type ConversationSessionListStatus = ConversationSessionInfo["status"] | "all";
2631
+ declare function createFeedPublisher(publish: FeedPublishTransport): FeedPublisher;
2632
+
2394
2633
  /**
2395
- * Bounded filters for indexed conversation history.
2396
- *
2397
- * At least one ownership filter (`environmentId`, `sandboxId`, or
2398
- * `subjectId`) is required by the SDK. Results are newest-first and default to
2399
- * 100 rows; use the opaque `cursor` returned by the page response to request
2400
- * the next page.
2634
+ * Property specification in a manifest operation
2401
2635
  */
2402
- interface ConversationSessionListOptions {
2403
- environmentId?: string;
2404
- sandboxId?: string;
2405
- subjectId?: string;
2406
- sessionScope?: string | null;
2407
- status?: ConversationSessionListStatus;
2408
- limit?: number;
2409
- cursor?: string;
2410
- }
2411
- interface ConversationSessionListResponse {
2412
- items: ConversationSessionInfo[];
2413
- nextCursor: string | null;
2636
+ interface ManifestPropertySpec {
2637
+ label?: string;
2638
+ value?: string | number | boolean;
2639
+ ref?: string;
2640
+ instanceOf?: string;
2641
+ create?: string;
2642
+ has?: Record<string, ManifestPropertySpec>;
2643
+ type?: string;
2644
+ /** Temporal representation for date fields: civil date or instant. */
2645
+ format?: "date" | "date-time";
2646
+ description?: string;
2647
+ required?: boolean;
2648
+ note?: string | string[];
2649
+ enum?: string[] | ManifestEnumRuleSpec;
2650
+ filterBy?: boolean | string[] | ManifestFilterBySpec;
2651
+ validate?: ManifestValidationRuleSpec[];
2414
2652
  }
2415
-
2416
- type SessionFileSource = "dock" | "sdk" | "agent" | "runtime" | "processor" | "library" | "imported";
2417
- type SessionFileKind = "csv" | "spreadsheet" | "pdf" | "image" | "text" | "document" | "binary";
2418
- type SessionFileStatus = "queued" | "ready" | "processing" | "processed" | "failed" | "deleted";
2419
- interface SessionFileRecord {
2420
- fileId: string;
2421
- sessionId: string;
2422
- tenantId: string | null;
2423
- subjectId: string | null;
2424
- sandboxId: string | null;
2425
- environmentId: string | null;
2426
- filename: string;
2427
- safeFilename: string;
2428
- contentType: string;
2429
- byteLength: number;
2430
- sha256: string;
2431
- r2Key: string;
2432
- kind: SessionFileKind;
2433
- source: SessionFileSource;
2434
- status: SessionFileStatus;
2435
- createdAt: number;
2436
- updatedAt: number;
2437
- jobId?: string;
2438
- parentFileIds?: string[];
2439
- outputPath?: string;
2440
- metadata?: Record<string, unknown>;
2653
+ type ManifestValidationOperator = "eq" | "neq" | "gt" | "gte" | "lt" | "lte" | "true" | "false" | "regex" | "contains" | "not_contains" | "starts_with" | "ends_with";
2654
+ interface ManifestEnumRuleSpec {
2655
+ values: string[];
2656
+ labels?: string[];
2657
+ message?: string;
2441
2658
  }
2442
- interface SessionFileUploadOptions {
2443
- filename?: string;
2444
- contentType?: string;
2445
- source?: "dock" | "sdk" | "imported";
2446
- parentFileIds?: string[];
2447
- metadata?: Record<string, unknown>;
2659
+ interface ManifestFilterBySpec {
2660
+ operators: string[];
2661
+ scalarType?: string;
2448
2662
  }
2449
-
2450
- type FeedSourceActor = "user" | "agent" | "system" | "customer_method";
2451
- interface FeedSource {
2452
- actor: FeedSourceActor;
2453
- clientId?: string;
2454
- /** Stable authored handle for a transient producer, when available. */
2455
- operationId?: string;
2456
- jobId?: string;
2457
- turnId?: string;
2458
- method?: string;
2663
+ interface ManifestValidationRuleSpec {
2664
+ operator: ManifestValidationOperator;
2665
+ stringValue?: string;
2666
+ numberValue?: number;
2667
+ booleanValue?: boolean;
2668
+ message?: string;
2459
2669
  }
2460
- type FeedIconToken = "neutral" | "info" | "database" | "search" | "clock" | "sparkles" | "check" | "warning" | "error";
2461
- type FeedFeedbackTone = "info" | "working" | "awaiting" | "success" | "warning" | "error";
2462
- /** Tones that describe live state; terminal success belongs in durable history. */
2463
- type FeedTransientFeedbackTone = Exclude<FeedFeedbackTone, "success">;
2464
- type FeedItemKind = "message" | "feedback" | "objects" | "table" | "artifact" | "file" | "action_suggestion" | "prompt";
2465
- interface FeedTarget {
2466
- className: string;
2467
- id: string;
2670
+ interface ManifestStateMachineStateSpec {
2671
+ name: string;
2468
2672
  label?: string;
2673
+ description?: string;
2674
+ isFinal?: boolean;
2469
2675
  }
2470
- interface FeedItemBase {
2471
- id: string;
2472
- sequence: number;
2473
- occurredAt: number;
2474
- kind: FeedItemKind;
2475
- operationId: string;
2476
- batchIndex: number;
2477
- source?: FeedSource;
2478
- }
2479
- interface MessageFeedItem extends FeedItemBase {
2480
- kind: "message";
2481
- payload: {
2482
- role: "user" | "assistant" | "system";
2483
- text: string;
2484
- format?: "plain_text" | "markdown";
2485
- target?: FeedTarget;
2486
- inReplyToPromptId?: string;
2487
- answer?: string | number | boolean | null;
2488
- answerDisplay?: string;
2489
- };
2490
- }
2491
- interface FeedbackFeedItem extends FeedItemBase {
2492
- kind: "feedback";
2493
- payload: {
2494
- text: string;
2495
- icon?: FeedIconToken;
2496
- tone: FeedFeedbackTone;
2497
- audience: "customer";
2498
- action?: {
2499
- actionId: string;
2500
- kind: "frontend" | "backend" | "system";
2501
- label: string;
2502
- status: "queued" | "done" | "failed";
2503
- };
2504
- code?: string;
2505
- };
2506
- }
2507
- type FeedObjectReference = {
2508
- type: "entry";
2676
+ type ManifestStateTransitionInputBinding = null | string | number | boolean | ManifestStateTransitionInputBinding[] | {
2677
+ [key: string]: ManifestStateTransitionInputBinding;
2678
+ } | {
2679
+ const: unknown;
2680
+ } | {
2681
+ from: "object";
2509
2682
  path: string;
2683
+ editable?: boolean;
2510
2684
  } | {
2511
- type: "list";
2685
+ from: "field";
2512
2686
  name: string;
2687
+ editable?: boolean;
2513
2688
  } | {
2514
- type: "variable";
2689
+ from: "relationship";
2515
2690
  name: string;
2691
+ path?: string;
2692
+ many?: boolean;
2693
+ editable?: boolean;
2694
+ } | {
2695
+ from: "session";
2696
+ path: string;
2697
+ editable?: boolean;
2698
+ } | {
2699
+ from: "actor";
2700
+ path: string;
2701
+ editable?: boolean;
2516
2702
  };
2517
- interface ObjectsFeedItem extends FeedItemBase {
2518
- kind: "objects";
2519
- payload: {
2520
- label?: string;
2521
- refs: FeedObjectReference[];
2522
- fallback?: Array<{
2523
- className?: string;
2524
- id: string;
2525
- label?: string;
2526
- }>;
2527
- };
2528
- }
2529
- type FeedTableCell = string | number | boolean | null | {
2530
- kind: "relative_time" | "date";
2531
- value: string | number;
2532
- };
2533
- interface FeedTableColumn {
2534
- id: string;
2535
- label: string;
2703
+ interface ManifestStateTransitionActionSpec {
2704
+ effect: string;
2705
+ /** User-facing name of the connected system that performs the effect. */
2706
+ providerLabel?: string;
2707
+ input?: Record<string, ManifestStateTransitionInputBinding>;
2536
2708
  }
2537
- interface FeedTableRowReference {
2538
- entryPath?: string;
2709
+ interface ManifestStateTransitionAssigneeSpec {
2710
+ kind: string;
2711
+ from?: ManifestStateTransitionInputBinding;
2712
+ role?: string;
2713
+ label?: string;
2714
+ }
2715
+ interface ManifestStateTransitionRelatedStateRequirementSpec {
2716
+ relationship: string;
2717
+ machine: string;
2718
+ state: string;
2539
2719
  className?: string;
2540
- id?: string;
2541
2720
  label?: string;
2721
+ mode?: "every" | "some" | "any";
2542
2722
  }
2543
- interface FeedTableRow {
2544
- id: string;
2545
- reference?: FeedTableRowReference;
2546
- cells: FeedTableCell[];
2723
+ interface ManifestStateTransitionRequirementsSpec {
2724
+ fields?: string[];
2725
+ relationships?: string[];
2726
+ relatedStates?: ManifestStateTransitionRelatedStateRequirementSpec[];
2547
2727
  }
2548
- interface FeedTableProjection {
2549
- id: string;
2728
+ interface ManifestStateTransitionPermissionSpec {
2729
+ profile?: string;
2730
+ profileId?: string;
2550
2731
  label?: string;
2551
- source?: string;
2552
- columns: FeedTableColumn[];
2553
- rows: FeedTableRow[];
2554
- }
2555
- interface TableFeedItem extends FeedItemBase {
2556
- kind: "table";
2557
- payload: {
2558
- tableId: string;
2559
- label?: string;
2560
- columns: FeedTableColumn[];
2561
- rows: FeedTableRow[];
2562
- truncated?: boolean;
2563
- };
2732
+ reason?: string;
2564
2733
  }
2565
- interface ArtifactFeedItem extends FeedItemBase {
2566
- kind: "artifact";
2567
- payload: {
2568
- artifactId: string;
2569
- fallback: {
2570
- kind: "effect" | "batch" | "state_path";
2571
- label: string;
2572
- status?: string;
2573
- description?: string;
2574
- target?: FeedTarget;
2575
- };
2576
- };
2734
+ interface ManifestStateTransitionExpectedOutcomeSpec {
2735
+ machine?: string;
2736
+ state: string;
2737
+ summary?: string;
2577
2738
  }
2578
- type FeedFileSource = "dock" | "sdk" | "agent" | "runtime" | "processor" | "library" | "imported";
2579
- interface FileFeedItem extends FeedItemBase {
2580
- kind: "file";
2581
- payload: {
2582
- fileId: string;
2583
- fallback: {
2584
- filename: string;
2585
- contentType?: string;
2586
- byteLength?: number;
2587
- status?: string;
2588
- source?: FeedFileSource;
2589
- };
2590
- };
2739
+ interface ManifestStateTransitionOutcomeSpec {
2740
+ label?: string;
2741
+ to: string | "$current";
2742
+ primary?: boolean;
2743
+ disposition: "continue" | "error";
2591
2744
  }
2592
- /**
2593
- * The bounded subset needed to create an artifact from a suggestion.
2594
- *
2595
- * This is deliberately data-only. It must never contain executable UI or
2596
- * callback values.
2597
- */
2598
- interface NormalizedSuggestedArtifact {
2599
- version?: 1;
2600
- kind: "effect" | "batch" | "state_path";
2601
- label: string;
2745
+ interface ManifestStateMachineTransitionSpec {
2746
+ name: string;
2747
+ from: string;
2748
+ to: string;
2749
+ label?: string;
2602
2750
  description?: string;
2603
- status?: string;
2604
- target?: FeedTarget;
2605
- inputSchema?: Record<string, unknown>;
2606
- inputValues?: Record<string, unknown>;
2607
- relationships?: Record<string, string | string[] | null>;
2608
- policy?: Record<string, unknown>;
2609
- statePlan?: Record<string, unknown>;
2610
- metadata?: Record<string, unknown>;
2751
+ userVisible?: boolean;
2752
+ action?: ManifestStateTransitionActionSpec;
2753
+ assignee?: ManifestStateTransitionAssigneeSpec;
2754
+ requirements?: ManifestStateTransitionRequirementsSpec;
2755
+ permission?: ManifestStateTransitionPermissionSpec | string;
2756
+ risk?: "low" | "medium" | "high";
2757
+ expectedOutcome?: ManifestStateTransitionExpectedOutcomeSpec | string;
2758
+ outcomes?: Record<string, ManifestStateTransitionOutcomeSpec>;
2611
2759
  }
2612
- interface ActionSuggestionFeedItem extends FeedItemBase {
2613
- kind: "action_suggestion";
2614
- payload: {
2615
- suggestionId: string;
2616
- label: string;
2617
- description?: string;
2618
- target?: FeedTarget;
2619
- proposedArtifact?: NormalizedSuggestedArtifact;
2620
- };
2760
+ interface ManifestStateMachineSpec {
2761
+ name: string;
2762
+ stateField?: string;
2763
+ entryState: string;
2764
+ states: Array<string | ManifestStateMachineStateSpec>;
2765
+ transitions: ManifestStateMachineTransitionSpec[];
2766
+ finalStates?: string[];
2621
2767
  }
2622
- interface PromptFeedItem extends FeedItemBase {
2623
- kind: "prompt";
2624
- payload: {
2625
- promptId: string;
2626
- type: "choice" | "confirm" | "input";
2627
- title: string;
2628
- message: string;
2629
- options?: Array<{
2630
- value: string;
2631
- label: string;
2632
- }>;
2633
- placeholder?: string;
2634
- defaultValue?: string | boolean | null;
2635
- allowEmpty?: boolean;
2636
- openedAt: number;
2637
- };
2768
+ interface ManifestPostConditionSpec {
2769
+ condition: string;
2770
+ description?: string;
2638
2771
  }
2639
- type FeedItem = MessageFeedItem | FeedbackFeedItem | ObjectsFeedItem | TableFeedItem | ArtifactFeedItem | FileFeedItem | ActionSuggestionFeedItem | PromptFeedItem;
2640
- interface TransientFeedItemBase {
2641
- id: string;
2642
- ordinal: number;
2643
- revision: number;
2644
- createdAt: number;
2645
- updatedAt: number;
2646
- expiresAt?: number;
2647
- source?: Omit<FeedSource, "actor" | "clientId"> & {
2648
- actor: Exclude<FeedSourceActor, "user">;
2649
- promptId?: string;
2650
- };
2772
+ interface ManifestDryRunSpec {
2773
+ enabled?: boolean;
2774
+ description?: string;
2651
2775
  }
2652
- interface TransientMessageFeedItem extends TransientFeedItemBase {
2653
- kind: "message";
2654
- producerRevision: number;
2655
- payload: {
2656
- role: "assistant";
2657
- text: string;
2658
- format?: "plain_text" | "markdown";
2659
- };
2776
+ interface ManifestReverseSpec {
2777
+ handler?: string;
2778
+ description?: string;
2660
2779
  }
2661
- interface TransientFeedbackFeedItem extends TransientFeedItemBase {
2662
- kind: "feedback";
2663
- payload: {
2664
- text: string;
2665
- icon?: FeedIconToken;
2666
- tone: FeedTransientFeedbackTone;
2667
- audience: "customer";
2780
+ interface ManifestApprovalRequiredSpec {
2781
+ required?: boolean;
2782
+ reason?: string;
2783
+ mode?: string;
2784
+ }
2785
+ type ManifestCreatesSpec = string | {
2786
+ className: string;
2787
+ idPath?: string;
2788
+ pathPath?: string;
2789
+ statePath?: string;
2790
+ completionState?: string;
2791
+ classStateHandle?: boolean;
2792
+ };
2793
+ interface ManifestEffectMetamodelSpec {
2794
+ reconcileWith?: string;
2795
+ fenceWith?: string;
2796
+ versionPrecondition?: {
2797
+ expected: string;
2668
2798
  };
2799
+ concurrency?: MutationConcurrency;
2800
+ postCondition?: string | ManifestPostConditionSpec;
2801
+ dryRun?: boolean | ManifestDryRunSpec;
2802
+ reverse?: string | ManifestReverseSpec;
2803
+ approvalRequired?: boolean | ManifestApprovalRequiredSpec;
2804
+ creates?: ManifestCreatesSpec;
2805
+ /**
2806
+ * Declarative effect category used by orchestration/validation.
2807
+ *
2808
+ * `read` means the effect observes or explains current state without
2809
+ * changing product state. `write` means it can mutate product state or call an
2810
+ * external side-effect. `ui` is reserved for frontend-only UI effects.
2811
+ */
2812
+ access?: "read" | "write" | "ui";
2813
+ effectKind?: "read" | "write" | "ui";
2814
+ sideEffect?: "read" | "write" | "ui" | "readonly" | "read_only";
2669
2815
  }
2670
- type TransientFeedItem = TransientMessageFeedItem | TransientFeedbackFeedItem;
2671
- interface FeedSnapshot {
2672
- tail: FeedItem[];
2673
- transients: TransientFeedItem[];
2674
- revision: number;
2675
- documentEpoch: number;
2676
- documentRevision: number;
2677
- lastSequence: number;
2678
- archivedThroughSequence: number;
2679
- hasOlder: boolean;
2680
- isHydrated: boolean;
2681
- isRepairing: boolean;
2682
- error: Error | null;
2816
+ /**
2817
+ * Relationship definition between two classes
2818
+ */
2819
+ interface ManifestRelationshipDef {
2820
+ /** Optional name (auto-generated from left_right if omitted) */
2821
+ name?: string;
2822
+ /** Left model path */
2823
+ left: string;
2824
+ /** Right model path */
2825
+ right: string;
2826
+ /** Submodel name on the left model */
2827
+ leftSubmodel: string;
2828
+ /** Submodel name on the right model */
2829
+ rightSubmodel: string;
2830
+ /** Whether the left side is a collection */
2831
+ leftIsMany: boolean;
2832
+ /** Whether the right side is a collection */
2833
+ rightIsMany: boolean;
2683
2834
  }
2684
- interface FeedListOptions {
2685
- afterSequence?: number;
2686
- beforeSequence?: number;
2687
- limit?: number;
2835
+ interface ManifestEffectSchema {
2836
+ type: string;
2837
+ properties?: Record<string, unknown>;
2838
+ required?: string[];
2839
+ items?: unknown;
2840
+ description?: string;
2841
+ [key: string]: unknown;
2688
2842
  }
2689
- interface FeedPage {
2690
- items: FeedItem[];
2691
- firstSequence: number | null;
2692
- lastSequence: number | null;
2693
- hasMoreBefore: boolean;
2694
- hasMoreAfter: boolean;
2843
+ interface ManifestEffectDeclaration {
2844
+ name: string;
2845
+ label?: string;
2846
+ description?: string;
2847
+ attachedClass?: string;
2848
+ isStatic?: boolean;
2849
+ inputSchema: ManifestEffectSchema;
2850
+ outputSchema?: ManifestEffectSchema;
2851
+ stability?: "stable" | "experimental" | "deprecated";
2852
+ tags?: string[];
2853
+ metamodels?: ManifestEffectMetamodelSpec;
2854
+ commit?: {
2855
+ kind: "effect" | "transition";
2856
+ };
2695
2857
  }
2696
- interface FeedSubscribeOptions {
2697
- afterSequence?: number;
2858
+ /**
2859
+ * An event type within an event stream definition
2860
+ */
2861
+ interface ManifestEventTypeDef {
2862
+ name: string;
2863
+ description?: string;
2864
+ payloadSchema: ManifestEffectSchema;
2698
2865
  }
2699
- type FeedSubscriptionChange = {
2700
- type: "append";
2701
- items: FeedItem[];
2702
- } | {
2703
- type: "transients";
2704
- items: TransientFeedItem[];
2705
- revision: number;
2706
- } | {
2707
- type: "resource_refresh";
2708
- documentRevision: number;
2709
- resourceIds?: string[];
2710
- } | {
2711
- type: "reset";
2712
- snapshot: FeedSnapshot;
2713
- };
2714
- interface SessionFeedApi {
2715
- getSnapshot(): FeedSnapshot;
2716
- list(options?: FeedListOptions): Promise<FeedPage>;
2717
- subscribe(listener: (change: FeedSubscriptionChange) => void, options?: FeedSubscribeOptions): () => void;
2866
+ /**
2867
+ * Event stream definition for outgoing typed events
2868
+ */
2869
+ interface ManifestEventStreamDef {
2870
+ name: string;
2871
+ description?: string;
2872
+ eventTypes: ManifestEventTypeDef[];
2718
2873
  }
2719
2874
  /**
2720
- * Merge independently contiguous archive/live collections by authoritative
2721
- * sequence. Expected overlap collapses by occurrence identity; conflicting
2722
- * IDs or positions fail closed.
2875
+ * A single operation in a manifest volume
2723
2876
  */
2724
- declare function mergeFeedItemsBySequence(...collections: ReadonlyArray<readonly FeedItem[]>): FeedItem[];
2877
+ interface ManifestOperation {
2878
+ /** Create a new model/class */
2879
+ create?: string;
2880
+ /** Authored user-facing name stored on the graph model. */
2881
+ label?: string;
2882
+ /** Target an existing model for modification */
2883
+ on?: string;
2884
+ /** Extend from a parent class */
2885
+ extends?: string;
2886
+ /** Instantiate a type */
2887
+ instanceOf?: string;
2888
+ /** Define submodels/fields */
2889
+ has?: Record<string, ManifestPropertySpec>;
2890
+ /** Advisory notes attached to the model/class itself */
2891
+ note?: string | string[];
2892
+ /** State machines attached to the created or targeted class */
2893
+ stateMachines?: ManifestStateMachineSpec[];
2894
+ /** Define a relationship between two classes */
2895
+ defineRelationship?: ManifestRelationshipDef;
2896
+ /** Declare a build-owned effect */
2897
+ withEffect?: ManifestEffectDeclaration;
2898
+ /** Define an outgoing event stream with typed events */
2899
+ defineEventStream?: ManifestEventStreamDef;
2900
+ }
2725
2901
  /**
2726
- * Select the newest revision of each transient and preserve server ordinal
2727
- * order. Duplicate ordinal ownership is a chronology violation.
2902
+ * A volume in a manifest
2728
2903
  */
2729
- declare function orderTransientFeedItems(items: readonly TransientFeedItem[]): TransientFeedItem[];
2730
- type FeedListTransport = (options: FeedListOptions) => Promise<FeedPage | Record<string, unknown>>;
2731
- type FeedSnapshotRegressionReason = "canonical_deactivation" | "invalid_canonical_document" | "older_document_epoch" | "document_revision_regression" | "last_sequence_regression" | "last_sequence_without_revision" | "feed_revision_regression" | "identity_conflict";
2732
- type FeedDiagnostic = {
2733
- type: "gap_detected";
2734
- expectedSequence: number;
2735
- targetSequence: number;
2736
- repairAvailable: boolean;
2737
- } | {
2738
- type: "gap_repair";
2739
- outcome: "success" | "failure" | "cancelled";
2740
- durationMs: number;
2741
- pageCount: number;
2742
- repairedThroughSequence: number;
2743
- targetSequence: number;
2744
- } | {
2745
- type: "snapshot_regression_rejected";
2746
- reason: FeedSnapshotRegressionReason;
2747
- currentDocumentEpoch: number;
2748
- incomingDocumentEpoch: number;
2749
- currentDocumentRevision: number;
2750
- incomingDocumentRevision: number;
2751
- currentFeedRevision: number;
2752
- incomingFeedRevision: number;
2753
- currentLastSequence: number;
2754
- incomingLastSequence: number;
2755
- } | {
2756
- type: "unknown_kind";
2757
- kind: string;
2758
- sequence: number;
2759
- consumer?: "sdk" | "dock";
2760
- };
2761
- type FeedDiagnosticListener = (diagnostic: FeedDiagnostic) => void;
2762
- declare const GRANULAR_FEED_DIAGNOSTIC_EVENT: "granular:feed-diagnostic";
2763
- type FeedDiagnosticEventTarget = {
2764
- dispatchEvent?: (event: unknown) => unknown;
2765
- CustomEvent?: new (type: string, init: {
2766
- detail: Readonly<FeedDiagnostic>;
2767
- }) => unknown;
2768
- };
2769
- declare function normalizeFeedDiagnosticKind(kind: string): string;
2770
- declare function normalizeFeedDiagnostic(diagnostic: FeedDiagnostic): FeedDiagnostic;
2771
2904
  /**
2772
- * Dependency-free production sink for browser SDK and Dock diagnostics.
2773
- *
2774
- * Hosts can listen for `granular:feed-diagnostic` and forward the bounded
2775
- * metadata to their telemetry provider. Server/customer payloads, operation
2776
- * IDs, and resource IDs are not part of the diagnostic union.
2905
+ * Import descriptor for referencing modules
2777
2906
  */
2778
- declare function emitFeedDiagnosticToDefaultSink(diagnostic: FeedDiagnostic, target?: FeedDiagnosticEventTarget): void;
2779
- declare function emitFeedDiagnostic(diagnostic: FeedDiagnostic, listener?: FeedDiagnosticListener | null): void;
2780
- interface SessionFeedControllerOptions {
2781
- listTransport?: FeedListTransport | null;
2782
- isHydrated?: boolean;
2783
- /**
2784
- * Receives chronology metadata only. Durable payloads, operation IDs, and
2785
- * resource IDs are deliberately not included.
2786
- */
2787
- onDiagnostic?: FeedDiagnosticListener | null;
2788
- /** Test-only clock seam for deterministic repair duration assertions. */
2789
- now?: () => number;
2790
- /** Test seam for deterministic quiet-feed repair retries. */
2791
- scheduleRepairRetry?: (callback: () => void, delayMs: number) => unknown;
2792
- /** Test seam paired with `scheduleRepairRetry`. */
2793
- cancelRepairRetry?: (handle: unknown) => void;
2794
- /** Initial archive repair retry delay. Defaults to 500ms. */
2795
- initialRepairRetryDelayMs?: number;
2796
- /** Maximum archive repair retry delay. Defaults to 10s. */
2797
- maxRepairRetryDelayMs?: number;
2907
+ interface ManifestImport {
2908
+ /** Alias prefix used in operations (e.g., "@std") */
2909
+ alias: string;
2910
+ /** Module name (e.g., "standard_modules") */
2911
+ name: string;
2912
+ /** Version label (e.g., "prod", "v1.2.3") */
2913
+ label?: string;
2798
2914
  }
2799
- interface FeedDocumentState {
2800
- schemaVersion: 1;
2801
- activation: {
2802
- mode: "canonical";
2803
- activatedAt: number;
2804
- };
2805
- revision: number;
2806
- lastSequence: number;
2807
- archivedThroughSequence: number;
2808
- tail: FeedItem[];
2809
- transientById: Record<string, TransientFeedItem>;
2810
- lastTransientOrdinal: number;
2915
+ interface ManifestVolume {
2916
+ name: string;
2917
+ scope: "sandbox" | "build" | "user";
2918
+ imports?: ManifestImport[];
2919
+ operations: ManifestOperation[];
2811
2920
  }
2812
- declare function emptyFeedSnapshot(isHydrated?: boolean): FeedSnapshot;
2813
- /**
2814
- * Canonical mode is selected solely by the irreversible activation marker.
2815
- *
2816
- * This is intentionally separate from document-shape validation. An activated
2817
- * but temporarily partial/corrupt document must fail closed in canonical mode;
2818
- * treating it as non-canonical would mix two mutually exclusive projections.
2819
- */
2820
- declare function hasCanonicalSessionFeedActivation(document: unknown): boolean;
2821
2921
  /**
2822
- * Capability predicate retained for SDK consumers. It answers whether the
2823
- * session is canonical, not whether the current canonical payload is valid.
2922
+ * A manifest defines the structure of a sandbox's data model
2824
2923
  */
2825
- declare function isCanonicalSessionFeedDocument(document: unknown): boolean;
2826
- declare function readSessionFeedSnapshot(document: unknown, options?: {
2827
- isHydrated?: boolean;
2828
- isRepairing?: boolean;
2829
- error?: Error | null;
2830
- }): FeedSnapshot;
2831
- declare function normalizeFeedPage(value: unknown): FeedPage;
2832
- type FeedSubscriber = (change: FeedSubscriptionChange) => void;
2924
+ interface ManifestContent {
2925
+ schemaVersion: 2;
2926
+ name: string;
2927
+ description?: string;
2928
+ volumes: ManifestVolume[];
2929
+ }
2930
+
2833
2931
  /**
2834
- * Stateful bridge between replicated Automerge snapshots and the public feed.
2835
- *
2836
- * It owns sequence deduplication, stale snapshot rejection and history repair.
2837
- * UI consumers never merge raw websocket events with this stream.
2932
+ * Effect handler for static/global effects: receives (input, context)
2838
2933
  */
2839
- declare class SessionFeedController implements SessionFeedApi {
2840
- private snapshot;
2841
- private canonical;
2842
- private canonicalStructureValid;
2843
- private deliveredThrough;
2844
- private knownBySequence;
2845
- private sequenceById;
2846
- private subscribers;
2847
- private listTransport;
2848
- private repairGeneration;
2849
- private repairPromise;
2850
- private repairRetryHandle;
2851
- private repairRetryToken;
2852
- private repairFailureAttempt;
2853
- private scheduleRepairRetryCallback;
2854
- private cancelRepairRetryCallback;
2855
- private initialRepairRetryDelayMs;
2856
- private maxRepairRetryDelayMs;
2857
- private disposed;
2858
- private diagnosticListener;
2859
- private diagnosticNow;
2860
- private observedUnknownPositions;
2861
- constructor(initialDocument: unknown, options?: SessionFeedControllerOptions);
2862
- setListTransport(transport: FeedListTransport | null): void;
2863
- getSnapshot(): FeedSnapshot;
2864
- /**
2865
- * Stop background archive work when its owning Session is replaced or
2866
- * explicitly disconnected. Late transport completions are quarantined by
2867
- * the generation check and cannot update subscribers.
2868
- */
2869
- dispose(): void;
2870
- list(options?: FeedListOptions): Promise<FeedPage>;
2871
- subscribe(listener: FeedSubscriber, options?: FeedSubscribeOptions): () => void;
2934
+ interface EffectHandlerContext {
2935
+ attemptId?: string;
2936
+ /** Authoritative invocation contract; the provider enforces conditional writes. */
2937
+ execution?: {
2938
+ access: "read" | "write";
2939
+ operationKey?: string;
2940
+ reconcileWith?: string;
2941
+ fenceWith?: string;
2942
+ concurrency?: MutationConcurrency;
2943
+ versionPrecondition?: {
2944
+ expected: string;
2945
+ };
2946
+ recoveryControl?: "fence";
2947
+ };
2948
+ effectClientId: string;
2949
+ sandboxId: string;
2950
+ environmentId: string;
2951
+ /** Stable effect call id assigned by the authoritative session. */
2952
+ invocationId?: string;
2872
2953
  /**
2873
- * Accept the latest synced document. Calls may arrive out of order after a
2874
- * reconnect; freshness watermarks prevent an older snapshot from regressing
2875
- * durable positions or transient state.
2954
+ * Stable, runtime-computed key for the authoritative product mutation.
2955
+ * Customer adapters should persist this key with the product result and
2956
+ * return that same result when an invocation is retried.
2876
2957
  */
2877
- updateDocument(document: unknown, options?: {
2878
- forceReset?: boolean;
2879
- }): void;
2958
+ idempotencyKey?: string;
2959
+ /** Owning execution/job when the effect is invoked from one. */
2960
+ jobId?: string;
2961
+ buildId?: string;
2962
+ buildVersionNumber?: number;
2963
+ sessionId: string;
2964
+ tenantId?: string;
2965
+ principalId?: string;
2966
+ permissionProfileId?: string;
2967
+ user: {
2968
+ granularId?: string;
2969
+ userId?: string;
2970
+ subjectId: string;
2971
+ identityId?: string;
2972
+ principalId?: string;
2973
+ };
2974
+ behaviors?: ResolvedEffectBehaviors;
2975
+ invocation?: EffectInvocationMetadata;
2880
2976
  /**
2881
- * Quarantine a canonical replacement rejected by the document transport.
2882
- * The notice deliberately contains no replacement document, so accepted
2883
- * feed history remains the only data visible to subscribers during repair.
2884
- *
2885
- * @internal
2977
+ * Publish durable customer-visible feedback for the directed invocation
2978
+ * owned by this effect host or `tool.invoke` callback.
2886
2979
  */
2887
- quarantineCanonicalReplacement(quarantine: {
2888
- documentEpoch: number;
2889
- documentRevision: number;
2890
- error: Error;
2891
- }): void;
2892
- private acceptReset;
2893
- private emitDiagnostic;
2894
- private rejectSnapshotRegression;
2895
- private observeUnknownKinds;
2896
- private selectNewerTransients;
2897
- private remember;
2898
- private findIdentityConflict;
2899
- private drainContiguous;
2900
- private startRepair;
2901
- private cancelScheduledRepairRetry;
2902
- private scheduleQuietRepairRetry;
2903
- private repair;
2904
- private emit;
2905
- }
2906
- interface PublishFeedbackOptions {
2907
- icon?: FeedIconToken;
2908
- tone?: FeedFeedbackTone;
2909
- code?: string;
2910
- operationId?: string;
2911
- }
2912
- interface PublishTransientFeedbackOptions {
2913
- icon?: FeedIconToken;
2914
- tone?: FeedTransientFeedbackTone;
2915
- expiresAt?: number;
2916
- operationId?: string;
2980
+ feedback?: FeedPublisher["feedback"];
2981
+ /**
2982
+ * Create invocation-owned live feedback that can be updated and settled.
2983
+ * Present under the same invocation-scoped conditions as `feedback`.
2984
+ */
2985
+ transientFeedback?: FeedPublisher["transientFeedback"];
2986
+ /**
2987
+ * Acknowledge the product mutation declared by the active effect. There is
2988
+ * intentionally no generic callable `commit(...)` form.
2989
+ */
2990
+ commit: EffectCommitContext;
2917
2991
  }
2918
- interface SettleTransientFeedbackOptions {
2919
- icon?: FeedIconToken;
2920
- tone?: FeedFeedbackTone;
2921
- code?: string;
2922
- operationId?: string;
2923
- /** Set false to remove the live row without creating durable history. */
2924
- durable?: boolean;
2992
+ interface ResolvedEffectPostCondition {
2993
+ condition: string;
2994
+ description?: string;
2925
2995
  }
2926
- interface TransientFeedbackHandle {
2927
- readonly id: string;
2928
- readonly ordinal: number;
2929
- readonly revision: number;
2930
- update(text: string, options?: Omit<PublishTransientFeedbackOptions, "operationId"> & {
2931
- operationId?: string;
2932
- }): Promise<TransientFeedbackHandle>;
2933
- settle(text?: string, options?: SettleTransientFeedbackOptions): Promise<FeedbackFeedItem | null>;
2996
+ interface ResolvedEffectDryRun {
2997
+ enabled: boolean;
2998
+ description?: string;
2934
2999
  }
2935
- interface FeedPublisher {
2936
- feedback(text: string, options?: PublishFeedbackOptions): Promise<FeedbackFeedItem>;
2937
- transientFeedback(text: string, options?: PublishTransientFeedbackOptions): Promise<TransientFeedbackHandle>;
3000
+ interface ResolvedEffectReverse {
3001
+ handler?: string;
3002
+ description?: string;
2938
3003
  }
2939
- type FeedPublishTransport = (method: string, params: Record<string, unknown>) => Promise<unknown>;
2940
- /**
2941
- * Build customer-visible feedback helpers for a trusted, invocation-scoped
2942
- * transport. This is infrastructure for effect/grounding execution hosts; it
2943
- * is intentionally not attached to browser Session instances.
2944
- */
2945
- declare function createFeedPublisher(publish: FeedPublishTransport): FeedPublisher;
2946
-
2947
- type JobStatus = "queued" | "running" | "awaitingTool" | "awaitingHuman" | "succeeded" | "failed" | "timeout" | "canceled";
2948
- type JobFeedbackSentiment = "good" | "bad";
2949
- interface JobFeedbackToolCall {
2950
- callId?: string;
2951
- toolName?: string;
2952
- input?: unknown;
2953
- output?: unknown;
2954
- error?: string;
2955
- startedAt?: number;
2956
- completedAt?: number;
2957
- durationMs?: number | null;
3004
+ interface ResolvedEffectApprovalRequired {
3005
+ required: boolean;
3006
+ reason?: string;
3007
+ mode?: string;
2958
3008
  }
2959
- interface JobFeedbackMetadata {
2960
- source: "sdk";
2961
- status: JobStatus;
2962
- code: string;
2963
- domainRevision?: string;
2964
- createdAt: number;
2965
- startedAt?: number;
2966
- completedAt?: number;
2967
- durationMs?: number | null;
2968
- result?: unknown;
2969
- error?: string;
2970
- stdout: string[];
2971
- stderr: string[];
2972
- toolCalls: JobFeedbackToolCall[];
3009
+ interface ResolvedEffectBehaviors {
3010
+ postCondition?: ResolvedEffectPostCondition;
3011
+ dryRun?: ResolvedEffectDryRun;
3012
+ reverse?: ResolvedEffectReverse;
3013
+ approvalRequired?: ResolvedEffectApprovalRequired;
2973
3014
  }
2974
- interface JobFeedbackInput {
2975
- sentiment: JobFeedbackSentiment;
2976
- comment?: string | null;
3015
+ type EffectInvocationMode = "execute" | "dryRun" | "reverse" | "artifactOptions";
3016
+ interface EffectArtifactOptionsInvocation {
3017
+ fieldName: string;
3018
+ query?: string;
3019
+ limit?: number;
2977
3020
  }
2978
- interface JobFeedbackRecord {
2979
- feedbackId: string;
2980
- tenantId?: string;
2981
- sessionId: string;
2982
- environmentId: string;
2983
- sandboxId?: string;
2984
- buildId?: string;
2985
- subjectId?: string;
2986
- jobId: string;
2987
- sentiment: JobFeedbackSentiment;
2988
- comment?: string | null;
2989
- metadata: JobFeedbackMetadata & Record<string, unknown>;
2990
- createdAt: number;
2991
- updatedAt: number;
3021
+ interface EffectInvocationMetadata {
3022
+ mode?: EffectInvocationMode;
3023
+ /** Trusted runtime metadata; committed effects are dispatched to backend hosts only. */
3024
+ commitKind?: "effect" | "transition";
3025
+ /**
3026
+ * Present when an effect is being run as part of a durable action artifact.
3027
+ * It lets an application distinguish the artifact's authoritative record
3028
+ * mirror from an ordinary session effect invocation.
3029
+ */
3030
+ artifactId?: string;
3031
+ reverseHandler?: string;
3032
+ sourceEffectKey?: string;
3033
+ sourceEffectName?: string;
3034
+ /**
3035
+ * Present only when the artifact runtime asks an effect for authoritative
3036
+ * relationship choices. This is deliberately kept out of the effect input
3037
+ * so application handlers receive the exact same action payload they will
3038
+ * eventually execute.
3039
+ */
3040
+ artifactOptions?: EffectArtifactOptionsInvocation;
3041
+ /** Resolved, server-authored transition selected for this invocation. */
3042
+ transition?: CommitTransitionInvocation;
2992
3043
  }
3044
+ type ToolHandler = (input: any, context: EffectHandlerContext) => Promise<unknown>;
2993
3045
  /**
2994
- * Persisted feedback row listed at the environment level.
3046
+ * Effect handler for instance methods: receives (objectId, input, context)
2995
3047
  */
2996
- interface EnvironmentFeedbackRecord {
2997
- feedbackId: string;
2998
- sessionId: string;
2999
- jobId: string;
3000
- sentiment: JobFeedbackSentiment;
3001
- comment?: string | null;
3002
- metadata?: Record<string, unknown> | null;
3003
- createdAt: string | null;
3048
+ type InstanceToolHandler = (id: string, input: any, context: EffectHandlerContext) => Promise<unknown>;
3049
+ interface EffectArtifactRelationshipOption {
3050
+ id: string;
3051
+ label: string;
3052
+ /** Canonical graph path used when the ontology has no authored label. */
3053
+ path?: string | null;
3054
+ description?: string;
3055
+ fields?: Record<string, string | number | boolean | null>;
3004
3056
  }
3005
- /**
3006
- * Result from submitting a job
3007
- */
3008
- interface JobSubmitResult {
3009
- jobId: string;
3057
+ interface EffectArtifactRelationshipOptionsResult {
3058
+ items: EffectArtifactRelationshipOption[];
3059
+ /** True when the returned page contains the complete eligible option set. */
3060
+ complete?: boolean;
3061
+ /** True when more eligible options exist beyond this response. */
3062
+ hasMore?: boolean;
3063
+ /** Number of eligible options for the current query when known. */
3064
+ totalCount?: number;
3065
+ /** Typed empty/loading outcome that the Artifact UI can explain locally. */
3066
+ status?: "ok" | "domain_empty" | "no_match" | "workspace_syncing" | "verification_failed" | "provider_unavailable";
3067
+ /**
3068
+ * Actionable explanation shown when no eligible record is available.
3069
+ * It must be customer-facing and must not expose internal policy machinery.
3070
+ */
3071
+ emptyMessage?: string;
3010
3072
  }
3073
+ type ArtifactOptionsHandler = (input: any, context: EffectHandlerContext) => Promise<EffectArtifactRelationshipOptionsResult>;
3011
3074
  /**
3012
- * Represents a job executed in the sandbox
3075
+ * Effect schema for declaring or registering an effect.
3076
+ *
3077
+ * Effects come in three flavours:
3078
+ *
3079
+ * 1. **Instance methods** — set `className`, omit `static`.
3080
+ * In the sandbox: `tolkien.get_bio({ detailed: true })`
3081
+ * Handler signature: `(objectId: string, params: any) => any`
3082
+ *
3083
+ * 2. **Static methods** — set `className` + `static: true`.
3084
+ * In the sandbox: `Author.search({ query: 'tolkien' })`
3085
+ * Handler signature: `(params: any) => any`
3086
+ *
3087
+ * 3. **Global effects** — omit `className`.
3088
+ * In the sandbox: `global_search({ query: 'rings' })`
3089
+ * Handler signature: `(params: any) => any`
3090
+ *
3091
+ * Both `inputSchema` and `outputSchema` accept JSON Schema objects.
3092
+ * The `outputSchema` drives the return type in the auto-generated
3093
+ * TypeScript declarations that sandbox code imports from Harness v3 runtime modules.
3013
3094
  */
3014
- interface Job {
3015
- /** Unique Job ID */
3016
- id: string;
3017
- /** Current status of the job */
3018
- status: JobStatus;
3019
- /** Promise that resolves with the job result */
3020
- result: Promise<unknown>;
3021
- /** Attach user feedback to this job and persist it with job/session metadata */
3022
- leaveFeedback(input: JobFeedbackInput): Promise<JobFeedbackRecord>;
3023
- /** Subscribe to job events */
3024
- on(event: string, handler: (data: unknown) => void): () => void;
3025
- }
3026
- interface Prompt {
3027
- id: string;
3028
- /** Job that owns this prompt, when it was opened by a running job. */
3029
- jobId?: string;
3030
- /** Harness turn that owns this prompt. */
3031
- turnId?: string;
3032
- type: "confirm" | "choice" | "input";
3033
- title: string;
3034
- message: string;
3035
- options?: Array<string | {
3036
- value: string;
3037
- label: string;
3038
- description?: string;
3039
- }>;
3040
- defaultValue?: unknown;
3041
- placeholder?: string;
3042
- allowEmpty?: boolean;
3043
- metadata?: Record<string, unknown>;
3044
- }
3045
- interface UserMessageShowRefs {
3046
- entryPaths?: string[];
3047
- listNames?: string[];
3048
- variableNames?: string[];
3049
- fileIds?: string[];
3050
- }
3051
- interface UserMessageTarget {
3052
- className: string;
3053
- id: string;
3095
+ interface ToolSchema {
3096
+ effectKey?: string;
3097
+ name: string;
3098
+ /** Authored user-facing operation name. Falls back to the canonical name. */
3054
3099
  label?: string;
3055
- }
3056
- interface UserMessageInput {
3100
+ description: string;
3101
+ /** JSON Schema for the effect input parameters */
3102
+ inputSchema: Record<string, unknown>;
3057
3103
  /**
3058
- * Caller-owned logical user-message ID used to correlate optimistic and durable
3059
- * turns. Reuse this id when retrying a call after an ambiguous timeout.
3104
+ * JSON Schema for the tool's return value.
3105
+ * Used to generate typed return types in the sandbox TypeScript declarations.
3060
3106
  *
3061
- * When omitted together with `operationId`, the SDK reserves an identity for
3062
- * that single invocation. A later caller-level retry must supply the
3063
- * previously chosen id or operationId; identical content is never deduped.
3107
+ * @example
3108
+ * ```typescript
3109
+ * outputSchema: {
3110
+ * type: 'object',
3111
+ * properties: {
3112
+ * bio: { type: 'string', description: 'The biography text' },
3113
+ * source: { type: 'string', description: 'Source of the bio' },
3114
+ * },
3115
+ * required: ['bio'],
3116
+ * }
3117
+ * // Generates: Promise<{ bio: string; source?: string }>
3118
+ * ```
3064
3119
  */
3065
- id?: string;
3120
+ outputSchema?: Record<string, unknown>;
3121
+ stability?: "stable" | "experimental" | "deprecated";
3122
+ provenance?: {
3123
+ source: "mcp" | "custom";
3124
+ };
3125
+ tags?: string[];
3066
3126
  /**
3067
- * Caller-owned idempotency key for the logical append operation. If omitted,
3068
- * the SDK derives it from `id`, or from the id it reserves for this call.
3127
+ * The class this effect belongs to (e.g., `'author'`, `'book'`).
3128
+ * When set, the effect becomes a method on the auto-generated class.
3129
+ * Omit for global effects (standalone exported functions).
3069
3130
  */
3070
- operationId?: string;
3071
- content: string;
3072
- show?: UserMessageShowRefs;
3073
- target?: UserMessageTarget;
3074
- }
3075
- interface UserMessageAppendResult {
3076
- ok: boolean;
3077
- messageId: string;
3078
- timestamp: number;
3079
- }
3080
- interface AssistantReplyPublicationInput {
3081
- /** Stable caller-owned identity for this exact assistant occurrence. */
3082
- id: string;
3083
- /** Stable idempotency key reused after an ambiguous response. */
3084
- operationId: string;
3085
- /** Exact assistant text to append to the canonical feed. */
3086
- text: string;
3087
- }
3088
- interface AssistantReplyPublicationResult {
3089
- ok: true;
3090
- /** Caller-owned logical identity supplied as `id`. */
3091
- messageId: string;
3092
- /** Canonical durable feed occurrence identity used by presentation clients. */
3093
- feedItemId: string;
3094
- timestamp: number;
3131
+ className?: string;
3132
+ /**
3133
+ * If `true`, this is a static/class-level method (no object ID required).
3134
+ * If `false` or omitted and `className` is set, this is an instance method
3135
+ * that operates on a specific object (the object's real-world ID is
3136
+ * passed as the first argument to the handler).
3137
+ */
3138
+ static?: boolean;
3139
+ /**
3140
+ * Optional build-version selector for this live effect binding.
3141
+ *
3142
+ * When omitted, the binding applies to all build versions for the sandbox.
3143
+ */
3144
+ versionSelector?: EffectVersionSelector;
3145
+ /** Declarative runtime behaviors attached to the effect. */
3146
+ metamodels?: ManifestEffectMetamodelSpec;
3147
+ /** Wire-safe product acknowledgement kind. */
3148
+ commit?: {
3149
+ kind: "effect" | "transition";
3150
+ };
3095
3151
  }
3096
- interface SessionTranscriptActionSuggestion {
3097
- suggestionId?: string;
3098
- label: string;
3099
- description?: string | null;
3100
- artifact?: Record<string, unknown>;
3101
- target?: Record<string, unknown> | null;
3102
- metadata?: Record<string, unknown>;
3152
+ type EffectSchema = ToolSchema;
3153
+ /**
3154
+ * Effect with handler — what users provide to `registerEffect()`.
3155
+ *
3156
+ * - **Instance methods** (`className` set, `static` omitted):
3157
+ * handler receives `(objectId: string, params: any)`
3158
+ * - **Static methods** (`className` set, `static: true`):
3159
+ * handler receives `(params: any)`
3160
+ * - **Global tools** (no `className`):
3161
+ * handler receives `(params: any)`
3162
+ */
3163
+ interface ToolWithHandler extends ToolSchema {
3164
+ /** Handler-local mapper is never serialized into the live effect catalog. */
3165
+ commit?: CommitDeclaration<any>;
3166
+ handler: ToolHandler | InstanceToolHandler;
3167
+ dryRunHandler?: ToolHandler | InstanceToolHandler;
3168
+ reverseHandler?: ToolHandler | InstanceToolHandler;
3169
+ /**
3170
+ * Optional server-authoritative option resolver for prepared artifact
3171
+ * relationship and enum fields. It is invoked on the original effect and is
3172
+ * not published as a separate agent-visible tool.
3173
+ */
3174
+ artifactOptionsHandler?: ArtifactOptionsHandler;
3103
3175
  }
3104
- interface SessionTranscriptShowRefs extends UserMessageShowRefs {
3105
- sessionArtifactIds?: string[];
3106
- actionSuggestions?: SessionTranscriptActionSuggestion[];
3107
- tables?: FeedTableProjection[];
3176
+ type EffectWithHandler = ToolWithHandler;
3177
+ /**
3178
+ * Result from publishing or synchronizing effects
3179
+ */
3180
+ interface PublishToolsResult {
3181
+ accepted: boolean;
3182
+ domainRevision: string;
3183
+ rejected?: Array<{
3184
+ name: string;
3185
+ reason: string;
3186
+ }>;
3108
3187
  }
3109
- interface SessionTimelineEvent {
3110
- id?: string;
3111
- eventId?: string;
3112
- kind?: string;
3113
- type?: string;
3114
- status?: string | null;
3115
- message?: string;
3116
- summary?: string;
3117
- title?: string;
3118
- ts?: number;
3119
- timestamp?: number;
3120
- at?: number;
3121
- createdAt?: number;
3188
+ type PublishEffectsResult = PublishToolsResult;
3189
+ type EffectVersionSelector = {
3190
+ mode: "all";
3191
+ } | {
3192
+ mode: "exact";
3193
+ versionNumber: number;
3194
+ } | {
3195
+ mode: "before";
3196
+ versionNumber: number;
3197
+ } | {
3198
+ mode: "after";
3199
+ versionNumber: number;
3200
+ };
3201
+ /**
3202
+ * Domain state response
3203
+ */
3204
+ interface DomainState {
3205
+ activeDomainRevision?: string;
3206
+ tools?: Array<{
3207
+ name: string;
3208
+ description?: string;
3209
+ inputSchema?: Record<string, unknown>;
3210
+ outputSchema?: Record<string, unknown>;
3211
+ metamodels?: ManifestEffectMetamodelSpec;
3212
+ }>;
3122
3213
  [key: string]: unknown;
3123
3214
  }
3124
-
3125
3215
  /**
3126
- * Property specification in a manifest operation
3216
+ * Information about a live or declared effect
3127
3217
  */
3128
- interface ManifestPropertySpec {
3129
- label?: string;
3130
- value?: string | number | boolean;
3131
- ref?: string;
3132
- instanceOf?: string;
3133
- create?: string;
3134
- has?: Record<string, ManifestPropertySpec>;
3135
- type?: string;
3136
- /** Temporal representation for date fields: civil date or instant. */
3137
- format?: "date" | "date-time";
3218
+ interface ToolInfo {
3219
+ effectKey?: string;
3220
+ /** Unique name of the effect */
3221
+ name: string;
3222
+ /** Description of what the effect does */
3138
3223
  description?: string;
3139
- required?: boolean;
3140
- note?: string | string[];
3141
- enum?: string[] | ManifestEnumRuleSpec;
3142
- filterBy?: boolean | string[] | ManifestFilterBySpec;
3143
- validate?: ManifestValidationRuleSpec[];
3224
+ /** JSON Schema for effect input */
3225
+ inputSchema?: Record<string, unknown>;
3226
+ /** JSON Schema for effect output */
3227
+ outputSchema?: Record<string, unknown>;
3228
+ /** Client ID that published this effect (absent for domain-only entries) */
3229
+ clientId?: string;
3230
+ /** Whether the effect is ready for use (has a registered handler) */
3231
+ ready: boolean;
3232
+ /** Timestamp when the effect was published */
3233
+ publishedAt?: number;
3234
+ /** Class this effect belongs to (instance/static method) */
3235
+ className?: string;
3236
+ /** Whether this is a static method */
3237
+ static?: boolean;
3238
+ /** Optional build-version selector associated with the live binding. */
3239
+ versionSelector?: EffectVersionSelector;
3240
+ /** Declarative runtime behaviors attached to the effect. */
3241
+ metamodels?: ManifestEffectMetamodelSpec;
3144
3242
  }
3145
- type ManifestValidationOperator = "eq" | "neq" | "gt" | "gte" | "lt" | "lte" | "true" | "false" | "regex" | "contains" | "not_contains" | "starts_with" | "ends_with";
3146
- interface ManifestEnumRuleSpec {
3147
- values: string[];
3148
- labels?: string[];
3149
- message?: string;
3243
+ interface EffectInfo extends ToolInfo {
3150
3244
  }
3151
- interface ManifestFilterBySpec {
3152
- operators: string[];
3153
- scalarType?: string;
3245
+ /**
3246
+ * Event data when the list of available effects changes
3247
+ */
3248
+ interface ToolsChangedEvent {
3249
+ /** The current list of all available effects */
3250
+ tools: ToolInfo[];
3251
+ /** Names of effects that were added or updated */
3252
+ added: string[];
3253
+ /** Names of effects that were removed */
3254
+ removed: string[];
3154
3255
  }
3155
- interface ManifestValidationRuleSpec {
3156
- operator: ManifestValidationOperator;
3157
- stringValue?: string;
3158
- numberValue?: number;
3159
- booleanValue?: boolean;
3160
- message?: string;
3256
+ interface EffectsChangedEvent extends ToolsChangedEvent {
3257
+ /** The current list of all available effects */
3258
+ effects: EffectInfo[];
3161
3259
  }
3162
- interface ManifestStateMachineStateSpec {
3260
+ type EffectHandler = ToolHandler;
3261
+ type InstanceEffectHandler = InstanceToolHandler;
3262
+
3263
+ interface StateMachineDefinition {
3163
3264
  name: string;
3164
3265
  label?: string;
3165
- description?: string;
3166
- isFinal?: boolean;
3266
+ states: Record<string, {
3267
+ label?: string;
3268
+ isFinal?: boolean;
3269
+ }>;
3270
+ transitions: Record<string, {
3271
+ label?: string;
3272
+ from: string;
3273
+ effect: ToolWithHandler;
3274
+ outcomes: Record<string, CommitTransitionOutcomeDeclaration>;
3275
+ }>;
3167
3276
  }
3168
- type ManifestStateTransitionInputBinding = null | string | number | boolean | ManifestStateTransitionInputBinding[] | {
3169
- [key: string]: ManifestStateTransitionInputBinding;
3170
- } | {
3171
- const: unknown;
3172
- } | {
3173
- from: "object";
3174
- path: string;
3175
- editable?: boolean;
3176
- } | {
3177
- from: "field";
3178
- name: string;
3179
- editable?: boolean;
3180
- } | {
3181
- from: "relationship";
3182
- name: string;
3183
- path?: string;
3184
- many?: boolean;
3185
- editable?: boolean;
3186
- } | {
3187
- from: "session";
3188
- path: string;
3189
- editable?: boolean;
3190
- } | {
3191
- from: "actor";
3192
- path: string;
3193
- editable?: boolean;
3277
+ type DefinedStateMachine<TDefinition extends StateMachineDefinition = StateMachineDefinition> = TDefinition & {
3278
+ transitions: TDefinition["transitions"];
3194
3279
  };
3195
- interface ManifestStateTransitionActionSpec {
3196
- effect: string;
3197
- /** User-facing name of the connected system that performs the effect. */
3198
- providerLabel?: string;
3199
- input?: Record<string, ManifestStateTransitionInputBinding>;
3200
- }
3201
- interface ManifestStateTransitionAssigneeSpec {
3202
- kind: string;
3203
- from?: ManifestStateTransitionInputBinding;
3204
- role?: string;
3205
- label?: string;
3206
- }
3207
- interface ManifestStateTransitionRelatedStateRequirementSpec {
3208
- relationship: string;
3209
- machine: string;
3210
- state: string;
3211
- className?: string;
3212
- label?: string;
3213
- mode?: "every" | "some" | "any";
3214
- }
3215
- interface ManifestStateTransitionRequirementsSpec {
3216
- fields?: string[];
3217
- relationships?: string[];
3218
- relatedStates?: ManifestStateTransitionRelatedStateRequirementSpec[];
3280
+ interface CommitTransport {
3281
+ persist(request: EffectCommitRequest): Promise<CommitReceipt>;
3282
+ mappingFailed?(input: {
3283
+ effectKey: string;
3284
+ effectName: string;
3285
+ invocationId: string;
3286
+ idempotencyKey: string;
3287
+ environmentId: string;
3288
+ message: string;
3289
+ }): Promise<void>;
3219
3290
  }
3220
- interface ManifestStateTransitionPermissionSpec {
3221
- profile?: string;
3222
- profileId?: string;
3223
- label?: string;
3291
+ declare function defineProjection<TResult, TProjection extends ProjectionResult = ProjectionResult>(mapper: ProjectionMapper<TResult, TProjection>): ProjectionMapper<TResult, TProjection>;
3292
+ declare function defineEffect<TEffect extends ToolWithHandler>(effect: TEffect): TEffect;
3293
+ declare function defineStateMachine<const TDefinition extends StateMachineDefinition>(definition: TDefinition): DefinedStateMachine<TDefinition>;
3294
+ declare function validateProjectionResult(declaration: CommitDeclaration<any>, projection: ProjectionResult): void;
3295
+ /** Stable JSON used by tests, fingerprints, and source-event conflict checks. */
3296
+ declare function canonicalizeCommitValue(value: unknown): string;
3297
+
3298
+ interface WSDisconnectInfo {
3299
+ code?: number;
3224
3300
  reason?: string;
3301
+ wasClean?: boolean;
3302
+ unexpected: boolean;
3303
+ timestamp: number;
3304
+ reconnectScheduled: boolean;
3305
+ reconnectDelayMs?: number;
3225
3306
  }
3226
- interface ManifestStateTransitionExpectedOutcomeSpec {
3227
- machine?: string;
3228
- state: string;
3229
- summary?: string;
3307
+ interface WSReconnectErrorInfo {
3308
+ sessionId: string;
3309
+ error: string;
3310
+ timestamp: number;
3311
+ terminal: boolean;
3230
3312
  }
3231
- interface ManifestStateTransitionOutcomeSpec {
3232
- label?: string;
3233
- to: string | "$current";
3234
- primary?: boolean;
3235
- disposition: "continue" | "error";
3313
+ interface WSClientOptions {
3314
+ url: string;
3315
+ sessionId: string;
3316
+ token: string;
3317
+ initialDocumentSnapshot?: Record<string, unknown> | Uint8Array | null;
3318
+ tokenProvider?: AccessTokenProvider;
3319
+ WebSocketCtor?: any;
3320
+ /** Maximum time for one socket open attempt before reconnect may continue. */
3321
+ connectTimeoutMs?: number;
3322
+ maxReconnectAttempts?: number;
3323
+ reconnectDelayMs?: number;
3324
+ onUnexpectedClose?: (info: WSDisconnectInfo) => void;
3325
+ onReconnectError?: (info: WSReconnectErrorInfo) => void;
3236
3326
  }
3237
- interface ManifestStateMachineTransitionSpec {
3238
- name: string;
3239
- from: string;
3240
- to: string;
3241
- label?: string;
3242
- description?: string;
3243
- userVisible?: boolean;
3244
- action?: ManifestStateTransitionActionSpec;
3245
- assignee?: ManifestStateTransitionAssigneeSpec;
3246
- requirements?: ManifestStateTransitionRequirementsSpec;
3247
- permission?: ManifestStateTransitionPermissionSpec | string;
3248
- risk?: "low" | "medium" | "high";
3249
- expectedOutcome?: ManifestStateTransitionExpectedOutcomeSpec | string;
3250
- outcomes?: Record<string, ManifestStateTransitionOutcomeSpec>;
3327
+ interface RPCRequest {
3328
+ type: "rpc";
3329
+ method: string;
3330
+ params: unknown;
3331
+ id: string;
3251
3332
  }
3252
- interface ManifestStateMachineSpec {
3253
- name: string;
3254
- stateField?: string;
3255
- entryState: string;
3256
- states: Array<string | ManifestStateMachineStateSpec>;
3257
- transitions: ManifestStateMachineTransitionSpec[];
3258
- finalStates?: string[];
3333
+ interface RPCResponse {
3334
+ type: "rpc_result" | "rpc_error";
3335
+ id: string;
3336
+ result?: unknown;
3337
+ error?: {
3338
+ code: number;
3339
+ message: string;
3340
+ data?: unknown;
3341
+ };
3259
3342
  }
3260
- interface ManifestPostConditionSpec {
3261
- condition: string;
3262
- description?: string;
3343
+ interface SnapshotResetMessage {
3344
+ type: "snapshot_reset";
3345
+ documentEpoch: number;
3346
+ documentRevision: number;
3347
+ /** Legacy Automerge binary replacement payload. */
3348
+ data?: number[];
3349
+ /** Server-authoritative JSON replacement payload. */
3350
+ document?: Record<string, unknown>;
3263
3351
  }
3264
- interface ManifestDryRunSpec {
3265
- enabled?: boolean;
3266
- description?: string;
3352
+ /**
3353
+ * High-frequency job presentation update. It deliberately carries only the
3354
+ * bounded trace for one job; it is not a canonical document revision and must
3355
+ * not be treated as a replacement for the session snapshot.
3356
+ */
3357
+ interface JobActionTraceMessage {
3358
+ type: "job_action_trace";
3359
+ jobId: string;
3360
+ documentEpoch: number;
3361
+ documentRevision: number;
3362
+ actionTrace: Array<Record<string, unknown>>;
3363
+ actionSummary: string[];
3364
+ actionSummaryText: string;
3267
3365
  }
3268
- interface ManifestReverseSpec {
3269
- handler?: string;
3270
- description?: string;
3366
+ /**
3367
+ * Bounded live-feed overlay update. It carries no canonical document
3368
+ * revision: a transient is presentation state and must not create a full
3369
+ * snapshot/history entry just because its text changed.
3370
+ */
3371
+ interface FeedTransientPatchMessage {
3372
+ type: "feed_transient_patch";
3373
+ documentEpoch: number;
3374
+ documentRevision: number;
3375
+ feedRevision: number;
3376
+ lastTransientOrdinal: number;
3377
+ changes: Array<{
3378
+ transientId: string;
3379
+ item?: Record<string, unknown>;
3380
+ removed?: boolean;
3381
+ }>;
3271
3382
  }
3272
- interface ManifestApprovalRequiredSpec {
3273
- required?: boolean;
3274
- reason?: string;
3275
- mode?: string;
3383
+ interface RPCRequestFromServer {
3384
+ type: "rpc";
3385
+ method: string;
3386
+ params: unknown;
3387
+ id: string;
3276
3388
  }
3277
- type ManifestCreatesSpec = string | {
3278
- className: string;
3279
- idPath?: string;
3280
- pathPath?: string;
3281
- statePath?: string;
3282
- completionState?: string;
3283
- classStateHandle?: boolean;
3284
- };
3285
- interface ManifestEffectMetamodelSpec {
3286
- postCondition?: string | ManifestPostConditionSpec;
3287
- dryRun?: boolean | ManifestDryRunSpec;
3288
- reverse?: string | ManifestReverseSpec;
3289
- approvalRequired?: boolean | ManifestApprovalRequiredSpec;
3290
- creates?: ManifestCreatesSpec;
3389
+ interface ToolInvokeParams {
3390
+ callId: string;
3391
+ toolName: string;
3392
+ input: unknown;
3393
+ /** Server-derived execution metadata for the directed invocation context. */
3394
+ jobId?: string;
3395
+ sessionId?: string;
3396
+ environmentId?: string;
3397
+ sandboxId?: string;
3291
3398
  /**
3292
- * Declarative effect category used by orchestration/validation.
3293
- *
3294
- * `read` means the effect observes or explains current state without
3295
- * changing product state. `write` means it can mutate product state or call an
3296
- * external side-effect. `ui` is reserved for frontend-only UI effects.
3399
+ * Opaque, invocation-scoped grant. Only directed calls receive one; clients
3400
+ * must echo it to publish feedback or complete the invocation.
3297
3401
  */
3298
- access?: "read" | "write" | "ui";
3299
- effectKind?: "read" | "write" | "ui";
3300
- sideEffect?: "read" | "write" | "ui" | "readonly" | "read_only";
3301
- }
3302
- /**
3303
- * Relationship definition between two classes
3304
- */
3305
- interface ManifestRelationshipDef {
3306
- /** Optional name (auto-generated from left_right if omitted) */
3307
- name?: string;
3308
- /** Left model path */
3309
- left: string;
3310
- /** Right model path */
3311
- right: string;
3312
- /** Submodel name on the left model */
3313
- leftSubmodel: string;
3314
- /** Submodel name on the right model */
3315
- rightSubmodel: string;
3316
- /** Whether the left side is a collection */
3317
- leftIsMany: boolean;
3318
- /** Whether the right side is a collection */
3319
- rightIsMany: boolean;
3402
+ feedbackCapability?: string;
3320
3403
  }
3321
- interface ManifestEffectSchema {
3322
- type: string;
3323
- properties?: Record<string, unknown>;
3324
- required?: string[];
3325
- items?: unknown;
3326
- description?: string;
3327
- [key: string]: unknown;
3328
- }
3329
- interface ManifestEffectDeclaration {
3330
- name: string;
3331
- label?: string;
3332
- description?: string;
3333
- attachedClass?: string;
3334
- isStatic?: boolean;
3335
- inputSchema: ManifestEffectSchema;
3336
- outputSchema?: ManifestEffectSchema;
3337
- stability?: "stable" | "experimental" | "deprecated";
3338
- tags?: string[];
3339
- metamodels?: ManifestEffectMetamodelSpec;
3340
- commit?: {
3341
- kind: "effect" | "transition";
3404
+ interface ToolResultParams {
3405
+ callId: string;
3406
+ /** Echo of a directed invocation's short-lived feedback grant. */
3407
+ feedbackCapability?: string;
3408
+ result?: unknown;
3409
+ error?: string | {
3410
+ code: string;
3411
+ message: string;
3342
3412
  };
3343
3413
  }
3414
+
3415
+ type EndpointMode = "auto" | "local" | "production";
3416
+ interface GranularOptions {
3417
+ /** Your Granular API key (for service/CLI auth; use with GRANULAR_API_KEY) */
3418
+ apiKey?: string;
3419
+ /** Application/session JWT (for user-context auth; use from simulator or getAccessToken) */
3420
+ token?: string;
3421
+ /** Optional provider used to refresh JWT before authenticated requests and WebSocket (re)connect attempts */
3422
+ tokenProvider?: AccessTokenProvider;
3423
+ /** Optional key per logical GraphQL request. Preserve the key when explicitly replaying a request; no automatic retry is added. */
3424
+ graphqlIdempotencyKey?: (query: string, variables?: Record<string, unknown>) => string;
3425
+ /** Optional API URL (for on-prem or testing) */
3426
+ apiUrl?: string;
3427
+ /** Optional live effect-host WebSocket/base URL override (for local/on-prem routing) */
3428
+ effectHostUrl?: string;
3429
+ /** Optional endpoint mode when apiUrl is not explicitly provided */
3430
+ endpointMode?: EndpointMode;
3431
+ /** Optional WebSocket constructor (for Node.js environments) */
3432
+ WebSocketCtor?: any;
3433
+ /**
3434
+ * Optional callback invoked when a connected WebSocket closes unexpectedly.
3435
+ * Useful for forwarding close diagnostics to monitoring (e.g., Sentry).
3436
+ */
3437
+ onUnexpectedClose?: (info: WSDisconnectInfo) => void;
3438
+ /**
3439
+ * Optional callback invoked when automatic reconnect fails.
3440
+ * Useful to capture auth or gateway rejection causes.
3441
+ */
3442
+ onReconnectError?: (info: WSReconnectErrorInfo) => void;
3443
+ }
3444
+ /** Resolved auth credential: either apiKey or token must be provided */
3445
+ type GranularAuth = string;
3446
+
3344
3447
  /**
3345
- * An event type within an event stream definition
3448
+ * A user/subject object returned from recordUser()
3346
3449
  */
3347
- interface ManifestEventTypeDef {
3348
- name: string;
3349
- description?: string;
3350
- payloadSchema: ManifestEffectSchema;
3450
+ interface User {
3451
+ /** Internal Granular user identifier */
3452
+ granularId: string;
3453
+ /** External user identifier from your app */
3454
+ userId: string;
3455
+ /** @deprecated Use `granularId` instead */
3456
+ subjectId: string;
3457
+ /** @deprecated Use `userId` instead */
3458
+ identityId: string;
3459
+ /** User's display name */
3460
+ name?: string;
3461
+ /** User's email */
3462
+ email?: string;
3463
+ /**
3464
+ * Exact permission profile names or IDs requested when opening an
3465
+ * environment. Unknown references fail closed; only the explicit
3466
+ * `allow-all` compatibility profile may be provisioned automatically.
3467
+ */
3468
+ permissions: string[];
3351
3469
  }
3352
3470
  /**
3353
- * Event stream definition for outgoing typed events
3471
+ * Options for recording a user
3354
3472
  */
3355
- interface ManifestEventStreamDef {
3356
- name: string;
3357
- description?: string;
3358
- eventTypes: ManifestEventTypeDef[];
3473
+ interface RecordUserOptions {
3474
+ /** External user/identity ID (e.g. your Auth0 or database user ID) */
3475
+ userId: string;
3476
+ /** User's display name */
3477
+ name?: string;
3478
+ /** User's email */
3479
+ email?: string;
3480
+ /**
3481
+ * Exact permission profile names or IDs to carry into environment opening.
3482
+ * Custom profiles must already be provisioned with `granular build` or
3483
+ * `granular deploy`.
3484
+ */
3485
+ permissions?: string[];
3359
3486
  }
3360
3487
  /**
3361
- * A single operation in a manifest volume
3488
+ * Subject as returned from the API
3362
3489
  */
3363
- interface ManifestOperation {
3364
- /** Create a new model/class */
3365
- create?: string;
3366
- /** Authored user-facing name stored on the graph model. */
3367
- label?: string;
3368
- /** Target an existing model for modification */
3369
- on?: string;
3370
- /** Extend from a parent class */
3371
- extends?: string;
3372
- /** Instantiate a type */
3373
- instanceOf?: string;
3374
- /** Define submodels/fields */
3375
- has?: Record<string, ManifestPropertySpec>;
3376
- /** Advisory notes attached to the model/class itself */
3377
- note?: string | string[];
3378
- /** State machines attached to the created or targeted class */
3379
- stateMachines?: ManifestStateMachineSpec[];
3380
- /** Define a relationship between two classes */
3381
- defineRelationship?: ManifestRelationshipDef;
3382
- /** Declare a build-owned effect */
3383
- withEffect?: ManifestEffectDeclaration;
3384
- /** Define an outgoing event stream with typed events */
3385
- defineEventStream?: ManifestEventStreamDef;
3490
+ interface Subject {
3491
+ /** Internal Granular user identifier */
3492
+ granularId: string;
3493
+ /** External user identifier from your app */
3494
+ userId: string;
3495
+ subjectId: string;
3496
+ tenantId: string;
3497
+ identityId: string;
3498
+ email?: string | null;
3499
+ name?: string | null;
3500
+ metadata?: Record<string, unknown>;
3501
+ createdAt: number;
3502
+ updatedAt: number;
3386
3503
  }
3387
3504
  /**
3388
- * A volume in a manifest
3505
+ * Options for opening an ontology environment for one delegated subject.
3506
+ *
3507
+ * This does not open a live runtime session. Use
3508
+ * `environment.sessions.create()` or `granular.createSession({ environmentId })`
3509
+ * when you need a conversation/session with jobs, prompts, heap, and effects.
3389
3510
  */
3511
+ interface OpenEnvironmentOptions {
3512
+ /** The ontology name or ID to open. */
3513
+ ontology: string;
3514
+ /** Version channel to follow, typically `dev` or `prod`. */
3515
+ tag?: string;
3516
+ /**
3517
+ * External user identifier from your app.
3518
+ *
3519
+ * Exactly one of `userId`, `granularId`, or `user` should be provided.
3520
+ */
3521
+ userId?: string;
3522
+ /**
3523
+ * Internal Granular user identifier.
3524
+ *
3525
+ * Exactly one of `userId`, `granularId`, or `user` should be provided.
3526
+ */
3527
+ granularId?: string;
3528
+ /** Optional display name used when upserting the user. */
3529
+ name?: string;
3530
+ /** Optional email used when upserting the user. */
3531
+ email?: string;
3532
+ /**
3533
+ * Exact permission profile names or IDs to resolve before opening the
3534
+ * environment. Unknown references are rejected before assignment writes.
3535
+ * The reserved `allow-all` name is the only profile the SDK may provision
3536
+ * automatically for backwards compatibility; custom, `confirm-all`, and
3537
+ * `deny-all` profiles must already be synced.
3538
+ * Required at runtime when `assignmentMode` is omitted or set to `ensure`.
3539
+ * Ignored by `require-existing`, which never mutates authorization records.
3540
+ */
3541
+ permissions?: string[];
3542
+ /**
3543
+ * How the SDK should handle the subject's ontology assignment.
3544
+ *
3545
+ * `ensure` preserves the historical behavior: permission profiles and the
3546
+ * assignment are created or updated as needed. `require-existing` accepts
3547
+ * only `granularId`, requires a current assignment, and never issues SDK
3548
+ * authorization-setup writes for the selected subject, permission profile,
3549
+ * or assignment. Managed opening can still write default tags,
3550
+ * environments, activations, importer/setup state, sessions, and internal
3551
+ * shared-mount subjects.
3552
+ */
3553
+ assignmentMode?: "ensure" | "require-existing";
3554
+ /**
3555
+ * Optional integrity guard for `require-existing`. Opening fails when the
3556
+ * assignment read by the SDK does not use this permission profile ID. The
3557
+ * control plane rechecks the same expectation while resolving an existing
3558
+ * active environment and atomically when changing the active pointer.
3559
+ */
3560
+ expectedPermissionProfileId?: string;
3561
+ /**
3562
+ * When true, if the latest environment for this ontology/user/tag is marked
3563
+ * outdated relative to the current tag target, create a fresh environment on
3564
+ * the newest tag target instead of reusing the outdated one.
3565
+ */
3566
+ createFreshIfOutdated?: boolean;
3567
+ /**
3568
+ * Create a fresh environment on the current tag target. Reusing this key is
3569
+ * safe: it returns the environment created by the original operation.
3570
+ */
3571
+ resetKey?: string;
3572
+ /** Canonical active-environment slot. Defaults to `default`. */
3573
+ slot?: string;
3574
+ /** Backwards-compatible user object returned from `recordUser()`. */
3575
+ user?: User;
3576
+ }
3390
3577
  /**
3391
- * Import descriptor for referencing modules
3578
+ * One-time administrative migration of a known existing environment into
3579
+ * Granular's active-environment map. The environment id must be obtained from
3580
+ * a reviewed baseline; this API intentionally has no name-based lookup.
3392
3581
  */
3393
- interface ManifestImport {
3394
- /** Alias prefix used in operations (e.g., "@std") */
3395
- alias: string;
3396
- /** Module name (e.g., "standard_modules") */
3397
- name: string;
3398
- /** Version label (e.g., "prod", "v1.2.3") */
3399
- label?: string;
3400
- }
3401
- interface ManifestVolume {
3402
- name: string;
3403
- scope: "sandbox" | "build" | "user";
3404
- imports?: ManifestImport[];
3405
- operations: ManifestOperation[];
3582
+ interface AdoptEnvironmentOptions {
3583
+ sandboxId: string;
3584
+ tag: string;
3585
+ userId: string;
3586
+ environmentId: string;
3587
+ slot?: string;
3406
3588
  }
3407
3589
  /**
3408
- * A manifest defines the structure of a sandbox's data model
3590
+ * Deprecated compatibility alias for the legacy `connect()` entry point.
3591
+ *
3592
+ * `connect()` now resolves an environment handle and no longer opens a runtime
3593
+ * session automatically. Prefer `openEnvironment()` for new code.
3409
3594
  */
3410
- interface ManifestContent {
3411
- schemaVersion: 2;
3412
- name: string;
3413
- description?: string;
3414
- volumes: ManifestVolume[];
3415
- }
3416
-
3417
- interface SessionJobRecord {
3418
- jobId: string;
3419
- status: string;
3420
- code?: string;
3421
- createdAt?: number;
3422
- startedAt?: number;
3423
- completedAt?: number;
3424
- durationMs?: number | null;
3425
- progressPercent?: number | null;
3426
- progressMessage?: string | null;
3427
- stdout?: string[];
3428
- stderr?: string[];
3429
- result?: unknown;
3430
- error?: string | null;
3431
- toolCalls?: JobFeedbackToolCall[];
3432
- prompts?: Record<string, unknown>;
3433
- actionSummary?: string[];
3434
- actionTrace?: Array<Record<string, unknown>>;
3435
- [key: string]: unknown;
3436
- }
3437
- interface SessionTranscriptEntry {
3438
- id: string;
3439
- role: "user" | "assistant";
3440
- content: string;
3441
- timestamp: number;
3442
- /** Canonical durable feed position. */
3443
- sequence: number;
3444
- jobId?: string;
3445
- promptId?: string;
3446
- show?: SessionTranscriptShowRefs;
3447
- historyContent?: string;
3448
- source: "feed";
3595
+ interface ConnectOptions extends OpenEnvironmentOptions {
3596
+ /** @deprecated Legacy explicit environment slot name. Prefer `tag`. */
3597
+ environment?: string;
3598
+ /** @deprecated Legacy tag field. Prefer `tag`. */
3599
+ tagName?: string;
3600
+ /** @deprecated Ignored by `connect()` now that it no longer opens sessions. */
3601
+ clientId?: string;
3602
+ /**
3603
+ * @deprecated Ignored by `connect()` now that it no longer opens sessions.
3604
+ * Uses application record identity: class name plus the record id from the
3605
+ * customer's own system. Granular resolves the internal graph path.
3606
+ */
3607
+ initialHeap?: Array<{
3608
+ className: string;
3609
+ id: string;
3610
+ }>;
3449
3611
  }
3450
- type SessionHeapFieldType = "string" | "number" | "boolean" | "null" | "unknown";
3451
- interface SessionHeapFieldValue {
3452
- name: string;
3453
- type: SessionHeapFieldType;
3454
- value: string | number | boolean | null;
3612
+ /**
3613
+ * Options for creating a live runtime session from an opened environment.
3614
+ */
3615
+ interface CreateSessionOptions {
3616
+ /** Optional stable client ID. Defaults to `client_${Date.now()}`. */
3617
+ clientId?: string;
3618
+ /**
3619
+ * Optional application-owned history scope for this conversation.
3620
+ *
3621
+ * Use the same value when listing sessions or reading the materialized user
3622
+ * environment state so unrelated product surfaces never share history.
3623
+ */
3624
+ sessionScope?: string;
3625
+ /**
3626
+ * Optional session heap seed. Each item uses application record identity:
3627
+ * class name plus the record id from the customer's own system. Granular
3628
+ * resolves and hydrates the corresponding internal graph record on connect.
3629
+ */
3630
+ initialHeap?: Array<{
3631
+ className: string;
3632
+ id: string;
3633
+ }>;
3455
3634
  }
3456
- interface SessionHeapEntry {
3457
- path: string;
3458
- className: string;
3459
- id: string;
3460
- label?: string | null;
3461
- description?: string | null;
3462
- prototypes: string[];
3463
- fields: SessionHeapFieldValue[];
3464
- relatedJobIds: string[];
3465
- source: string;
3466
- createdAt: number;
3467
- updatedAt: number;
3635
+ /**
3636
+ * Control-plane session row: one real-time conversation thread with the agent for an environment.
3637
+ */
3638
+ interface ConversationSessionInfo {
3639
+ sessionId: string;
3640
+ tenantId?: string;
3641
+ environmentId: string;
3642
+ versionId?: string | null;
3643
+ docId: string;
3644
+ status: "active" | "closed" | "expired" | "failed" | "timeout";
3645
+ createdAt: string;
3646
+ lastSeenAt: string;
3647
+ summary?: string | null;
3648
+ summaryUpdatedAt?: string | null;
3649
+ subjectId?: string | null;
3650
+ sessionScope?: string | null;
3651
+ jobCount?: number;
3652
+ toolCallCount?: number;
3468
3653
  }
3469
- interface SessionHeapList {
3470
- name: string;
3471
- className: string;
3472
- paths: string[];
3473
- relatedJobIds: string[];
3474
- updatedAt: number;
3654
+ type ConversationSessionListStatus = ConversationSessionInfo["status"] | "all";
3655
+ /**
3656
+ * Bounded filters for indexed conversation history.
3657
+ *
3658
+ * At least one ownership filter (`environmentId`, `sandboxId`, or
3659
+ * `subjectId`) is required by the SDK. Results are newest-first and default to
3660
+ * 100 rows; use the opaque `cursor` returned by the page response to request
3661
+ * the next page.
3662
+ */
3663
+ interface ConversationSessionListOptions {
3664
+ environmentId?: string;
3665
+ sandboxId?: string;
3666
+ subjectId?: string;
3667
+ sessionScope?: string | null;
3668
+ status?: ConversationSessionListStatus;
3669
+ limit?: number;
3670
+ cursor?: string;
3475
3671
  }
3476
- interface SessionHeapVariable {
3477
- name: string;
3478
- kind: "entry" | "list" | "scalar";
3479
- entryPath?: string;
3480
- listName?: string;
3481
- value?: string | number | boolean | null;
3482
- className?: string;
3483
- updatedAt: number;
3672
+ interface ConversationSessionListResponse {
3673
+ items: ConversationSessionInfo[];
3674
+ nextCursor: string | null;
3484
3675
  }
3485
- interface SessionHeapSnapshot {
3486
- entriesByPath: Record<string, SessionHeapEntry>;
3487
- listsByName: Record<string, SessionHeapList>;
3488
- variablesByName: Record<string, SessionHeapVariable>;
3489
- updatedAt: number;
3676
+
3677
+ type JobStatus = "queued" | "running" | "awaitingTool" | "awaitingHuman" | "succeeded" | "failed" | "timeout" | "canceled";
3678
+ type JobFeedbackSentiment = "good" | "bad";
3679
+ interface JobFeedbackToolCall {
3680
+ callId?: string;
3681
+ toolName?: string;
3682
+ input?: unknown;
3683
+ output?: unknown;
3684
+ error?: string;
3685
+ startedAt?: number;
3686
+ completedAt?: number;
3687
+ durationMs?: number | null;
3490
3688
  }
3491
- interface RecordSearchResult {
3492
- path: string;
3493
- className: string;
3494
- id: string;
3495
- label: string;
3496
- description?: string | null;
3497
- fields: SessionHeapFieldValue[];
3689
+ interface JobFeedbackMetadata {
3690
+ source: "sdk";
3691
+ status: JobStatus;
3692
+ code: string;
3693
+ domainRevision?: string;
3694
+ createdAt: number;
3695
+ startedAt?: number;
3696
+ completedAt?: number;
3697
+ durationMs?: number | null;
3698
+ result?: unknown;
3699
+ error?: string;
3700
+ stdout: string[];
3701
+ stderr: string[];
3702
+ toolCalls: JobFeedbackToolCall[];
3498
3703
  }
3499
- interface RecordSearchOptions {
3500
- limit?: number;
3501
- offset?: number;
3502
- classNames?: string[];
3704
+ interface JobFeedbackInput {
3705
+ sentiment: JobFeedbackSentiment;
3706
+ comment?: string | null;
3503
3707
  }
3504
- interface RecordMentionInput {
3505
- className: string;
3506
- id?: string;
3507
- path?: string;
3708
+ interface JobFeedbackRecord {
3709
+ feedbackId: string;
3710
+ tenantId?: string;
3711
+ sessionId: string;
3712
+ environmentId: string;
3713
+ sandboxId?: string;
3714
+ buildId?: string;
3715
+ subjectId?: string;
3716
+ jobId: string;
3717
+ sentiment: JobFeedbackSentiment;
3718
+ comment?: string | null;
3719
+ metadata: JobFeedbackMetadata & Record<string, unknown>;
3720
+ createdAt: number;
3721
+ updatedAt: number;
3508
3722
  }
3509
- interface SessionDocumentResult {
3510
- sessionState: Record<string, unknown> | null;
3511
- document: Record<string, unknown> | null;
3512
- savedAt: number;
3723
+ /**
3724
+ * Persisted feedback row listed at the environment level.
3725
+ */
3726
+ interface EnvironmentFeedbackRecord {
3727
+ feedbackId: string;
3728
+ sessionId: string;
3729
+ jobId: string;
3730
+ sentiment: JobFeedbackSentiment;
3731
+ comment?: string | null;
3732
+ metadata?: Record<string, unknown> | null;
3733
+ createdAt: string | null;
3513
3734
  }
3514
- interface SessionJobListOptions extends SessionCollectionListOptions {
3515
- status?: string | null;
3516
- latest?: boolean | null;
3735
+ /**
3736
+ * Result from submitting a job
3737
+ */
3738
+ interface JobSubmitResult {
3739
+ jobId: string;
3517
3740
  }
3518
- interface SessionCollectionListResult<T = unknown> {
3519
- items: T[];
3520
- nextCursor: string | null;
3521
- totalCount: number;
3741
+ /**
3742
+ * Represents a job executed in the sandbox
3743
+ */
3744
+ interface Job {
3745
+ readonly diagnostics?: JobDiagnostics;
3746
+ /** Unique Job ID */
3747
+ id: string;
3748
+ /** Current status of the job */
3749
+ status: JobStatus;
3750
+ /** Promise that resolves with the job result */
3751
+ result: Promise<unknown>;
3752
+ /** Attach user feedback to this job and persist it with job/session metadata */
3753
+ leaveFeedback(input: JobFeedbackInput): Promise<JobFeedbackRecord>;
3754
+ /** Subscribe to job events */
3755
+ on(event: string, handler: (data: unknown) => void): () => void;
3522
3756
  }
3523
- interface UserEnvironmentPrompt {
3757
+ interface Prompt {
3524
3758
  id: string;
3525
- jobId?: string | null;
3526
- sessionId?: string;
3527
- type: Prompt["type"];
3528
- status: string;
3759
+ /** Job that owns this prompt, when it was opened by a running job. */
3760
+ jobId?: string;
3761
+ /** Harness turn that owns this prompt. */
3762
+ turnId?: string;
3763
+ type: "confirm" | "choice" | "input";
3529
3764
  title: string;
3530
3765
  message: string;
3531
- options?: Prompt["options"];
3766
+ options?: Array<string | {
3767
+ value: string;
3768
+ label: string;
3769
+ description?: string;
3770
+ }>;
3532
3771
  defaultValue?: unknown;
3533
3772
  placeholder?: string;
3534
3773
  allowEmpty?: boolean;
3535
- openedAt?: number | null;
3536
- answeredAt?: number | null;
3774
+ metadata?: Record<string, unknown>;
3775
+ }
3776
+ interface UserMessageShowRefs {
3777
+ entryPaths?: string[];
3778
+ listNames?: string[];
3779
+ variableNames?: string[];
3780
+ fileIds?: string[];
3781
+ }
3782
+ interface UserMessageTarget {
3783
+ className: string;
3784
+ id: string;
3785
+ label?: string;
3786
+ }
3787
+ interface UserMessageInput {
3788
+ /**
3789
+ * Caller-owned logical user-message ID used to correlate optimistic and durable
3790
+ * turns. Reuse this id when retrying a call after an ambiguous timeout.
3791
+ *
3792
+ * When omitted together with `operationId`, the SDK reserves an identity for
3793
+ * that single invocation. A later caller-level retry must supply the
3794
+ * previously chosen id or operationId; identical content is never deduped.
3795
+ */
3796
+ id?: string;
3797
+ /**
3798
+ * Caller-owned idempotency key for the logical append operation. If omitted,
3799
+ * the SDK derives it from `id`, or from the id it reserves for this call.
3800
+ */
3801
+ operationId?: string;
3802
+ content: string;
3803
+ show?: UserMessageShowRefs;
3804
+ target?: UserMessageTarget;
3805
+ }
3806
+ interface UserMessageAppendResult {
3807
+ ok: boolean;
3808
+ messageId: string;
3809
+ timestamp: number;
3810
+ }
3811
+ interface AssistantReplyPublicationInput {
3812
+ /** Stable caller-owned identity for this exact assistant occurrence. */
3813
+ id: string;
3814
+ /** Stable idempotency key reused after an ambiguous response. */
3815
+ operationId: string;
3816
+ /** Exact assistant text to append to the canonical feed. */
3817
+ text: string;
3818
+ }
3819
+ interface AssistantReplyPublicationResult {
3820
+ ok: true;
3821
+ /** Caller-owned logical identity supplied as `id`. */
3822
+ messageId: string;
3823
+ /** Canonical durable feed occurrence identity used by presentation clients. */
3824
+ feedItemId: string;
3825
+ timestamp: number;
3826
+ }
3827
+ interface SessionTranscriptActionSuggestion {
3828
+ suggestionId?: string;
3829
+ label: string;
3830
+ description?: string | null;
3831
+ artifact?: Record<string, unknown>;
3832
+ target?: Record<string, unknown> | null;
3833
+ metadata?: Record<string, unknown>;
3834
+ }
3835
+ interface SessionTranscriptShowRefs extends UserMessageShowRefs {
3836
+ sessionArtifactIds?: string[];
3837
+ actionSuggestions?: SessionTranscriptActionSuggestion[];
3838
+ tables?: FeedTableProjection[];
3839
+ }
3840
+ interface SessionTimelineEvent {
3841
+ id?: string;
3842
+ eventId?: string;
3843
+ kind?: string;
3844
+ type?: string;
3845
+ status?: string | null;
3846
+ message?: string;
3847
+ summary?: string;
3848
+ title?: string;
3849
+ ts?: number;
3850
+ timestamp?: number;
3851
+ at?: number;
3852
+ createdAt?: number;
3853
+ [key: string]: unknown;
3854
+ }
3855
+
3856
+ type SessionFileSource = "dock" | "sdk" | "agent" | "runtime" | "processor" | "library" | "imported";
3857
+ type SessionFileKind = "csv" | "spreadsheet" | "pdf" | "image" | "text" | "document" | "binary";
3858
+ type SessionFileStatus = "queued" | "ready" | "processing" | "processed" | "failed" | "deleted";
3859
+ interface SessionFileRecord {
3860
+ fileId: string;
3861
+ sessionId: string;
3862
+ tenantId: string | null;
3863
+ subjectId: string | null;
3864
+ sandboxId: string | null;
3865
+ environmentId: string | null;
3866
+ filename: string;
3867
+ safeFilename: string;
3868
+ contentType: string;
3869
+ byteLength: number;
3870
+ sha256: string;
3871
+ r2Key: string;
3872
+ kind: SessionFileKind;
3873
+ source: SessionFileSource;
3874
+ status: SessionFileStatus;
3875
+ createdAt: number;
3876
+ updatedAt: number;
3877
+ jobId?: string;
3878
+ parentFileIds?: string[];
3879
+ outputPath?: string;
3880
+ metadata?: Record<string, unknown>;
3881
+ }
3882
+ interface SessionFileUploadOptions {
3883
+ filename?: string;
3884
+ contentType?: string;
3885
+ source?: "dock" | "sdk" | "imported";
3886
+ parentFileIds?: string[];
3887
+ metadata?: Record<string, unknown>;
3888
+ }
3889
+
3890
+ interface SessionJobRecord {
3891
+ executionReport?: JobExecutionReport;
3892
+ jobId: string;
3893
+ status: string;
3894
+ code?: string;
3895
+ createdAt?: number;
3896
+ startedAt?: number;
3897
+ completedAt?: number;
3898
+ durationMs?: number | null;
3899
+ progressPercent?: number | null;
3900
+ progressMessage?: string | null;
3901
+ stdout?: string[];
3902
+ stderr?: string[];
3903
+ result?: unknown;
3904
+ error?: string | null;
3905
+ toolCalls?: JobFeedbackToolCall[];
3906
+ prompts?: Record<string, unknown>;
3907
+ actionSummary?: string[];
3908
+ actionTrace?: Array<Record<string, unknown>>;
3909
+ [key: string]: unknown;
3910
+ }
3911
+ interface SessionTranscriptEntry {
3912
+ id: string;
3913
+ role: "user" | "assistant";
3914
+ content: string;
3915
+ timestamp: number;
3916
+ /** Canonical durable feed position. */
3917
+ sequence: number;
3918
+ jobId?: string;
3919
+ promptId?: string;
3920
+ show?: SessionTranscriptShowRefs;
3921
+ historyContent?: string;
3922
+ source: "feed";
3923
+ }
3924
+ type SessionHeapFieldType = "string" | "number" | "boolean" | "null" | "unknown";
3925
+ interface SessionHeapFieldValue {
3926
+ name: string;
3927
+ type: SessionHeapFieldType;
3928
+ value: string | number | boolean | null;
3929
+ }
3930
+ interface SessionHeapEntry {
3931
+ path: string;
3932
+ className: string;
3933
+ id: string;
3934
+ label?: string | null;
3935
+ description?: string | null;
3936
+ prototypes: string[];
3937
+ fields: SessionHeapFieldValue[];
3938
+ relatedJobIds: string[];
3939
+ source: string;
3940
+ createdAt: number;
3941
+ updatedAt: number;
3942
+ }
3943
+ interface SessionHeapList {
3944
+ name: string;
3945
+ className: string;
3946
+ paths: string[];
3947
+ relatedJobIds: string[];
3948
+ updatedAt: number;
3949
+ }
3950
+ interface SessionHeapVariable {
3951
+ name: string;
3952
+ kind: "entry" | "list" | "scalar";
3953
+ entryPath?: string;
3954
+ listName?: string;
3955
+ value?: string | number | boolean | null;
3956
+ className?: string;
3957
+ updatedAt: number;
3958
+ }
3959
+ interface SessionHeapSnapshot {
3960
+ entriesByPath: Record<string, SessionHeapEntry>;
3961
+ listsByName: Record<string, SessionHeapList>;
3962
+ variablesByName: Record<string, SessionHeapVariable>;
3963
+ updatedAt: number;
3964
+ }
3965
+ interface RecordSearchResult {
3966
+ path: string;
3967
+ className: string;
3968
+ id: string;
3969
+ label: string;
3970
+ description?: string | null;
3971
+ fields: SessionHeapFieldValue[];
3972
+ }
3973
+ interface RecordSearchOptions {
3974
+ limit?: number;
3975
+ offset?: number;
3976
+ classNames?: string[];
3977
+ }
3978
+ interface RecordMentionInput {
3979
+ className: string;
3980
+ id?: string;
3981
+ path?: string;
3982
+ }
3983
+ interface SessionDocumentResult {
3984
+ sessionState: Record<string, unknown> | null;
3985
+ document: Record<string, unknown> | null;
3986
+ savedAt: number;
3987
+ }
3988
+ interface SessionJobListOptions extends SessionCollectionListOptions {
3989
+ status?: string | null;
3990
+ latest?: boolean | null;
3991
+ }
3992
+ interface SessionCollectionListResult<T = unknown> {
3993
+ items: T[];
3994
+ nextCursor: string | null;
3995
+ totalCount: number;
3996
+ }
3997
+ interface UserEnvironmentPrompt {
3998
+ id: string;
3999
+ jobId?: string | null;
4000
+ sessionId?: string;
4001
+ type: Prompt["type"];
4002
+ status: string;
4003
+ title: string;
4004
+ message: string;
4005
+ options?: Prompt["options"];
4006
+ defaultValue?: unknown;
4007
+ placeholder?: string;
4008
+ allowEmpty?: boolean;
4009
+ openedAt?: number | null;
4010
+ answeredAt?: number | null;
3537
4011
  metadata?: Record<string, unknown>;
3538
4012
  }
3539
4013
  interface UserEnvironmentMessagePreview {
@@ -3603,7 +4077,7 @@ interface UserEnvironmentStateOptions {
3603
4077
  * control-plane reconciliation now, which is useful after a known external
3604
4078
  * state change and for deterministic integration tests.
3605
4079
  */
3606
- consistency?: "cached" | "refresh";
4080
+ consistency?: "cached" | "live" | "snapshot" | "refresh";
3607
4081
  }
3608
4082
  interface MarkUserEnvironmentReadOptions {
3609
4083
  sessionId?: string;
@@ -3612,324 +4086,321 @@ interface MarkUserEnvironmentReadOptions {
3612
4086
  readThroughSequence: number;
3613
4087
  }
3614
4088
 
3615
- /**
3616
- * Effect handler for static/global effects: receives (input, context)
4089
+ /** Structural subset of synchronous SQLite drivers (tested with bun:sqlite).
4090
+ * Business queries must use this same database, and must contain no remote effects.
3617
4091
  */
3618
- interface EffectHandlerContext {
3619
- effectClientId: string;
3620
- sandboxId: string;
3621
- environmentId: string;
3622
- /** Stable effect call id assigned by the authoritative session. */
3623
- invocationId?: string;
3624
- /**
3625
- * Stable, runtime-computed key for the authoritative product mutation.
3626
- * Customer adapters should persist this key with the product result and
3627
- * return that same result when an invocation is retried.
3628
- */
3629
- idempotencyKey?: string;
3630
- /** Owning execution/job when the effect is invoked from one. */
3631
- jobId?: string;
3632
- buildId?: string;
3633
- buildVersionNumber?: number;
3634
- sessionId: string;
3635
- tenantId?: string;
3636
- principalId?: string;
3637
- permissionProfileId?: string;
3638
- user: {
3639
- granularId?: string;
3640
- userId?: string;
3641
- subjectId: string;
3642
- identityId?: string;
3643
- principalId?: string;
4092
+ interface CommitSqliteDatabase {
4093
+ exec(sql: string): unknown;
4094
+ query(sql: string): {
4095
+ get(...values: any[]): unknown;
4096
+ all(...values: any[]): unknown[];
4097
+ run(...values: any[]): unknown;
3644
4098
  };
3645
- behaviors?: ResolvedEffectBehaviors;
3646
- invocation?: EffectInvocationMetadata;
3647
- /**
3648
- * Publish durable customer-visible feedback for the directed invocation
3649
- * owned by this effect host or `tool.invoke` callback.
3650
- */
3651
- feedback?: FeedPublisher["feedback"];
3652
- /**
3653
- * Create invocation-owned live feedback that can be updated and settled.
3654
- * Present under the same invocation-scoped conditions as `feedback`.
3655
- */
3656
- transientFeedback?: FeedPublisher["transientFeedback"];
4099
+ transaction<T>(fn: () => T): {
4100
+ (): T;
4101
+ immediate(): T;
4102
+ };
4103
+ }
4104
+ interface CommitStorageInvocation {
4105
+ context: Pick<EffectHandlerContext, "sandboxId" | "environmentId" | "user" | "tenantId" | "principalId" | "invocationId" | "execution">;
4106
+ operationId: string;
4107
+ effectKey: string;
4108
+ input: unknown;
4109
+ }
4110
+ interface StoredEffectCommit {
4111
+ result: unknown;
4112
+ request: EffectCommitRequest;
4113
+ }
4114
+ interface CommitStorage {
4115
+ /** Synchronous callback and source evidence share one real transaction. */
4116
+ execute(invocation: CommitStorageInvocation, handler: () => StoredEffectCommit): StoredEffectCommit;
4117
+ inspect(invocation: CommitStorageInvocation): MutationReceipt | {
4118
+ outcome: "unknown";
4119
+ terminal: false;
4120
+ operationId: string;
4121
+ };
4122
+ fence(invocation: CommitStorageInvocation): MutationReceipt;
4123
+ /** Delivery only: never runs the business handler. */
4124
+ recover(transport: CommitTransport, sandboxId: string): Promise<{
4125
+ delivered: number;
4126
+ pending: number;
4127
+ }>;
4128
+ }
4129
+ /** Configure once; attach to existing commit declarations. No Effect dependency. */
4130
+ declare function sqliteCommitStorage(db: CommitSqliteDatabase): CommitStorage;
4131
+
4132
+ interface ObjectReference {
4133
+ className: string;
4134
+ id: string;
4135
+ /** Canonical graph path, when already known. */
4136
+ path?: string;
4137
+ }
4138
+ interface SourceAcknowledgement {
4139
+ /** Stable product-side operation or record reference. */
4140
+ reference: string;
4141
+ /** Monotonic product version, causal token, or serialized adapter sequence. */
4142
+ version?: string;
3657
4143
  /**
3658
- * Acknowledge the product mutation declared by the active effect. There is
3659
- * intentionally no generic callable `commit(...)` form.
4144
+ * Declares what the version orders. `global` may safely order every target
4145
+ * in one atomic projection; `target` (and omission) is scoped to each
4146
+ * affected target and cannot bridge missing target watermarks.
3660
4147
  */
3661
- commit: EffectCommitContext;
4148
+ versionScope?: "global" | "target";
3662
4149
  }
3663
- interface ResolvedEffectPostCondition {
3664
- condition: string;
3665
- description?: string;
4150
+ interface CommitSafeError {
4151
+ code: string;
4152
+ message: string;
4153
+ retryable: boolean;
4154
+ fieldPath?: string;
3666
4155
  }
3667
- interface ResolvedEffectDryRun {
3668
- enabled: boolean;
3669
- description?: string;
4156
+ interface TransitionOutcomeProjection {
4157
+ /** Authored source outcome key, mapped by the active transition declaration. */
4158
+ key: string;
4159
+ error?: CommitSafeError;
3670
4160
  }
3671
- interface ResolvedEffectReverse {
3672
- handler?: string;
3673
- description?: string;
4161
+ interface CanonicalProjectedRecord {
4162
+ className: string;
4163
+ id: string;
4164
+ label?: string;
4165
+ fields: Record<string, string | number | boolean | null>;
3674
4166
  }
3675
- interface ResolvedEffectApprovalRequired {
3676
- required: boolean;
3677
- reason?: string;
3678
- mode?: string;
4167
+ type ObjectProjectionChange = {
4168
+ kind: "object";
4169
+ operation: "created" | "updated";
4170
+ record: CanonicalProjectedRecord;
4171
+ } | {
4172
+ kind: "object";
4173
+ operation: "deleted";
4174
+ target: ObjectReference;
4175
+ };
4176
+ interface RelationshipProjectionChange {
4177
+ kind: "relationship";
4178
+ operation: "connected" | "disconnected";
4179
+ relationship: string;
4180
+ from: ObjectReference;
4181
+ to: ObjectReference;
3679
4182
  }
3680
- interface ResolvedEffectBehaviors {
3681
- postCondition?: ResolvedEffectPostCondition;
3682
- dryRun?: ResolvedEffectDryRun;
3683
- reverse?: ResolvedEffectReverse;
3684
- approvalRequired?: ResolvedEffectApprovalRequired;
4183
+ interface StateObservationProjectionChange {
4184
+ kind: "state_observation";
4185
+ target: ObjectReference;
4186
+ machine: string;
4187
+ state: string;
3685
4188
  }
3686
- type EffectInvocationMode = "execute" | "dryRun" | "reverse" | "artifactOptions";
3687
- interface EffectArtifactOptionsInvocation {
3688
- fieldName: string;
3689
- query?: string;
3690
- limit?: number;
4189
+ type ProjectionChange = ObjectProjectionChange | RelationshipProjectionChange | StateObservationProjectionChange;
4190
+ interface BaseProjectionResult {
4191
+ source: SourceAcknowledgement;
4192
+ primaryTarget?: ObjectReference;
4193
+ changes: ProjectionChange[];
4194
+ safeSummary?: Record<string, string | number | boolean | null>;
3691
4195
  }
3692
- interface EffectInvocationMetadata {
3693
- mode?: EffectInvocationMode;
3694
- /** Trusted runtime metadata; committed effects are dispatched to backend hosts only. */
3695
- commitKind?: "effect" | "transition";
3696
- /**
3697
- * Present when an effect is being run as part of a durable action artifact.
3698
- * It lets an application distinguish the artifact's authoritative record
3699
- * mirror from an ordinary session effect invocation.
3700
- */
3701
- artifactId?: string;
3702
- reverseHandler?: string;
3703
- sourceEffectKey?: string;
3704
- sourceEffectName?: string;
3705
- /**
3706
- * Present only when the artifact runtime asks an effect for authoritative
3707
- * relationship choices. This is deliberately kept out of the effect input
3708
- * so application handlers receive the exact same action payload they will
3709
- * eventually execute.
3710
- */
3711
- artifactOptions?: EffectArtifactOptionsInvocation;
3712
- /** Resolved, server-authored transition selected for this invocation. */
3713
- transition?: CommitTransitionInvocation;
4196
+ type EffectProjectionResult = BaseProjectionResult & {
4197
+ outcome?: never;
4198
+ };
4199
+ type TransitionProjectionResult = BaseProjectionResult & {
4200
+ outcome: TransitionOutcomeProjection;
4201
+ };
4202
+ type ProjectionResult = EffectProjectionResult | TransitionProjectionResult;
4203
+ type ProjectionMapper<TResult, TProjection extends ProjectionResult = ProjectionResult> = (result: Readonly<TResult>, invocation?: {
4204
+ input: unknown;
4205
+ }) => TProjection;
4206
+ type CommitDeclaration<TResult = any> = ({
4207
+ kind: "effect";
4208
+ project: ProjectionMapper<TResult, EffectProjectionResult>;
4209
+ } | {
4210
+ kind: "transition";
4211
+ project: ProjectionMapper<TResult, TransitionProjectionResult>;
4212
+ /** Automatic snapshot mappers select by product state; custom mappers select an explicit key. */
4213
+ outcomeSelection?: "explicit" | "product_state";
4214
+ }) & {
4215
+ storage?: CommitStorage;
4216
+ };
4217
+ type AgentCommitStatus = "not_requested" | "pending" | "syncing" | "synced" | "failed" | "reconciling";
4218
+ interface CommitChangeReceipt {
4219
+ changeId: string;
4220
+ kind: ProjectionChange["kind"] | "state_transition";
4221
+ operation: string;
4222
+ target: ObjectReference;
4223
+ label?: string;
4224
+ path?: string;
4225
+ status: "pending" | "applied" | "already_applied" | "failed";
4226
+ error?: CommitSafeError;
3714
4227
  }
3715
- type ToolHandler = (input: any, context: EffectHandlerContext) => Promise<unknown>;
3716
- /**
3717
- * Effect handler for instance methods: receives (objectId, input, context)
3718
- */
3719
- type InstanceToolHandler = (id: string, input: any, context: EffectHandlerContext) => Promise<unknown>;
3720
- interface EffectArtifactRelationshipOption {
3721
- id: string;
3722
- label: string;
3723
- /** Canonical graph path used when the ontology has no authored label. */
3724
- path?: string | null;
3725
- description?: string;
3726
- fields?: Record<string, string | number | boolean | null>;
4228
+ interface CommitTransitionReceipt {
4229
+ machine: string;
4230
+ transition: string;
4231
+ from: string;
4232
+ outcome: string;
4233
+ to: string;
4234
+ disposition: "continue" | "error";
3727
4235
  }
3728
- interface EffectArtifactRelationshipOptionsResult {
3729
- items: EffectArtifactRelationshipOption[];
3730
- /** True when the returned page contains the complete eligible option set. */
3731
- complete?: boolean;
3732
- /** True when more eligible options exist beyond this response. */
3733
- hasMore?: boolean;
3734
- /** Number of eligible options for the current query when known. */
3735
- totalCount?: number;
3736
- /** Typed empty/loading outcome that the Artifact UI can explain locally. */
3737
- status?: "ok" | "domain_empty" | "no_match" | "workspace_syncing" | "verification_failed" | "provider_unavailable";
3738
- /**
3739
- * Actionable explanation shown when no eligible record is available.
3740
- * It must be customer-facing and must not expose internal policy machinery.
3741
- */
3742
- emptyMessage?: string;
4236
+ interface CommitReceipt {
4237
+ commitId: string;
4238
+ kind: "effect" | "transition";
4239
+ deduplicated: boolean;
4240
+ product: {
4241
+ status: "committed";
4242
+ reference: string;
4243
+ version?: string;
4244
+ };
4245
+ agent: {
4246
+ status: AgentCommitStatus;
4247
+ environmentId?: string;
4248
+ };
4249
+ primaryTarget?: ObjectReference;
4250
+ affected: CommitChangeReceipt[];
4251
+ transition?: CommitTransitionReceipt;
4252
+ createdAt: string;
4253
+ updatedAt: string;
3743
4254
  }
3744
- type ArtifactOptionsHandler = (input: any, context: EffectHandlerContext) => Promise<EffectArtifactRelationshipOptionsResult>;
3745
- /**
3746
- * Effect schema for declaring or registering an effect.
3747
- *
3748
- * Effects come in three flavours:
3749
- *
3750
- * 1. **Instance methods** — set `className`, omit `static`.
3751
- * In the sandbox: `tolkien.get_bio({ detailed: true })`
3752
- * Handler signature: `(objectId: string, params: any) => any`
3753
- *
3754
- * 2. **Static methods** — set `className` + `static: true`.
3755
- * In the sandbox: `Author.search({ query: 'tolkien' })`
3756
- * Handler signature: `(params: any) => any`
3757
- *
3758
- * 3. **Global effects** — omit `className`.
3759
- * In the sandbox: `global_search({ query: 'rings' })`
3760
- * Handler signature: `(params: any) => any`
3761
- *
3762
- * Both `inputSchema` and `outputSchema` accept JSON Schema objects.
3763
- * The `outputSchema` drives the return type in the auto-generated
3764
- * TypeScript declarations that sandbox code imports from Harness v3 runtime modules.
3765
- */
3766
- interface ToolSchema {
3767
- effectKey?: string;
3768
- name: string;
3769
- /** Authored user-facing operation name. Falls back to the canonical name. */
3770
- label?: string;
3771
- description: string;
3772
- /** JSON Schema for the effect input parameters */
3773
- inputSchema: Record<string, unknown>;
3774
- /**
3775
- * JSON Schema for the tool's return value.
3776
- * Used to generate typed return types in the sandbox TypeScript declarations.
3777
- *
3778
- * @example
3779
- * ```typescript
3780
- * outputSchema: {
3781
- * type: 'object',
3782
- * properties: {
3783
- * bio: { type: 'string', description: 'The biography text' },
3784
- * source: { type: 'string', description: 'Source of the bio' },
3785
- * },
3786
- * required: ['bio'],
3787
- * }
3788
- * // Generates: Promise<{ bio: string; source?: string }>
3789
- * ```
3790
- */
3791
- outputSchema?: Record<string, unknown>;
3792
- stability?: "stable" | "experimental" | "deprecated";
3793
- provenance?: {
3794
- source: "mcp" | "custom";
4255
+ interface ExternalCommitOptions {
4256
+ /** Stable product webhook or change-log event identity. */
4257
+ sourceEventId?: string;
4258
+ }
4259
+ interface ObservationReceipt {
4260
+ observationId: string;
4261
+ deduplicated: boolean;
4262
+ source: SourceAcknowledgement;
4263
+ agent: {
4264
+ status: AgentCommitStatus;
4265
+ environmentId: string;
4266
+ };
4267
+ affected: CommitChangeReceipt[];
4268
+ createdAt: string;
4269
+ updatedAt: string;
4270
+ }
4271
+ /** Payload-free evidence from retained session run reports. */
4272
+ interface SessionHistoryRunEvidence {
4273
+ source: "retained_run_report";
4274
+ goalDecision: {
4275
+ source: "harness_goal_evaluation";
4276
+ decision: "satisfied" | "partial" | "confirmation_denied" | "blocked_by_policy" | "impossible" | "interrupted" | "blocked_by_missing_capability" | "await_user" | "continue" | "no_progress" | "repair_code" | "retry_job" | "retry_prepared" | null;
4277
+ criteria: {
4278
+ passed: number;
4279
+ failed: number;
4280
+ notApplicable: number;
4281
+ unknown: number;
4282
+ } | null;
3795
4283
  };
3796
- tags?: string[];
3797
- /**
3798
- * The class this effect belongs to (e.g., `'author'`, `'book'`).
3799
- * When set, the effect becomes a method on the auto-generated class.
3800
- * Omit for global effects (standalone exported functions).
3801
- */
3802
- className?: string;
3803
- /**
3804
- * If `true`, this is a static/class-level method (no object ID required).
3805
- * If `false` or omitted and `className` is set, this is an instance method
3806
- * that operates on a specific object (the object's real-world ID is
3807
- * passed as the first argument to the handler).
3808
- */
3809
- static?: boolean;
3810
- /**
3811
- * Optional build-version selector for this live effect binding.
3812
- *
3813
- * When omitted, the binding applies to all build versions for the sandbox.
3814
- */
3815
- versionSelector?: EffectVersionSelector;
3816
- /** Declarative runtime behaviors attached to the effect. */
3817
- metamodels?: ManifestEffectMetamodelSpec;
3818
- /** Wire-safe product acknowledgement kind. */
3819
- commit?: {
3820
- kind: "effect" | "transition";
4284
+ approval: "not_recorded";
4285
+ actor: "not_recorded";
4286
+ build: "not_recorded";
4287
+ }
4288
+ /** Persisted ledger facts; missing fields must remain unknown for old records. */
4289
+ interface SessionMutationEvidence {
4290
+ source: "commit_ledger";
4291
+ invocationStatus: "reserved" | "running" | "failed" | "unknown" | "mapping_failed" | "committed";
4292
+ ontologyBuildId?: string;
4293
+ /** False means no correlated retained commit, not proof that the product was unchanged. */
4294
+ productCommitRecorded: boolean;
4295
+ /** Agent projection attempts, distinct from product execution attempts. */
4296
+ agentAttempts?: number;
4297
+ committedAt?: string;
4298
+ completedAt?: string;
4299
+ approval: "not_recorded";
4300
+ actor: "not_recorded";
4301
+ }
4302
+ /** A recorded human answer; it does not establish product execution or commit. */
4303
+ interface SessionPolicyDecisionReceipt {
4304
+ schemaVersion: 1;
4305
+ source: "persisted_human_prompt";
4306
+ promptId: string;
4307
+ artifactId: string;
4308
+ jobId: string;
4309
+ decision: "approved" | "denied";
4310
+ answeredAt: number;
4311
+ recordedAt: number;
4312
+ executionScope?: {
4313
+ attemptId: string;
4314
+ effectKey: string;
3821
4315
  };
3822
4316
  }
3823
- type EffectSchema = ToolSchema;
3824
- /**
3825
- * Effect with handler — what users provide to `registerEffect()`.
3826
- *
3827
- * - **Instance methods** (`className` set, `static` omitted):
3828
- * handler receives `(objectId: string, params: any)`
3829
- * - **Static methods** (`className` set, `static: true`):
3830
- * handler receives `(params: any)`
3831
- * - **Global tools** (no `className`):
3832
- * handler receives `(params: any)`
3833
- */
3834
- interface ToolWithHandler extends ToolSchema {
3835
- /** Handler-local mapper is never serialized into the live effect catalog. */
3836
- commit?: CommitDeclaration<any>;
3837
- handler: ToolHandler | InstanceToolHandler;
3838
- dryRunHandler?: ToolHandler | InstanceToolHandler;
3839
- reverseHandler?: ToolHandler | InstanceToolHandler;
3840
- /**
3841
- * Optional server-authoritative option resolver for prepared artifact
3842
- * relationship and enum fields. It is invoked on the original effect and is
3843
- * not published as a separate agent-visible tool.
3844
- */
3845
- artifactOptionsHandler?: ArtifactOptionsHandler;
4317
+ interface SessionHistoryArtifactExecutionLink {
4318
+ source: "session_artifact_execution";
4319
+ artifactId: string;
4320
+ jobId: string | null;
4321
+ attemptId: string;
4322
+ invocationId: string;
4323
+ effectKey: string;
4324
+ /** Artifact attempt start, not proof of physical product dispatch. */
4325
+ startedAt: number;
4326
+ approval: "recorded" | "not_recorded";
4327
+ policyDecision?: SessionPolicyDecisionReceipt;
4328
+ commit: "recorded" | "not_recorded";
4329
+ commitId?: string;
4330
+ committedAt?: string;
4331
+ commitRecordedAt?: number;
3846
4332
  }
3847
- type EffectWithHandler = ToolWithHandler;
3848
- /**
3849
- * Result from publishing or synchronizing effects
3850
- */
3851
- interface PublishToolsResult {
3852
- accepted: boolean;
3853
- domainRevision: string;
3854
- rejected?: Array<{
3855
- name: string;
3856
- reason: string;
3857
- }>;
4333
+ interface SessionHistoryArtifactEvidence {
4334
+ source: "session_artifact_timeline";
4335
+ policyDecision: "recorded" | "not_recorded";
4336
+ policyDecisions: SessionPolicyDecisionReceipt[];
4337
+ executionLinks?: SessionHistoryArtifactExecutionLink[];
4338
+ actor: "not_recorded";
4339
+ completeness: "retained_only";
3858
4340
  }
3859
- type PublishEffectsResult = PublishToolsResult;
3860
- type EffectVersionSelector = {
3861
- mode: "all";
3862
- } | {
3863
- mode: "exact";
3864
- versionNumber: number;
3865
- } | {
3866
- mode: "before";
3867
- versionNumber: number;
3868
- } | {
3869
- mode: "after";
3870
- versionNumber: number;
3871
- };
3872
- /**
3873
- * Domain state response
3874
- */
3875
- interface DomainState {
3876
- activeDomainRevision?: string;
3877
- tools?: Array<{
3878
- name: string;
3879
- description?: string;
3880
- inputSchema?: Record<string, unknown>;
3881
- outputSchema?: Record<string, unknown>;
3882
- metamodels?: ManifestEffectMetamodelSpec;
3883
- }>;
3884
- [key: string]: unknown;
4341
+ interface SessionMutationView {
4342
+ evidence?: SessionMutationEvidence;
4343
+ invocationId: string;
4344
+ commitId?: string;
4345
+ jobId?: string;
4346
+ artifactId?: string;
4347
+ kind: "effect" | "transition";
4348
+ operationLabel: string;
4349
+ phase: "updating_product" | "checking_product_outcome" | "product_failed" | "updating_agent" | "ready" | "attention";
4350
+ product: {
4351
+ displayName: string;
4352
+ status: "pending" | "updated" | "failed" | "checking";
4353
+ };
4354
+ agent: {
4355
+ displayName: string;
4356
+ status: "not_needed" | "pending" | "updating" | "ready" | "failed";
4357
+ };
4358
+ primaryTarget?: ObjectReference;
4359
+ affected: CommitChangeReceipt[];
4360
+ transition?: CommitTransitionReceipt;
4361
+ error?: CommitSafeError;
4362
+ createdAt: string;
4363
+ updatedAt: string;
3885
4364
  }
3886
- /**
3887
- * Information about a live or declared effect
3888
- */
3889
- interface ToolInfo {
3890
- effectKey?: string;
3891
- /** Unique name of the effect */
3892
- name: string;
3893
- /** Description of what the effect does */
3894
- description?: string;
3895
- /** JSON Schema for effect input */
3896
- inputSchema?: Record<string, unknown>;
3897
- /** JSON Schema for effect output */
3898
- outputSchema?: Record<string, unknown>;
3899
- /** Client ID that published this effect (absent for domain-only entries) */
3900
- clientId?: string;
3901
- /** Whether the effect is ready for use (has a registered handler) */
3902
- ready: boolean;
3903
- /** Timestamp when the effect was published */
3904
- publishedAt?: number;
3905
- /** Class this effect belongs to (instance/static method) */
3906
- className?: string;
3907
- /** Whether this is a static method */
3908
- static?: boolean;
3909
- /** Optional build-version selector associated with the live binding. */
3910
- versionSelector?: EffectVersionSelector;
3911
- /** Declarative runtime behaviors attached to the effect. */
3912
- metamodels?: ManifestEffectMetamodelSpec;
4365
+ interface CommitTransitionOutcomeDeclaration {
4366
+ label?: string;
4367
+ to: string | "$current";
4368
+ primary?: boolean;
4369
+ disposition: "continue" | "error";
3913
4370
  }
3914
- interface EffectInfo extends ToolInfo {
4371
+ interface CommitTransitionInvocation {
4372
+ className: string;
4373
+ objectId: string;
4374
+ objectPath?: string;
4375
+ machine: string;
4376
+ transition: string;
4377
+ from: string;
4378
+ outcomes: Record<string, CommitTransitionOutcomeDeclaration>;
4379
+ fencingToken?: string;
4380
+ /** Internal coordinator identity used to hold one lock across a state goal. */
4381
+ lockOwnerId?: string;
3915
4382
  }
3916
- /**
3917
- * Event data when the list of available effects changes
3918
- */
3919
- interface ToolsChangedEvent {
3920
- /** The current list of all available effects */
3921
- tools: ToolInfo[];
3922
- /** Names of effects that were added or updated */
3923
- added: string[];
3924
- /** Names of effects that were removed */
3925
- removed: string[];
4383
+ interface EffectCommitContext {
4384
+ effect(productResult: unknown): Promise<CommitReceipt>;
4385
+ transition(productResult: unknown): Promise<CommitReceipt>;
3926
4386
  }
3927
- interface EffectsChangedEvent extends ToolsChangedEvent {
3928
- /** The current list of all available effects */
3929
- effects: EffectInfo[];
4387
+ /** Wire-safe payload produced after a local declaration mapper runs. */
4388
+ interface EffectCommitRequest {
4389
+ kind: "effect" | "transition";
4390
+ effectKey: string;
4391
+ effectName: string;
4392
+ operationLabel: string;
4393
+ invocationId: string;
4394
+ idempotencyKey: string;
4395
+ sandboxId: string;
4396
+ environmentId: string;
4397
+ sessionId?: string;
4398
+ jobId?: string;
4399
+ artifactId?: string;
4400
+ buildId?: string;
4401
+ projection: ProjectionResult;
4402
+ transition?: CommitTransitionInvocation;
3930
4403
  }
3931
- type EffectHandler = ToolHandler;
3932
- type InstanceEffectHandler = InstanceToolHandler;
3933
4404
 
3934
4405
  interface CanonicalDocumentQuarantine {
3935
4406
  documentEpoch: number;
@@ -4163,8 +4634,24 @@ declare class Session {
4163
4634
  * `effect.invoke` RPC back to the sandbox effect host, where the registered handlers
4164
4635
  * execute locally and return the result to the sandbox.
4165
4636
  */
4637
+ /** Ask the ontology-declared provider to reconcile an uncertain invocation. */
4638
+ reconcileInvocation(operationId: string, options?: {
4639
+ fence?: boolean;
4640
+ }): Promise<{
4641
+ ok: boolean;
4642
+ operationId: string;
4643
+ outcome?: "committed" | "not_committed";
4644
+ result?: unknown;
4645
+ error?: string;
4646
+ diagnostics?: JobDiagnostics;
4647
+ }>;
4648
+ /** Inspect a canonical commit already recorded by this session. */
4649
+ getCommitReceipt(commitId: string): Promise<CommitReceipt>;
4650
+ /** Retry only graph synchronization of this session's existing product commit. */
4651
+ retryCommitProjection(commitId: string): Promise<CommitReceipt>;
4166
4652
  submitJob(code: string, domainRevisionOrOptions?: string | {
4167
4653
  domainRevision?: string;
4654
+ runtime?: "promise" | "effect";
4168
4655
  metadata?: Record<string, unknown>;
4169
4656
  agent?: Record<string, unknown>;
4170
4657
  }): Promise<Job>;
@@ -4262,7 +4749,9 @@ declare class Session {
4262
4749
  /**
4263
4750
  * Get TypeScript class declarations for the current domain (for LLM/code gen).
4264
4751
  */
4265
- getDomainTypes(): Promise<string>;
4752
+ getDomainTypes(options?: {
4753
+ runtime?: "promise" | "effect";
4754
+ }): Promise<string>;
4266
4755
  /**
4267
4756
  * Get Markdown documentation for the current domain (human-readable).
4268
4757
  */
@@ -4270,7 +4759,9 @@ declare class Session {
4270
4759
  /**
4271
4760
  * Get domain documentation for LLMs. Returns types (preferred) or fallback.
4272
4761
  */
4273
- getDomainDocumentation(): Promise<string>;
4762
+ getDomainDocumentation(options?: {
4763
+ runtime?: "promise" | "effect";
4764
+ }): Promise<string>;
4274
4765
  /**
4275
4766
  * Generate markdown documentation from the domain summary.
4276
4767
  * Class-aware: groups tools by class with property/relationship info.
@@ -4526,7 +5017,7 @@ declare class Environment {
4526
5017
  */
4527
5018
  graphql<T = any>(query: string, variables?: Record<string, any>, options?: {
4528
5019
  idempotencyKey?: string;
4529
- readPreference?: 'prefer-current-v1';
5020
+ readPreference?: "prefer-current-v1";
4530
5021
  }): Promise<GraphQLResult<T>>;
4531
5022
  searchRecords(query: string, options?: RecordSearchOptions): Promise<RecordSearchResult[]>;
4532
5023
  /**
@@ -4871,6 +5362,10 @@ declare class EnvironmentSession extends Session {
4871
5362
  list: (options?: SessionCollectionListOptions) => Promise<SessionCollectionListResult<SessionTimelineEvent>>;
4872
5363
  };
4873
5364
  get jobs(): {
5365
+ events: (jobId: string, options?: {
5366
+ after?: number;
5367
+ limit?: number;
5368
+ }) => Promise<JobEventPage>;
4874
5369
  list: (options?: SessionJobListOptions) => Promise<SessionCollectionListResult<SessionJobRecord>>;
4875
5370
  get: (jobId: string) => Promise<SessionJobRecord>;
4876
5371
  latest: (options?: Pick<SessionJobListOptions, "status">) => Promise<SessionJobRecord | null>;
@@ -5057,6 +5552,8 @@ declare class Granular {
5057
5552
  private usersProviders;
5058
5553
  /** In-flight host connection promises to avoid duplicate concurrent connects */
5059
5554
  private sandboxEffectHostPromises;
5555
+ private effectHostGenerations;
5556
+ private effectHostRecovery;
5060
5557
  /** Ontology-bound environment importer hooks keyed by the caller's ontology identifier. */
5061
5558
  private ontologyImporters;
5062
5559
  /** Resolved importer hooks keyed by sandboxId for fast lookups during openEnvironment(). */
@@ -5239,6 +5736,8 @@ declare class Granular {
5239
5736
  private publishSandboxEffectCatalog;
5240
5737
  private syncSandboxEffectCatalog;
5241
5738
  private recoverEffectHost;
5739
+ private effectCommitTransport;
5740
+ private recoverSourceCommits;
5242
5741
  private startEffectHostHeartbeat;
5243
5742
  private stopEffectHostHeartbeat;
5244
5743
  registerUsers(ontologyNameOrId: string, handler: UsersHandler, options?: UsersProviderOptions): Promise<Readonly<UsersRegistration>>;
@@ -5391,4 +5890,4 @@ declare class Granular {
5391
5890
  private request;
5392
5891
  }
5393
5892
 
5394
- export { type UserMembershipHandler as $, type ArtifactWorkflowNode as A, type EventsFeedTransport as B, type CommitReceipt as C, Environment as D, type EnvironmentData as E, type FeedPublishTransport as F, Granular as G, EnvironmentSession as H, OntologyHandle as I, isGraphQLMutationDocument as J, Session as K, type PublishToolsResult as L, type ManifestEffectMetamodelSpec as M, type ToolHandler as N, type OnboardingTestSessionRestriction as O, type ProjectionResult as P, type InstanceToolHandler as Q, type ResolvedEffectBehaviors as R, type SessionHeapEntry as S, type ToolWithHandler as T, type DomainState as U, type RegisteredUser as V, WSClient as W, type UsersHandler as X, type UsersPage as Y, type UsersPageRequest as Z, type UsersRegistration as _, type EnvironmentRecordImportSummary as a, normalizeFeedDiagnostic as a$, type UsersProviderOptions as a0, type EventsFeedResponse as a1, type EventsFeedOutcome as a2, type EventsFeedEnvironment as a3, type EventsFeedActivityType as a4, type EventsFeedEvidence as a5, type EventsFeedFinding as a6, type EventsFeedOutcomeLink as a7, type EventsFeedActivity as a8, type EventsFeedBreakdown as a9, type FeedTableRow as aA, type FeedTableProjection as aB, type TableFeedItem as aC, type ArtifactFeedItem as aD, type FeedFileSource as aE, type FileFeedItem as aF, type NormalizedSuggestedArtifact as aG, type ActionSuggestionFeedItem as aH, type PromptFeedItem as aI, type TransientFeedItemBase as aJ, type TransientMessageFeedItem as aK, type TransientFeedbackFeedItem as aL, type TransientFeedItem as aM, type FeedSnapshot as aN, type FeedListOptions as aO, type FeedPage as aP, type FeedSubscribeOptions as aQ, type FeedSubscriptionChange as aR, type SessionFeedApi as aS, mergeFeedItemsBySequence as aT, orderTransientFeedItems as aU, type FeedListTransport as aV, type FeedSnapshotRegressionReason as aW, type FeedDiagnostic as aX, type FeedDiagnosticListener as aY, GRANULAR_FEED_DIAGNOSTIC_EVENT as aZ, normalizeFeedDiagnosticKind as a_, type EventsFeedResolution as aa, type EventsFeedProblem as ab, type EventsFeedOccurrence as ac, type EventsFeedFilter as ad, type EventsFeedPage as ae, type EventsFeedDetail as af, type EventsFeedMetrics as ag, type EventsFeedCaptureHealth as ah, type EventsFeedResolutionInput as ai, type EventsFeedSqlRequest as aj, type EventsFeedSqlResult as ak, type FeedSourceActor as al, type FeedSource as am, type FeedIconToken as an, type FeedFeedbackTone as ao, type FeedTransientFeedbackTone as ap, type FeedItemKind as aq, type FeedTarget as ar, type FeedItemBase as as, type MessageFeedItem as at, type FeedbackFeedItem as au, type FeedObjectReference as av, type ObjectsFeedItem as aw, type FeedTableCell as ax, type FeedTableColumn as ay, type FeedTableRowReference as az, type EndpointMode as b, type PermissionRules as b$, emitFeedDiagnosticToDefaultSink as b0, emitFeedDiagnostic as b1, type SessionFeedControllerOptions as b2, type FeedDocumentState as b3, emptyFeedSnapshot as b4, hasCanonicalSessionFeedActivation as b5, isCanonicalSessionFeedDocument as b6, readSessionFeedSnapshot as b7, normalizeFeedPage as b8, SessionFeedController as b9, type GranularAuth as bA, type GranularOptions as bB, type AdoptEnvironmentOptions as bC, type ConnectOptions as bD, type ConversationSessionInfo as bE, type ConversationSessionListOptions as bF, type ConversationSessionListResponse as bG, type ConversationSessionListStatus as bH, type CreateSessionOptions as bI, type OpenEnvironmentOptions as bJ, type RecordUserOptions as bK, type Subject as bL, type User as bM, type Assignment as bN, type AssignmentListResponse as bO, type Build as bP, type BuildListResponse as bQ, type BuildPolicy as bR, type BuildStatus as bS, type CreateEnvironmentData as bT, type CreatePermissionProfileData as bU, type CreateSandboxData as bV, type EnvironmentListResponse as bW, type Manifest as bX, type ManifestListResponse as bY, type PermissionProfile as bZ, type PermissionProfileListResponse as b_, type PublishFeedbackOptions as ba, type PublishTransientFeedbackOptions as bb, type SettleTransientFeedbackOptions as bc, type TransientFeedbackHandle as bd, type FeedPublisher as be, createFeedPublisher as bf, type SessionHistoryRunEvidence as bg, type SessionMutationEvidence as bh, type SessionPolicyDecisionReceipt as bi, type SessionHistoryArtifactExecutionLink as bj, type SessionHistoryArtifactEvidence as bk, type ConditionIR as bl, type MatchedPolicy as bm, type PolicyOperator as bn, type PolicyOrigin as bo, type PolicyPredicateSource as bp, type PolicyRuleIR as bq, type PolicySource as br, type APIError as bs, type AccessTokenProvider as bt, type DeleteResponse as bu, type GraphQLResult as bv, type SessionCollectionListOptions as bw, type StreamEvent as bx, type StreamStats as by, type StreamSubscription as bz, type EffectCommitRequest as c, type SessionFileRecord as c$, type Sandbox as c0, type SandboxListResponse as c1, type SemanticVersionDiff as c2, type SemanticVersionDiffEntry as c3, type Version as c4, type VersionTag as c5, type VersionTracking as c6, type ArtifactOptionsHandler as c7, type EffectArtifactOptionsInvocation as c8, type EffectArtifactRelationshipOption as c9, type ObjectReference as cA, type ProjectionChange as cB, type RelationshipProjectionChange as cC, type SessionMutationView as cD, type SourceAcknowledgement as cE, type StateObservationProjectionChange as cF, type TransitionOutcomeProjection as cG, type TransitionProjectionResult as cH, type AssistantReplyPublicationInput as cI, type AssistantReplyPublicationResult as cJ, type EnvironmentFeedbackRecord as cK, type Job as cL, type JobFeedbackInput as cM, type JobFeedbackMetadata as cN, type JobFeedbackRecord as cO, type JobFeedbackSentiment as cP, type JobFeedbackToolCall as cQ, type JobStatus as cR, type JobSubmitResult as cS, type SessionTimelineEvent as cT, type SessionTranscriptActionSuggestion as cU, type SessionTranscriptShowRefs as cV, type UserMessageAppendResult as cW, type UserMessageInput as cX, type UserMessageShowRefs as cY, type UserMessageTarget as cZ, type SessionFileKind as c_, type EffectArtifactRelationshipOptionsResult as ca, type EffectHandler as cb, type EffectInfo as cc, type EffectInvocationMetadata as cd, type EffectInvocationMode as ce, type EffectSchema as cf, type EffectVersionSelector as cg, type EffectWithHandler as ch, type EffectsChangedEvent as ci, type InstanceEffectHandler as cj, type PublishEffectsResult as ck, type ResolvedEffectApprovalRequired as cl, type ResolvedEffectDryRun as cm, type ResolvedEffectPostCondition as cn, type ResolvedEffectReverse as co, type ToolInfo as cp, type ToolsChangedEvent as cq, type AgentCommitStatus as cr, type BaseProjectionResult as cs, type CanonicalProjectedRecord as ct, type CommitChangeReceipt as cu, type CommitSafeError as cv, type CommitTransitionReceipt as cw, type EffectCommitContext as cx, type ExternalCommitOptions as cy, type ObjectProjectionChange as cz, type ProjectionMapper as d, type RPCResponse as d$, type SessionFileSource as d0, type SessionFileStatus as d1, type SessionFileUploadOptions as d2, type ArtifactApprovalDecisionInput as d3, type ArtifactApprovalDecisionResult as d4, type ArtifactApprovalTask as d5, type ArtifactApprovalTaskListOptions as d6, type ArtifactApprovalTaskStatus as d7, type ArtifactWorkflowAttention as d8, type ArtifactWorkflowCompletionState as d9, type ManualActionSource as dA, type ManualActionStatus as dB, type ManualActionSuggestion as dC, type ManualActionSuggestionOptions as dD, type ManualActionTarget as dE, type RecordManualActionInput as dF, type MarkUserEnvironmentReadOptions as dG, type RecordMentionInput as dH, type RecordSearchOptions as dI, type RecordSearchResult as dJ, type SessionCollectionListResult as dK, type SessionDocumentResult as dL, type SessionHeapFieldType as dM, type SessionHeapFieldValue as dN, type SessionHeapVariable as dO, type SessionJobListOptions as dP, type SessionJobRecord as dQ, type UserEnvironmentArtifactAttention as dR, type UserEnvironmentMessagePreview as dS, type UserEnvironmentPrompt as dT, type UserEnvironmentSessionState as dU, type UserEnvironmentState as dV, type UserEnvironmentStateOptions as dW, type FeedTransientPatchMessage as dX, type JobActionTraceMessage as dY, type RPCRequest as dZ, type RPCRequestFromServer as d_, type ArtifactWorkflowNodeAvailability as da, type ArtifactWorkflowNodeKind as db, type ArtifactWorkflowOperationPhase as dc, type ArtifactWorkflowRecap as dd, type ArtifactWorkflowRecapItem as de, type SessionArtifactApprovalOptions as df, type SessionArtifactAutonomyPolicy as dg, type SessionArtifactExecutionOptions as dh, type SessionArtifactExecutionResult as di, type SessionArtifactFieldProvenance as dj, type SessionArtifactFieldProvenanceSource as dk, type SessionArtifactKind as dl, type SessionArtifactListOptions as dm, type SessionArtifactRelationshipCreateInput as dn, type SessionArtifactRelationshipOption as dp, type SessionArtifactRelationshipOptionsInput as dq, type SessionArtifactRelationshipOptionsResult as dr, type SessionArtifactRequestContext as ds, type SessionArtifactRequestContextSource as dt, type SessionArtifactStatus as du, type SessionArtifactValidationResult as dv, type ManualActionListOptions as dw, type ManualActionOccurrence as dx, type ManualActionRecordResult as dy, type ManualActionRelatedRecord as dz, type CommitTransitionOutcomeDeclaration as e, type OnboardingProductPostcondition as e$, type SnapshotResetMessage as e0, type ToolInvokeParams as e1, type ToolResultParams as e2, type WSClientOptions as e3, type WSDisconnectInfo as e4, type WSReconnectErrorInfo as e5, type DefineRelationshipOptions as e6, type EnvironmentSetupImporterClaim as e7, type EnvironmentSetupLifecycleStatus as e8, type EnvironmentSetupSummary as e9, type ManifestEventStreamDef as eA, type ManifestEventTypeDef as eB, type ManifestFilterBySpec as eC, type ManifestImport as eD, type ManifestOperation as eE, type ManifestPostConditionSpec as eF, type ManifestPropertySpec as eG, type ManifestRelationshipDef as eH, type ManifestReverseSpec as eI, type ManifestStateMachineSpec as eJ, type ManifestStateMachineStateSpec as eK, type ManifestStateMachineTransitionSpec as eL, type ManifestStateTransitionActionSpec as eM, type ManifestStateTransitionAssigneeSpec as eN, type ManifestStateTransitionExpectedOutcomeSpec as eO, type ManifestStateTransitionInputBinding as eP, type ManifestStateTransitionOutcomeSpec as eQ, type ManifestStateTransitionPermissionSpec as eR, type ManifestStateTransitionRelatedStateRequirementSpec as eS, type ManifestStateTransitionRequirementsSpec as eT, type ManifestValidationOperator as eU, type ManifestValidationRuleSpec as eV, type ManifestVolume as eW, type OnboardingTestOperation as eX, type OnboardingDenialTarget as eY, type OnboardingTestActionProfileSelection as eZ, type OnboardingTestActionProfile as e_, type EnvironmentSetupTriggerReason as ea, type EnvironmentStateMachineProxy as eb, type EnvironmentStateObservationInput as ec, type EnvironmentStateProxy as ed, type EnvironmentStateTarget as ee, type EnvironmentStateUpdateInput as ef, type ModelRef as eg, type RecordImport as eh, type RecordImportItem as ei, type RecordImportItemStatus as ej, type RecordImportOptions as ek, type RecordImportStats as el, type RecordImportStatus as em, type RecordImportWriteMode as en, type RecordObjectResult as eo, type RecordObjectStateValue as ep, type RecordObjectsChunkInfo as eq, type RecordObjectsOptions as er, type RelationshipInfo as es, type RunEnvironmentImporterOptions as et, type ManifestApprovalRequiredSpec as eu, type ManifestCreatesSpec as ev, type ManifestDryRunSpec as ew, type ManifestEffectDeclaration as ex, type ManifestEffectSchema as ey, type ManifestEnumRuleSpec as ez, type CommitDeclaration as f, type OnboardingTestRequestInput as f0, type OnboardingTestRequest as f1, type OnboardingTestObservationInput as f2, type OnboardingTestObservation as f3, type OnboardingTestOutcome as f4, type OnboardingTestEvidence as f5, onboardingExpectedDenialObserved as f6, type DevelopmentUser as f7, type DevelopmentProviderContext as f8, type DevelopmentUserProgress as f9, type DevelopmentUserOperation as fa, type DevelopmentPostcondition as fb, type DevelopmentAdditionalObservation as fc, type DevelopmentReadback as fd, type DevelopmentCollectionBinding as fe, type DevelopmentIncrementalStatus as ff, type DevelopmentPostconditionVerifier as fg, type DevelopmentProviderOptions as fh, type DevelopmentProviderRegistration as fi, developmentPreparationOperationKey as fj, DevelopmentProvider as fk, type CustomerSkillRegistration as fl, type CustomerSkillOptions as fm, customerSkillSlug as fn, customerSkillOrigin as fo, customerSkillPrompt as fp, customerSkillInstructions as fq, createCustomerSkillSetup as fr, type EffectHandlerContext as g, type RecordObjectOptions as h, type ManifestContent as i, type CommitTransitionInvocation as j, type SessionHeapList as k, type FeedItem as l, type SessionHeapSnapshot as m, type Prompt as n, type SessionTranscriptEntry as o, type ArtifactWorkflowNodeStatus as p, type ArtifactWorkflow as q, type SessionArtifactRecord as r, type ToolSchema as s, type EnvironmentImporter as t, type EnvironmentImporterImportOptions as u, type EffectProjectionResult as v, type ObservationReceipt as w, type StructuralSteeringContext as x, EventsFeed as y, eventsFeedSearch as z };
5893
+ export { type StateMachineDefinition as $, type ArtifactWorkflowNode as A, Environment as B, type CommitTransport as C, EnvironmentSession as D, type EnvironmentData as E, type FeedPublishTransport as F, Granular as G, OntologyHandle as H, isGraphQLMutationDocument as I, Session as J, type PublishToolsResult as K, type ToolHandler as L, type ManifestEffectMetamodelSpec as M, type InstanceToolHandler as N, type OnboardingTestSessionRestriction as O, type ProjectionResult as P, type DomainState as Q, type ResolvedEffectBehaviors as R, type SessionHeapEntry as S, type ToolWithHandler as T, canonicalizeCommitValue as U, defineEffect as V, WSClient as W, defineProjection as X, defineStateMachine as Y, validateProjectionResult as Z, type DefinedStateMachine as _, type EnvironmentRecordImportSummary as a, type FeedTableProjection as a$, type RegisteredUser as a0, type UsersHandler as a1, type UsersPage as a2, type UsersPageRequest as a3, type UsersRegistration as a4, type UserMembershipHandler as a5, type UsersProviderOptions as a6, JobExecutionError as a7, type JobFailure as a8, type DomainFailure as a9, type EventsFeedResolution as aA, type EventsFeedProblem as aB, type EventsFeedOccurrence as aC, type EventsFeedFilter as aD, type EventsFeedPage as aE, type EventsFeedDetail as aF, type EventsFeedMetrics as aG, type EventsFeedCaptureHealth as aH, type EventsFeedResolutionInput as aI, type EventsFeedSqlRequest as aJ, type EventsFeedSqlResult as aK, type FeedSourceActor as aL, type FeedSource as aM, type FeedIconToken as aN, type FeedFeedbackTone as aO, type FeedTransientFeedbackTone as aP, type FeedItemKind as aQ, type FeedTarget as aR, type FeedItemBase as aS, type MessageFeedItem as aT, type FeedbackFeedItem as aU, type FeedObjectReference as aV, type ObjectsFeedItem as aW, type FeedTableCell as aX, type FeedTableColumn as aY, type FeedTableRowReference as aZ, type FeedTableRow as a_, type JobDiagnostics as aa, type FailureHandling as ab, type MutationReceipt as ac, type VersionToken as ad, type JobExecutionReport as ae, type ExecutionNode as af, type ExecutionEvent as ag, type ExecutionCapture as ah, type QueryObservation as ai, type QueryStage as aj, type QueryPredicate as ak, type BehaviorFinding as al, type HostExecutionEvidence as am, sqliteCommitStorage as an, type CommitStorage as ao, type CommitSqliteDatabase as ap, type CommitStorageInvocation as aq, type EventsFeedResponse as ar, type EventsFeedOutcome as as, type EventsFeedEnvironment as at, type EventsFeedActivityType as au, type EventsFeedEvidence as av, type EventsFeedFinding as aw, type EventsFeedOutcomeLink as ax, type EventsFeedActivity as ay, type EventsFeedBreakdown as az, type EndpointMode as b, type GranularOptions as b$, type TableFeedItem as b0, type ArtifactFeedItem as b1, type FeedFileSource as b2, type FileFeedItem as b3, type NormalizedSuggestedArtifact as b4, type ActionSuggestionFeedItem as b5, type PromptFeedItem as b6, type TransientFeedItemBase as b7, type TransientMessageFeedItem as b8, type TransientFeedbackFeedItem as b9, type PublishFeedbackOptions as bA, type PublishTransientFeedbackOptions as bB, type SettleTransientFeedbackOptions as bC, type TransientFeedbackHandle as bD, type FeedPublisher as bE, createFeedPublisher as bF, type SessionHistoryRunEvidence as bG, type SessionMutationEvidence as bH, type SessionPolicyDecisionReceipt as bI, type SessionHistoryArtifactExecutionLink as bJ, type SessionHistoryArtifactEvidence as bK, type ConditionIR as bL, type MatchedPolicy as bM, type PolicyOperator as bN, type PolicyOrigin as bO, type PolicyPredicateSource as bP, type PolicyRuleIR as bQ, type PolicySource as bR, type APIError as bS, type AccessTokenProvider as bT, type DeleteResponse as bU, type GraphQLResult as bV, type SessionCollectionListOptions as bW, type StreamEvent as bX, type StreamStats as bY, type StreamSubscription as bZ, type GranularAuth as b_, type TransientFeedItem as ba, type FeedSnapshot as bb, type FeedListOptions as bc, type FeedPage as bd, type FeedSubscribeOptions as be, type FeedSubscriptionChange as bf, type SessionFeedApi as bg, mergeFeedItemsBySequence as bh, orderTransientFeedItems as bi, type FeedListTransport as bj, type FeedSnapshotRegressionReason as bk, type FeedDiagnostic as bl, type FeedDiagnosticListener as bm, GRANULAR_FEED_DIAGNOSTIC_EVENT as bn, normalizeFeedDiagnosticKind as bo, normalizeFeedDiagnostic as bp, emitFeedDiagnosticToDefaultSink as bq, emitFeedDiagnostic as br, type SessionFeedControllerOptions as bs, type FeedDocumentState as bt, emptyFeedSnapshot as bu, hasCanonicalSessionFeedActivation as bv, isCanonicalSessionFeedDocument as bw, readSessionFeedSnapshot as bx, normalizeFeedPage as by, SessionFeedController as bz, type EffectHandlerContext as c, type ObjectProjectionChange as c$, type AdoptEnvironmentOptions as c0, type ConnectOptions as c1, type ConversationSessionInfo as c2, type ConversationSessionListOptions as c3, type ConversationSessionListResponse as c4, type ConversationSessionListStatus as c5, type CreateSessionOptions as c6, type OpenEnvironmentOptions as c7, type RecordUserOptions as c8, type Subject as c9, type EffectArtifactRelationshipOptionsResult as cA, type EffectHandler as cB, type EffectInfo as cC, type EffectInvocationMetadata as cD, type EffectInvocationMode as cE, type EffectSchema as cF, type EffectVersionSelector as cG, type EffectWithHandler as cH, type EffectsChangedEvent as cI, type InstanceEffectHandler as cJ, type PublishEffectsResult as cK, type ResolvedEffectApprovalRequired as cL, type ResolvedEffectDryRun as cM, type ResolvedEffectPostCondition as cN, type ResolvedEffectReverse as cO, type ToolInfo as cP, type ToolsChangedEvent as cQ, type AgentCommitStatus as cR, type BaseProjectionResult as cS, type CanonicalProjectedRecord as cT, type CommitChangeReceipt as cU, type CommitSafeError as cV, type CommitTransitionOutcomeDeclaration as cW, type CommitTransitionReceipt as cX, type EffectCommitContext as cY, type EffectCommitRequest as cZ, type ExternalCommitOptions as c_, type User as ca, type Assignment as cb, type AssignmentListResponse as cc, type Build as cd, type BuildListResponse as ce, type BuildPolicy as cf, type BuildStatus as cg, type CreateEnvironmentData as ch, type CreatePermissionProfileData as ci, type CreateSandboxData as cj, type EnvironmentListResponse as ck, type Manifest as cl, type ManifestListResponse as cm, type PermissionProfile as cn, type PermissionProfileListResponse as co, type PermissionRules as cp, type Sandbox as cq, type SandboxListResponse as cr, type SemanticVersionDiff as cs, type SemanticVersionDiffEntry as ct, type Version as cu, type VersionTag as cv, type VersionTracking as cw, type ArtifactOptionsHandler as cx, type EffectArtifactOptionsInvocation as cy, type EffectArtifactRelationshipOption as cz, type CommitReceipt as d, type ManualActionRelatedRecord as d$, type ObjectReference as d0, type ProjectionChange as d1, type RelationshipProjectionChange as d2, type SessionMutationView as d3, type SourceAcknowledgement as d4, type StateObservationProjectionChange as d5, type TransitionOutcomeProjection as d6, type TransitionProjectionResult as d7, type AssistantReplyPublicationInput as d8, type AssistantReplyPublicationResult as d9, type ArtifactApprovalTaskStatus as dA, type ArtifactWorkflowAttention as dB, type ArtifactWorkflowCompletionState as dC, type ArtifactWorkflowNodeAvailability as dD, type ArtifactWorkflowNodeKind as dE, type ArtifactWorkflowOperationPhase as dF, type ArtifactWorkflowRecap as dG, type ArtifactWorkflowRecapItem as dH, type SessionArtifactApprovalOptions as dI, type SessionArtifactAutonomyPolicy as dJ, type SessionArtifactExecutionOptions as dK, type SessionArtifactExecutionResult as dL, type SessionArtifactFieldProvenance as dM, type SessionArtifactFieldProvenanceSource as dN, type SessionArtifactKind as dO, type SessionArtifactListOptions as dP, type SessionArtifactRelationshipCreateInput as dQ, type SessionArtifactRelationshipOption as dR, type SessionArtifactRelationshipOptionsInput as dS, type SessionArtifactRelationshipOptionsResult as dT, type SessionArtifactRequestContext as dU, type SessionArtifactRequestContextSource as dV, type SessionArtifactStatus as dW, type SessionArtifactValidationResult as dX, type ManualActionListOptions as dY, type ManualActionOccurrence as dZ, type ManualActionRecordResult as d_, type EnvironmentFeedbackRecord as da, type Job as db, type JobFeedbackInput as dc, type JobFeedbackMetadata as dd, type JobFeedbackRecord as de, type JobFeedbackSentiment as df, type JobFeedbackToolCall as dg, type JobStatus as dh, type JobSubmitResult as di, type SessionTimelineEvent as dj, type SessionTranscriptActionSuggestion as dk, type SessionTranscriptShowRefs as dl, type UserMessageAppendResult as dm, type UserMessageInput as dn, type UserMessageShowRefs as dp, type UserMessageTarget as dq, type SessionFileKind as dr, type SessionFileRecord as ds, type SessionFileSource as dt, type SessionFileStatus as du, type SessionFileUploadOptions as dv, type ArtifactApprovalDecisionInput as dw, type ArtifactApprovalDecisionResult as dx, type ArtifactApprovalTask as dy, type ArtifactApprovalTaskListOptions as dz, type RecordObjectOptions as e, type ManifestEnumRuleSpec as e$, type ManualActionSource as e0, type ManualActionStatus as e1, type ManualActionSuggestion as e2, type ManualActionSuggestionOptions as e3, type ManualActionTarget as e4, type RecordManualActionInput as e5, type MarkUserEnvironmentReadOptions as e6, type RecordMentionInput as e7, type RecordSearchOptions as e8, type RecordSearchResult as e9, type EnvironmentSetupLifecycleStatus as eA, type EnvironmentSetupSummary as eB, type EnvironmentSetupTriggerReason as eC, type EnvironmentStateMachineProxy as eD, type EnvironmentStateObservationInput as eE, type EnvironmentStateProxy as eF, type EnvironmentStateTarget as eG, type EnvironmentStateUpdateInput as eH, type ModelRef as eI, type RecordImport as eJ, type RecordImportItem as eK, type RecordImportItemStatus as eL, type RecordImportOptions as eM, type RecordImportStats as eN, type RecordImportStatus as eO, type RecordImportWriteMode as eP, type RecordObjectResult as eQ, type RecordObjectStateValue as eR, type RecordObjectsChunkInfo as eS, type RecordObjectsOptions as eT, type RelationshipInfo as eU, type RunEnvironmentImporterOptions as eV, type ManifestApprovalRequiredSpec as eW, type ManifestCreatesSpec as eX, type ManifestDryRunSpec as eY, type ManifestEffectDeclaration as eZ, type ManifestEffectSchema as e_, type SessionCollectionListResult as ea, type SessionDocumentResult as eb, type SessionHeapFieldType as ec, type SessionHeapFieldValue as ed, type SessionHeapVariable as ee, type SessionJobListOptions as ef, type SessionJobRecord as eg, type UserEnvironmentArtifactAttention as eh, type UserEnvironmentMessagePreview as ei, type UserEnvironmentPrompt as ej, type UserEnvironmentSessionState as ek, type UserEnvironmentState as el, type UserEnvironmentStateOptions as em, type FeedTransientPatchMessage as en, type JobActionTraceMessage as eo, type RPCRequest as ep, type RPCRequestFromServer as eq, type RPCResponse as er, type SnapshotResetMessage as es, type ToolInvokeParams as et, type ToolResultParams as eu, type WSClientOptions as ev, type WSDisconnectInfo as ew, type WSReconnectErrorInfo as ex, type DefineRelationshipOptions as ey, type EnvironmentSetupImporterClaim as ez, type ManifestContent as f, type ManifestEventStreamDef as f0, type ManifestEventTypeDef as f1, type ManifestFilterBySpec as f2, type ManifestImport as f3, type ManifestOperation as f4, type ManifestPostConditionSpec as f5, type ManifestPropertySpec as f6, type ManifestRelationshipDef as f7, type ManifestReverseSpec as f8, type ManifestStateMachineSpec as f9, type DevelopmentProviderContext as fA, type DevelopmentUserProgress as fB, type DevelopmentUserOperation as fC, type DevelopmentPostcondition as fD, type DevelopmentAdditionalObservation as fE, type DevelopmentReadback as fF, type DevelopmentCollectionBinding as fG, type DevelopmentIncrementalStatus as fH, type DevelopmentPostconditionVerifier as fI, type DevelopmentProviderOptions as fJ, type DevelopmentProviderRegistration as fK, developmentPreparationOperationKey as fL, DevelopmentProvider as fM, type CustomerSkillRegistration as fN, type CustomerSkillOptions as fO, customerSkillSlug as fP, customerSkillOrigin as fQ, customerSkillPrompt as fR, customerSkillInstructions as fS, createCustomerSkillSetup as fT, type ManifestStateMachineStateSpec as fa, type ManifestStateMachineTransitionSpec as fb, type ManifestStateTransitionActionSpec as fc, type ManifestStateTransitionAssigneeSpec as fd, type ManifestStateTransitionExpectedOutcomeSpec as fe, type ManifestStateTransitionInputBinding as ff, type ManifestStateTransitionOutcomeSpec as fg, type ManifestStateTransitionPermissionSpec as fh, type ManifestStateTransitionRelatedStateRequirementSpec as fi, type ManifestStateTransitionRequirementsSpec as fj, type ManifestValidationOperator as fk, type ManifestValidationRuleSpec as fl, type ManifestVolume as fm, type OnboardingTestOperation as fn, type OnboardingDenialTarget as fo, type OnboardingTestActionProfileSelection as fp, type OnboardingTestActionProfile as fq, type OnboardingProductPostcondition as fr, type OnboardingTestRequestInput as fs, type OnboardingTestRequest as ft, type OnboardingTestObservationInput as fu, type OnboardingTestObservation as fv, type OnboardingTestOutcome as fw, type OnboardingTestEvidence as fx, onboardingExpectedDenialObserved as fy, type DevelopmentUser as fz, type CommitTransitionInvocation as g, type SessionHeapList as h, type FeedItem as i, type SessionHeapSnapshot as j, type Prompt as k, type SessionTranscriptEntry as l, type ArtifactWorkflowNodeStatus as m, type ArtifactWorkflow as n, type SessionArtifactRecord as o, type ToolSchema as p, type CommitDeclaration as q, type EnvironmentImporter as r, type EnvironmentImporterImportOptions as s, type ProjectionMapper as t, type EffectProjectionResult as u, type ObservationReceipt as v, type StructuralSteeringContext as w, EventsFeed as x, eventsFeedSearch as y, type EventsFeedTransport as z };