@granular-software/sdk 0.4.80 → 0.4.82

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