@granular-software/sdk 0.4.79 → 0.4.81

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