@granular-software/sdk 0.4.20 → 0.4.21

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.
package/dist/cli/index.js CHANGED
@@ -17990,10 +17990,15 @@ var Session = class {
17990
17990
  * ```typescript
17991
17991
  * import { Author, Book, global_search } from './sandbox-tools';
17992
17992
  *
17993
- * const authors = await Author.list({ limit: 10, saveAs: 'recent_authors' });
17993
+ * const totalAuthors = await Author.count();
17994
+ * const firstAuthorsPage = await Author.page({ page: 1, perPage: 10, saveAs: 'recent_authors' });
17995
+ * const authors = firstAuthorsPage.items;
17994
17996
  * const tolkien = await Author.get({ path: 'author_tolkien' });
17995
17997
  * const bio = await tolkien.get_bio({ detailed: true });
17996
17998
  * const books = await tolkien.get_books();
17999
+ * for await (const author of Author.iterate({ perPage: 100, maxItems: 500 })) {
18000
+ * console.log(author.id);
18001
+ * }
17997
18002
  * ```
17998
18003
  *
17999
18004
  * Effect calls (instance methods, static methods, global functions) trigger
@@ -18860,9 +18865,9 @@ var STANDARD_MODULES_OPERATIONS = [
18860
18865
  { create: "class", extends: "entity", has: {} },
18861
18866
  { create: "user", extends: "entity", has: { email: { value: void 0 }, firstName: { value: void 0 }, lastName: { value: void 0 } } },
18862
18867
  { create: "company", extends: "entity", has: { name: { value: void 0 }, website: { value: void 0 } } },
18863
- { create: "string", has: { value: { value: void 0 } } },
18864
- { create: "number", has: { value: { value: 0 } } },
18865
- { create: "boolean", has: { value: { value: false } } },
18868
+ { create: "string", has: {} },
18869
+ { create: "number", has: {} },
18870
+ { create: "boolean", has: {} },
18866
18871
  { create: "tool_parameter", has: { name: { value: void 0 }, type: { value: "string" }, description: { value: void 0 }, required: { value: false } } }
18867
18872
  ];
18868
18873
  var BUILTIN_MODULES = {
@@ -18872,6 +18877,8 @@ var DEFAULT_DIRECT_RECORD_OBJECTS_REQUEST_BATCH_SIZE = 100;
18872
18877
  var MAX_RECORD_OBJECTS_CONCURRENCY = 16;
18873
18878
  var DEFAULT_DIRECT_RECORD_OBJECTS_RETRY_COUNT = 3;
18874
18879
  var DEFAULT_DIRECT_RECORD_OBJECTS_RETRY_DELAY_MS = 1e3;
18880
+ var LOCAL_CONTROL_REQUEST_RETRY_COUNT = 4;
18881
+ var LOCAL_CONTROL_REQUEST_RETRY_DELAY_MS = 500;
18875
18882
  function planRecordObjectsChunks(records, batchSize) {
18876
18883
  const total = records.length;
18877
18884
  const size = Math.max(1, Math.min(batchSize, total));
@@ -18886,6 +18893,17 @@ function planRecordObjectsChunks(records, batchSize) {
18886
18893
  function sleep(ms) {
18887
18894
  return new Promise((resolve2) => setTimeout(resolve2, ms));
18888
18895
  }
18896
+ function isLocalControlUrl(url) {
18897
+ try {
18898
+ const parsed = new URL(url);
18899
+ return parsed.hostname === "127.0.0.1" || parsed.hostname === "localhost" || parsed.hostname === "::1";
18900
+ } catch {
18901
+ return false;
18902
+ }
18903
+ }
18904
+ function isRetryableLocalWorkerRestart(status, body, url) {
18905
+ return isLocalControlUrl(url) && (status === 503 && body.includes("Your worker restarted mid-request") || status === 500 && body.includes("Network connection lost"));
18906
+ }
18889
18907
  function isRetryableRecordObjectsError(error2) {
18890
18908
  const message = error2 instanceof Error ? error2.message : String(error2);
18891
18909
  return /worker restarted mid-request|econnreset|network|socket connection was closed unexpectedly|timed out/i.test(message);
@@ -20909,23 +20927,36 @@ var Granular = class _Granular {
20909
20927
  if (this.debugHttp) {
20910
20928
  console.log(`[SDK] Requesting: ${url}`);
20911
20929
  }
20912
- const response = await fetch(url, {
20913
- ...options,
20914
- headers: {
20915
- "Authorization": `Bearer ${this.apiKey}`,
20916
- "Content-Type": "application/json",
20917
- "Connection": "close",
20918
- ...options.headers
20930
+ for (let attempt = 1; attempt <= LOCAL_CONTROL_REQUEST_RETRY_COUNT; attempt += 1) {
20931
+ const response = await fetch(url, {
20932
+ ...options,
20933
+ headers: {
20934
+ "Authorization": `Bearer ${this.apiKey}`,
20935
+ "Content-Type": "application/json",
20936
+ "Connection": "close",
20937
+ ...options.headers
20938
+ }
20939
+ });
20940
+ if (response.ok) {
20941
+ if (response.status === 204) {
20942
+ return { deleted: true };
20943
+ }
20944
+ return response.json();
20919
20945
  }
20920
- });
20921
- if (!response.ok) {
20922
20946
  const errorText = await response.text();
20947
+ const retryable = isRetryableLocalWorkerRestart(response.status, errorText, url);
20948
+ if (retryable && attempt < LOCAL_CONTROL_REQUEST_RETRY_COUNT) {
20949
+ if (this.debugHttp) {
20950
+ console.warn(
20951
+ `[SDK] Retrying local control request after worker restart (${attempt}/${LOCAL_CONTROL_REQUEST_RETRY_COUNT - 1} retries used): ${url}`
20952
+ );
20953
+ }
20954
+ await sleep(LOCAL_CONTROL_REQUEST_RETRY_DELAY_MS * attempt);
20955
+ continue;
20956
+ }
20923
20957
  throw new Error(`Granular API Error (${response.status}): ${errorText}`);
20924
20958
  }
20925
- if (response.status === 204) {
20926
- return { deleted: true };
20927
- }
20928
- return response.json();
20959
+ throw new Error(`Granular API Error: exhausted retries for ${url}`);
20929
20960
  }
20930
20961
  };
20931
20962
 
@@ -1314,10 +1314,15 @@ declare class Session {
1314
1314
  * ```typescript
1315
1315
  * import { Author, Book, global_search } from './sandbox-tools';
1316
1316
  *
1317
- * const authors = await Author.list({ limit: 10, saveAs: 'recent_authors' });
1317
+ * const totalAuthors = await Author.count();
1318
+ * const firstAuthorsPage = await Author.page({ page: 1, perPage: 10, saveAs: 'recent_authors' });
1319
+ * const authors = firstAuthorsPage.items;
1318
1320
  * const tolkien = await Author.get({ path: 'author_tolkien' });
1319
1321
  * const bio = await tolkien.get_bio({ detailed: true });
1320
1322
  * const books = await tolkien.get_books();
1323
+ * for await (const author of Author.iterate({ perPage: 100, maxItems: 500 })) {
1324
+ * console.log(author.id);
1325
+ * }
1321
1326
  * ```
1322
1327
  *
1323
1328
  * Effect calls (instance methods, static methods, global functions) trigger
@@ -2048,4 +2053,4 @@ declare class Granular {
2048
2053
  private request;
2049
2054
  }
2050
2055
 
2051
- export { type EffectInvocationMode as $, type AccessTokenProvider as A, type BuildPolicy as B, type ConnectOptions as C, type DomainState as D, type EffectHandlerContext as E, type Manifest as F, Granular as G, type ManifestListResponse as H, type InstanceToolHandler as I, type BuildStatus as J, type Build as K, type Version as L, type ManifestEffectMetamodelSpec as M, type BuildListResponse as N, type SemanticVersionDiffEntry as O, type Prompt as P, type SemanticVersionDiff as Q, type ResolvedEffectBehaviors as R, type SessionHeapEntry as S, type ToolWithHandler as T, type User as U, type VersionTracking as V, WSClient as W, type ResolvedEffectPostCondition as X, type ResolvedEffectDryRun as Y, type ResolvedEffectReverse as Z, type ResolvedEffectApprovalRequired as _, type SessionHeapList as a, type ManifestContent as a$, type EffectInvocationMetadata as a0, type EffectSchema as a1, type EffectWithHandler as a2, type PublishEffectsResult as a3, type ToolInfo as a4, type EffectInfo as a5, type ToolsChangedEvent as a6, type EffectsChangedEvent as a7, type EffectHandler as a8, type InstanceEffectHandler as a9, type RecordObjectsOptions as aA, type RecordImportStatus as aB, type RecordImportItemStatus as aC, type RecordImportStats as aD, type RecordImportItem as aE, type RecordImport as aF, type EnvironmentRecordImportSummary as aG, type ManifestPropertySpec as aH, type ManifestValidationOperator as aI, type ManifestEnumRuleSpec as aJ, type ManifestFilterBySpec as aK, type ManifestValidationRuleSpec as aL, type ManifestStateMachineStateSpec as aM, type ManifestStateMachineTransitionSpec as aN, type ManifestStateMachineSpec as aO, type ManifestPostConditionSpec as aP, type ManifestDryRunSpec as aQ, type ManifestReverseSpec as aR, type ManifestApprovalRequiredSpec as aS, type ManifestRelationshipDef as aT, type ManifestEffectSchema as aU, type ManifestEffectDeclaration as aV, type ManifestEventTypeDef as aW, type ManifestEventStreamDef as aX, type ManifestOperation as aY, type ManifestImport as aZ, type ManifestVolume as a_, type JobStatus as aa, type JobFeedbackSentiment as ab, type JobFeedbackToolCall as ac, type JobFeedbackMetadata as ad, type JobFeedbackInput as ae, type JobFeedbackRecord as af, type JobSubmitResult as ag, type Job as ah, type SessionHeapFieldType as ai, type SessionHeapFieldValue as aj, type SessionHeapVariable as ak, type WSDisconnectInfo as al, type WSReconnectErrorInfo as am, type WSClientOptions as an, type RPCRequest as ao, type RPCResponse as ap, type SyncMessage as aq, type RPCRequestFromServer as ar, type ToolInvokeParams as as, type ToolResultParams as at, type ModelRef as au, type RelationshipInfo as av, type DefineRelationshipOptions as aw, type RecordObjectOptions as ax, type RecordObjectResult as ay, type RecordObjectsChunkInfo as az, type SessionHeapSnapshot as b, type GraphQLResult as b0, type APIError as b1, type DeleteResponse as b2, type StreamEvent as b3, type StreamSubscription as b4, type StreamStats as b5, Environment as c, Session as d, type ToolSchema as e, type PublishToolsResult as f, type ToolHandler as g, type EndpointMode as h, type GranularOptions as i, type GranularAuth as j, type RecordUserOptions as k, type Subject as l, type ConversationSessionInfo as m, type Sandbox as n, type CreateSandboxData as o, type SandboxListResponse as p, type PermissionRules as q, type PermissionProfile as r, type CreatePermissionProfileData as s, type PermissionProfileListResponse as t, type Assignment as u, type AssignmentListResponse as v, type VersionTag as w, type EnvironmentData as x, type CreateEnvironmentData as y, type EnvironmentListResponse as z };
2056
+ export { type EffectInvocationMode as $, type AccessTokenProvider as A, type BuildPolicy as B, type ConnectOptions as C, type DomainState as D, type EndpointMode as E, type Manifest as F, Granular as G, type ManifestListResponse as H, type InstanceToolHandler as I, type BuildStatus as J, type Build as K, type Version as L, type ManifestEffectMetamodelSpec as M, type BuildListResponse as N, type SemanticVersionDiffEntry as O, type Prompt as P, type SemanticVersionDiff as Q, type ResolvedEffectBehaviors as R, type SessionHeapEntry as S, type ToolWithHandler as T, type User as U, type VersionTracking as V, WSClient as W, type ResolvedEffectPostCondition as X, type ResolvedEffectDryRun as Y, type ResolvedEffectReverse as Z, type ResolvedEffectApprovalRequired as _, type EffectHandlerContext as a, type ManifestContent as a$, type EffectInvocationMetadata as a0, type EffectSchema as a1, type EffectWithHandler as a2, type PublishEffectsResult as a3, type ToolInfo as a4, type EffectInfo as a5, type ToolsChangedEvent as a6, type EffectsChangedEvent as a7, type EffectHandler as a8, type InstanceEffectHandler as a9, type RecordObjectsOptions as aA, type RecordImportStatus as aB, type RecordImportItemStatus as aC, type RecordImportStats as aD, type RecordImportItem as aE, type RecordImport as aF, type EnvironmentRecordImportSummary as aG, type ManifestPropertySpec as aH, type ManifestValidationOperator as aI, type ManifestEnumRuleSpec as aJ, type ManifestFilterBySpec as aK, type ManifestValidationRuleSpec as aL, type ManifestStateMachineStateSpec as aM, type ManifestStateMachineTransitionSpec as aN, type ManifestStateMachineSpec as aO, type ManifestPostConditionSpec as aP, type ManifestDryRunSpec as aQ, type ManifestReverseSpec as aR, type ManifestApprovalRequiredSpec as aS, type ManifestRelationshipDef as aT, type ManifestEffectSchema as aU, type ManifestEffectDeclaration as aV, type ManifestEventTypeDef as aW, type ManifestEventStreamDef as aX, type ManifestOperation as aY, type ManifestImport as aZ, type ManifestVolume as a_, type JobStatus as aa, type JobFeedbackSentiment as ab, type JobFeedbackToolCall as ac, type JobFeedbackMetadata as ad, type JobFeedbackInput as ae, type JobFeedbackRecord as af, type JobSubmitResult as ag, type Job as ah, type SessionHeapFieldType as ai, type SessionHeapFieldValue as aj, type SessionHeapVariable as ak, type WSDisconnectInfo as al, type WSReconnectErrorInfo as am, type WSClientOptions as an, type RPCRequest as ao, type RPCResponse as ap, type SyncMessage as aq, type RPCRequestFromServer as ar, type ToolInvokeParams as as, type ToolResultParams as at, type ModelRef as au, type RelationshipInfo as av, type DefineRelationshipOptions as aw, type RecordObjectOptions as ax, type RecordObjectResult as ay, type RecordObjectsChunkInfo as az, type SessionHeapList as b, type GraphQLResult as b0, type APIError as b1, type DeleteResponse as b2, type StreamEvent as b3, type StreamSubscription as b4, type StreamStats as b5, type SessionHeapSnapshot as c, Environment as d, Session as e, type ToolSchema as f, type PublishToolsResult as g, type ToolHandler as h, type GranularOptions as i, type GranularAuth as j, type RecordUserOptions as k, type Subject as l, type ConversationSessionInfo as m, type Sandbox as n, type CreateSandboxData as o, type SandboxListResponse as p, type PermissionRules as q, type PermissionProfile as r, type CreatePermissionProfileData as s, type PermissionProfileListResponse as t, type Assignment as u, type AssignmentListResponse as v, type VersionTag as w, type EnvironmentData as x, type CreateEnvironmentData as y, type EnvironmentListResponse as z };
@@ -1314,10 +1314,15 @@ declare class Session {
1314
1314
  * ```typescript
1315
1315
  * import { Author, Book, global_search } from './sandbox-tools';
1316
1316
  *
1317
- * const authors = await Author.list({ limit: 10, saveAs: 'recent_authors' });
1317
+ * const totalAuthors = await Author.count();
1318
+ * const firstAuthorsPage = await Author.page({ page: 1, perPage: 10, saveAs: 'recent_authors' });
1319
+ * const authors = firstAuthorsPage.items;
1318
1320
  * const tolkien = await Author.get({ path: 'author_tolkien' });
1319
1321
  * const bio = await tolkien.get_bio({ detailed: true });
1320
1322
  * const books = await tolkien.get_books();
1323
+ * for await (const author of Author.iterate({ perPage: 100, maxItems: 500 })) {
1324
+ * console.log(author.id);
1325
+ * }
1321
1326
  * ```
1322
1327
  *
1323
1328
  * Effect calls (instance methods, static methods, global functions) trigger
@@ -2048,4 +2053,4 @@ declare class Granular {
2048
2053
  private request;
2049
2054
  }
2050
2055
 
2051
- export { type EffectInvocationMode as $, type AccessTokenProvider as A, type BuildPolicy as B, type ConnectOptions as C, type DomainState as D, type EffectHandlerContext as E, type Manifest as F, Granular as G, type ManifestListResponse as H, type InstanceToolHandler as I, type BuildStatus as J, type Build as K, type Version as L, type ManifestEffectMetamodelSpec as M, type BuildListResponse as N, type SemanticVersionDiffEntry as O, type Prompt as P, type SemanticVersionDiff as Q, type ResolvedEffectBehaviors as R, type SessionHeapEntry as S, type ToolWithHandler as T, type User as U, type VersionTracking as V, WSClient as W, type ResolvedEffectPostCondition as X, type ResolvedEffectDryRun as Y, type ResolvedEffectReverse as Z, type ResolvedEffectApprovalRequired as _, type SessionHeapList as a, type ManifestContent as a$, type EffectInvocationMetadata as a0, type EffectSchema as a1, type EffectWithHandler as a2, type PublishEffectsResult as a3, type ToolInfo as a4, type EffectInfo as a5, type ToolsChangedEvent as a6, type EffectsChangedEvent as a7, type EffectHandler as a8, type InstanceEffectHandler as a9, type RecordObjectsOptions as aA, type RecordImportStatus as aB, type RecordImportItemStatus as aC, type RecordImportStats as aD, type RecordImportItem as aE, type RecordImport as aF, type EnvironmentRecordImportSummary as aG, type ManifestPropertySpec as aH, type ManifestValidationOperator as aI, type ManifestEnumRuleSpec as aJ, type ManifestFilterBySpec as aK, type ManifestValidationRuleSpec as aL, type ManifestStateMachineStateSpec as aM, type ManifestStateMachineTransitionSpec as aN, type ManifestStateMachineSpec as aO, type ManifestPostConditionSpec as aP, type ManifestDryRunSpec as aQ, type ManifestReverseSpec as aR, type ManifestApprovalRequiredSpec as aS, type ManifestRelationshipDef as aT, type ManifestEffectSchema as aU, type ManifestEffectDeclaration as aV, type ManifestEventTypeDef as aW, type ManifestEventStreamDef as aX, type ManifestOperation as aY, type ManifestImport as aZ, type ManifestVolume as a_, type JobStatus as aa, type JobFeedbackSentiment as ab, type JobFeedbackToolCall as ac, type JobFeedbackMetadata as ad, type JobFeedbackInput as ae, type JobFeedbackRecord as af, type JobSubmitResult as ag, type Job as ah, type SessionHeapFieldType as ai, type SessionHeapFieldValue as aj, type SessionHeapVariable as ak, type WSDisconnectInfo as al, type WSReconnectErrorInfo as am, type WSClientOptions as an, type RPCRequest as ao, type RPCResponse as ap, type SyncMessage as aq, type RPCRequestFromServer as ar, type ToolInvokeParams as as, type ToolResultParams as at, type ModelRef as au, type RelationshipInfo as av, type DefineRelationshipOptions as aw, type RecordObjectOptions as ax, type RecordObjectResult as ay, type RecordObjectsChunkInfo as az, type SessionHeapSnapshot as b, type GraphQLResult as b0, type APIError as b1, type DeleteResponse as b2, type StreamEvent as b3, type StreamSubscription as b4, type StreamStats as b5, Environment as c, Session as d, type ToolSchema as e, type PublishToolsResult as f, type ToolHandler as g, type EndpointMode as h, type GranularOptions as i, type GranularAuth as j, type RecordUserOptions as k, type Subject as l, type ConversationSessionInfo as m, type Sandbox as n, type CreateSandboxData as o, type SandboxListResponse as p, type PermissionRules as q, type PermissionProfile as r, type CreatePermissionProfileData as s, type PermissionProfileListResponse as t, type Assignment as u, type AssignmentListResponse as v, type VersionTag as w, type EnvironmentData as x, type CreateEnvironmentData as y, type EnvironmentListResponse as z };
2056
+ export { type EffectInvocationMode as $, type AccessTokenProvider as A, type BuildPolicy as B, type ConnectOptions as C, type DomainState as D, type EndpointMode as E, type Manifest as F, Granular as G, type ManifestListResponse as H, type InstanceToolHandler as I, type BuildStatus as J, type Build as K, type Version as L, type ManifestEffectMetamodelSpec as M, type BuildListResponse as N, type SemanticVersionDiffEntry as O, type Prompt as P, type SemanticVersionDiff as Q, type ResolvedEffectBehaviors as R, type SessionHeapEntry as S, type ToolWithHandler as T, type User as U, type VersionTracking as V, WSClient as W, type ResolvedEffectPostCondition as X, type ResolvedEffectDryRun as Y, type ResolvedEffectReverse as Z, type ResolvedEffectApprovalRequired as _, type EffectHandlerContext as a, type ManifestContent as a$, type EffectInvocationMetadata as a0, type EffectSchema as a1, type EffectWithHandler as a2, type PublishEffectsResult as a3, type ToolInfo as a4, type EffectInfo as a5, type ToolsChangedEvent as a6, type EffectsChangedEvent as a7, type EffectHandler as a8, type InstanceEffectHandler as a9, type RecordObjectsOptions as aA, type RecordImportStatus as aB, type RecordImportItemStatus as aC, type RecordImportStats as aD, type RecordImportItem as aE, type RecordImport as aF, type EnvironmentRecordImportSummary as aG, type ManifestPropertySpec as aH, type ManifestValidationOperator as aI, type ManifestEnumRuleSpec as aJ, type ManifestFilterBySpec as aK, type ManifestValidationRuleSpec as aL, type ManifestStateMachineStateSpec as aM, type ManifestStateMachineTransitionSpec as aN, type ManifestStateMachineSpec as aO, type ManifestPostConditionSpec as aP, type ManifestDryRunSpec as aQ, type ManifestReverseSpec as aR, type ManifestApprovalRequiredSpec as aS, type ManifestRelationshipDef as aT, type ManifestEffectSchema as aU, type ManifestEffectDeclaration as aV, type ManifestEventTypeDef as aW, type ManifestEventStreamDef as aX, type ManifestOperation as aY, type ManifestImport as aZ, type ManifestVolume as a_, type JobStatus as aa, type JobFeedbackSentiment as ab, type JobFeedbackToolCall as ac, type JobFeedbackMetadata as ad, type JobFeedbackInput as ae, type JobFeedbackRecord as af, type JobSubmitResult as ag, type Job as ah, type SessionHeapFieldType as ai, type SessionHeapFieldValue as aj, type SessionHeapVariable as ak, type WSDisconnectInfo as al, type WSReconnectErrorInfo as am, type WSClientOptions as an, type RPCRequest as ao, type RPCResponse as ap, type SyncMessage as aq, type RPCRequestFromServer as ar, type ToolInvokeParams as as, type ToolResultParams as at, type ModelRef as au, type RelationshipInfo as av, type DefineRelationshipOptions as aw, type RecordObjectOptions as ax, type RecordObjectResult as ay, type RecordObjectsChunkInfo as az, type SessionHeapList as b, type GraphQLResult as b0, type APIError as b1, type DeleteResponse as b2, type StreamEvent as b3, type StreamSubscription as b4, type StreamStats as b5, type SessionHeapSnapshot as c, Environment as d, Session as e, type ToolSchema as f, type PublishToolsResult as g, type ToolHandler as h, type GranularOptions as i, type GranularAuth as j, type RecordUserOptions as k, type Subject as l, type ConversationSessionInfo as m, type Sandbox as n, type CreateSandboxData as o, type SandboxListResponse as p, type PermissionRules as q, type PermissionProfile as r, type CreatePermissionProfileData as s, type PermissionProfileListResponse as t, type Assignment as u, type AssignmentListResponse as v, type VersionTag as w, type EnvironmentData as x, type CreateEnvironmentData as y, type EnvironmentListResponse as z };
package/dist/index.d.mts CHANGED
@@ -1,9 +1,24 @@
1
- import { T as ToolWithHandler, E as EffectHandlerContext, M as ManifestEffectMetamodelSpec, R as ResolvedEffectBehaviors, S as SessionHeapEntry, a as SessionHeapList, b as SessionHeapSnapshot, P as Prompt } from './client-DWYdWpS-.mjs';
2
- export { b1 as APIError, A as AccessTokenProvider, u as Assignment, v as AssignmentListResponse, K as Build, N as BuildListResponse, B as BuildPolicy, J as BuildStatus, C as ConnectOptions, m as ConversationSessionInfo, y as CreateEnvironmentData, s as CreatePermissionProfileData, o as CreateSandboxData, aw as DefineRelationshipOptions, b2 as DeleteResponse, D as DomainState, a8 as EffectHandler, a5 as EffectInfo, a0 as EffectInvocationMetadata, $ as EffectInvocationMode, a1 as EffectSchema, a2 as EffectWithHandler, a7 as EffectsChangedEvent, h as EndpointMode, c as Environment, x as EnvironmentData, z as EnvironmentListResponse, aG as EnvironmentRecordImportSummary, G as Granular, j as GranularAuth, i as GranularOptions, b0 as GraphQLResult, a9 as InstanceEffectHandler, I as InstanceToolHandler, ah as Job, ae as JobFeedbackInput, ad as JobFeedbackMetadata, af as JobFeedbackRecord, ab as JobFeedbackSentiment, ac as JobFeedbackToolCall, aa as JobStatus, ag as JobSubmitResult, F as Manifest, aS as ManifestApprovalRequiredSpec, a$ as ManifestContent, aQ as ManifestDryRunSpec, aV as ManifestEffectDeclaration, aU as ManifestEffectSchema, aJ as ManifestEnumRuleSpec, aX as ManifestEventStreamDef, aW as ManifestEventTypeDef, aK as ManifestFilterBySpec, aZ as ManifestImport, H as ManifestListResponse, aY as ManifestOperation, aP as ManifestPostConditionSpec, aH as ManifestPropertySpec, aT as ManifestRelationshipDef, aR as ManifestReverseSpec, aO as ManifestStateMachineSpec, aM as ManifestStateMachineStateSpec, aN as ManifestStateMachineTransitionSpec, aI as ManifestValidationOperator, aL as ManifestValidationRuleSpec, a_ as ManifestVolume, au as ModelRef, r as PermissionProfile, t as PermissionProfileListResponse, q as PermissionRules, a3 as PublishEffectsResult, f as PublishToolsResult, ao as RPCRequest, ar as RPCRequestFromServer, ap as RPCResponse, aF as RecordImport, aE as RecordImportItem, aC as RecordImportItemStatus, aD as RecordImportStats, aB as RecordImportStatus, ax as RecordObjectOptions, ay as RecordObjectResult, az as RecordObjectsChunkInfo, aA as RecordObjectsOptions, k as RecordUserOptions, av as RelationshipInfo, _ as ResolvedEffectApprovalRequired, Y as ResolvedEffectDryRun, X as ResolvedEffectPostCondition, Z as ResolvedEffectReverse, n as Sandbox, p as SandboxListResponse, Q as SemanticVersionDiff, O as SemanticVersionDiffEntry, d as Session, ai as SessionHeapFieldType, aj as SessionHeapFieldValue, ak as SessionHeapVariable, b3 as StreamEvent, b5 as StreamStats, b4 as StreamSubscription, l as Subject, aq as SyncMessage, g as ToolHandler, a4 as ToolInfo, as as ToolInvokeParams, at as ToolResultParams, e as ToolSchema, a6 as ToolsChangedEvent, U as User, L as Version, w as VersionTag, V as VersionTracking, W as WSClient, an as WSClientOptions, al as WSDisconnectInfo, am as WSReconnectErrorInfo } from './client-DWYdWpS-.mjs';
1
+ import { E as EndpointMode, T as ToolWithHandler, a as EffectHandlerContext, M as ManifestEffectMetamodelSpec, R as ResolvedEffectBehaviors, S as SessionHeapEntry, b as SessionHeapList, c as SessionHeapSnapshot, P as Prompt } from './client-DLGC0mJk.mjs';
2
+ export { b1 as APIError, A as AccessTokenProvider, u as Assignment, v as AssignmentListResponse, K as Build, N as BuildListResponse, B as BuildPolicy, J as BuildStatus, C as ConnectOptions, m as ConversationSessionInfo, y as CreateEnvironmentData, s as CreatePermissionProfileData, o as CreateSandboxData, aw as DefineRelationshipOptions, b2 as DeleteResponse, D as DomainState, a8 as EffectHandler, a5 as EffectInfo, a0 as EffectInvocationMetadata, $ as EffectInvocationMode, a1 as EffectSchema, a2 as EffectWithHandler, a7 as EffectsChangedEvent, d as Environment, x as EnvironmentData, z as EnvironmentListResponse, aG as EnvironmentRecordImportSummary, G as Granular, j as GranularAuth, i as GranularOptions, b0 as GraphQLResult, a9 as InstanceEffectHandler, I as InstanceToolHandler, ah as Job, ae as JobFeedbackInput, ad as JobFeedbackMetadata, af as JobFeedbackRecord, ab as JobFeedbackSentiment, ac as JobFeedbackToolCall, aa as JobStatus, ag as JobSubmitResult, F as Manifest, aS as ManifestApprovalRequiredSpec, a$ as ManifestContent, aQ as ManifestDryRunSpec, aV as ManifestEffectDeclaration, aU as ManifestEffectSchema, aJ as ManifestEnumRuleSpec, aX as ManifestEventStreamDef, aW as ManifestEventTypeDef, aK as ManifestFilterBySpec, aZ as ManifestImport, H as ManifestListResponse, aY as ManifestOperation, aP as ManifestPostConditionSpec, aH as ManifestPropertySpec, aT as ManifestRelationshipDef, aR as ManifestReverseSpec, aO as ManifestStateMachineSpec, aM as ManifestStateMachineStateSpec, aN as ManifestStateMachineTransitionSpec, aI as ManifestValidationOperator, aL as ManifestValidationRuleSpec, a_ as ManifestVolume, au as ModelRef, r as PermissionProfile, t as PermissionProfileListResponse, q as PermissionRules, a3 as PublishEffectsResult, g as PublishToolsResult, ao as RPCRequest, ar as RPCRequestFromServer, ap as RPCResponse, aF as RecordImport, aE as RecordImportItem, aC as RecordImportItemStatus, aD as RecordImportStats, aB as RecordImportStatus, ax as RecordObjectOptions, ay as RecordObjectResult, az as RecordObjectsChunkInfo, aA as RecordObjectsOptions, k as RecordUserOptions, av as RelationshipInfo, _ as ResolvedEffectApprovalRequired, Y as ResolvedEffectDryRun, X as ResolvedEffectPostCondition, Z as ResolvedEffectReverse, n as Sandbox, p as SandboxListResponse, Q as SemanticVersionDiff, O as SemanticVersionDiffEntry, e as Session, ai as SessionHeapFieldType, aj as SessionHeapFieldValue, ak as SessionHeapVariable, b3 as StreamEvent, b5 as StreamStats, b4 as StreamSubscription, l as Subject, aq as SyncMessage, h as ToolHandler, a4 as ToolInfo, as as ToolInvokeParams, at as ToolResultParams, f as ToolSchema, a6 as ToolsChangedEvent, U as User, L as Version, w as VersionTag, V as VersionTracking, W as WSClient, an as WSClientOptions, al as WSDisconnectInfo, am as WSReconnectErrorInfo } from './client-DLGC0mJk.mjs';
3
3
  export { BuildGranularAgentSystemPromptInput, GeneratedJobCodeIssue, GranularAgentExecutionCheckpoint, GranularAgentHeapSummaryOptions, GranularAgentSessionContext, GranularAgentToolInfo, GranularAgentWorkflowFocus, HarnessContinuationDecision, HarnessControllerBudgets, HarnessProjectionOptions, HarnessPromptLike, HarnessVerifierSnapshot, HarnessVerifierSnapshotInput, buildContinuationInstruction, buildGranularAgentCheckpointBlock, buildGranularAgentDomainBlock, buildGranularAgentHeapBlock, buildGranularAgentLoopBlock, buildGranularAgentSessionBlock, buildGranularAgentSystemPrompt, buildGranularAgentToolBlock, buildGranularAgentWorkflowBlock, createHarnessVerifierSnapshot, evaluateContinuation, getCurrentClosureId, getExclusivePromptTarget, hasOpenPrompt, projectHeapSummary, projectLoopSummary, projectWorkflowFocus, projectWorkflowSummary, reviewGeneratedJobCode } from './agent-harness.mjs';
4
4
  import '@automerge/automerge';
5
5
  import '@automerge/automerge/slim';
6
6
 
7
+ declare function isLocalApiUrl(url: string): boolean;
8
+ /**
9
+ * Local dev + `sk_*` (WorkOS org key in env): map to the local gn_sk e2e key by default so every
10
+ * request (HTTP + WebSocket) uses the same tenant as the v2 UI on localhost (`default`). Without
11
+ * this, the SDK passes `sk_*` through → gateway resolves org_… while the UI still uses gn_sk →
12
+ * you only see old default-tenant sandboxes and new ingest data looks “missing”.
13
+ *
14
+ * - `GRANULAR_LOCAL_API_KEY` — explicit key to use instead (e.g. another gn_sk).
15
+ * - `GRANULAR_DISABLE_LOCAL_API_KEY_FALLBACK=1` — do not swap; send the real `sk_*` (org tenant +
16
+ * WorkOS validation on the gateway). Use when the UI is also on that org (e.g. session auth +
17
+ * NEXT_PUBLIC_DISABLE_LOCAL_API_KEY_FALLBACK on the app).
18
+ */
19
+ declare function resolveAuthTokenForApiUrl(authToken: string, apiUrl: string): string;
20
+ declare function resolveApiUrl(explicitApiUrl?: string, mode?: EndpointMode): string;
21
+
7
22
  type EffectRuntimeRequest = {
8
23
  effectKey: string;
9
24
  effectName: string;
@@ -41,4 +56,4 @@ declare function normalizePromptType(raw: Record<string, unknown> | null | undef
41
56
  declare function normalizePrompt(rawValue: unknown): Prompt | null;
42
57
  declare function resolvePromptAnswer(prompt: Prompt | undefined, answer: unknown): unknown;
43
58
 
44
- export { EffectHandlerContext, type JobPresentation, ManifestEffectMetamodelSpec, Prompt, ResolvedEffectBehaviors, SessionHeapEntry, SessionHeapList, SessionHeapSnapshot, ToolWithHandler, extractPromptTokens, invokeRegisteredEffect, normalizeEffectBehaviors, normalizePrompt, normalizePromptText, normalizePromptType, resolveJobPresentation, resolvePromptAnswer, scorePromptChoiceMatch };
59
+ export { EffectHandlerContext, EndpointMode, type JobPresentation, ManifestEffectMetamodelSpec, Prompt, ResolvedEffectBehaviors, SessionHeapEntry, SessionHeapList, SessionHeapSnapshot, ToolWithHandler, extractPromptTokens, invokeRegisteredEffect, isLocalApiUrl, normalizeEffectBehaviors, normalizePrompt, normalizePromptText, normalizePromptType, resolveApiUrl, resolveAuthTokenForApiUrl, resolveJobPresentation, resolvePromptAnswer, scorePromptChoiceMatch };
package/dist/index.d.ts CHANGED
@@ -1,9 +1,24 @@
1
- import { T as ToolWithHandler, E as EffectHandlerContext, M as ManifestEffectMetamodelSpec, R as ResolvedEffectBehaviors, S as SessionHeapEntry, a as SessionHeapList, b as SessionHeapSnapshot, P as Prompt } from './client-DWYdWpS-.js';
2
- export { b1 as APIError, A as AccessTokenProvider, u as Assignment, v as AssignmentListResponse, K as Build, N as BuildListResponse, B as BuildPolicy, J as BuildStatus, C as ConnectOptions, m as ConversationSessionInfo, y as CreateEnvironmentData, s as CreatePermissionProfileData, o as CreateSandboxData, aw as DefineRelationshipOptions, b2 as DeleteResponse, D as DomainState, a8 as EffectHandler, a5 as EffectInfo, a0 as EffectInvocationMetadata, $ as EffectInvocationMode, a1 as EffectSchema, a2 as EffectWithHandler, a7 as EffectsChangedEvent, h as EndpointMode, c as Environment, x as EnvironmentData, z as EnvironmentListResponse, aG as EnvironmentRecordImportSummary, G as Granular, j as GranularAuth, i as GranularOptions, b0 as GraphQLResult, a9 as InstanceEffectHandler, I as InstanceToolHandler, ah as Job, ae as JobFeedbackInput, ad as JobFeedbackMetadata, af as JobFeedbackRecord, ab as JobFeedbackSentiment, ac as JobFeedbackToolCall, aa as JobStatus, ag as JobSubmitResult, F as Manifest, aS as ManifestApprovalRequiredSpec, a$ as ManifestContent, aQ as ManifestDryRunSpec, aV as ManifestEffectDeclaration, aU as ManifestEffectSchema, aJ as ManifestEnumRuleSpec, aX as ManifestEventStreamDef, aW as ManifestEventTypeDef, aK as ManifestFilterBySpec, aZ as ManifestImport, H as ManifestListResponse, aY as ManifestOperation, aP as ManifestPostConditionSpec, aH as ManifestPropertySpec, aT as ManifestRelationshipDef, aR as ManifestReverseSpec, aO as ManifestStateMachineSpec, aM as ManifestStateMachineStateSpec, aN as ManifestStateMachineTransitionSpec, aI as ManifestValidationOperator, aL as ManifestValidationRuleSpec, a_ as ManifestVolume, au as ModelRef, r as PermissionProfile, t as PermissionProfileListResponse, q as PermissionRules, a3 as PublishEffectsResult, f as PublishToolsResult, ao as RPCRequest, ar as RPCRequestFromServer, ap as RPCResponse, aF as RecordImport, aE as RecordImportItem, aC as RecordImportItemStatus, aD as RecordImportStats, aB as RecordImportStatus, ax as RecordObjectOptions, ay as RecordObjectResult, az as RecordObjectsChunkInfo, aA as RecordObjectsOptions, k as RecordUserOptions, av as RelationshipInfo, _ as ResolvedEffectApprovalRequired, Y as ResolvedEffectDryRun, X as ResolvedEffectPostCondition, Z as ResolvedEffectReverse, n as Sandbox, p as SandboxListResponse, Q as SemanticVersionDiff, O as SemanticVersionDiffEntry, d as Session, ai as SessionHeapFieldType, aj as SessionHeapFieldValue, ak as SessionHeapVariable, b3 as StreamEvent, b5 as StreamStats, b4 as StreamSubscription, l as Subject, aq as SyncMessage, g as ToolHandler, a4 as ToolInfo, as as ToolInvokeParams, at as ToolResultParams, e as ToolSchema, a6 as ToolsChangedEvent, U as User, L as Version, w as VersionTag, V as VersionTracking, W as WSClient, an as WSClientOptions, al as WSDisconnectInfo, am as WSReconnectErrorInfo } from './client-DWYdWpS-.js';
1
+ import { E as EndpointMode, T as ToolWithHandler, a as EffectHandlerContext, M as ManifestEffectMetamodelSpec, R as ResolvedEffectBehaviors, S as SessionHeapEntry, b as SessionHeapList, c as SessionHeapSnapshot, P as Prompt } from './client-DLGC0mJk.js';
2
+ export { b1 as APIError, A as AccessTokenProvider, u as Assignment, v as AssignmentListResponse, K as Build, N as BuildListResponse, B as BuildPolicy, J as BuildStatus, C as ConnectOptions, m as ConversationSessionInfo, y as CreateEnvironmentData, s as CreatePermissionProfileData, o as CreateSandboxData, aw as DefineRelationshipOptions, b2 as DeleteResponse, D as DomainState, a8 as EffectHandler, a5 as EffectInfo, a0 as EffectInvocationMetadata, $ as EffectInvocationMode, a1 as EffectSchema, a2 as EffectWithHandler, a7 as EffectsChangedEvent, d as Environment, x as EnvironmentData, z as EnvironmentListResponse, aG as EnvironmentRecordImportSummary, G as Granular, j as GranularAuth, i as GranularOptions, b0 as GraphQLResult, a9 as InstanceEffectHandler, I as InstanceToolHandler, ah as Job, ae as JobFeedbackInput, ad as JobFeedbackMetadata, af as JobFeedbackRecord, ab as JobFeedbackSentiment, ac as JobFeedbackToolCall, aa as JobStatus, ag as JobSubmitResult, F as Manifest, aS as ManifestApprovalRequiredSpec, a$ as ManifestContent, aQ as ManifestDryRunSpec, aV as ManifestEffectDeclaration, aU as ManifestEffectSchema, aJ as ManifestEnumRuleSpec, aX as ManifestEventStreamDef, aW as ManifestEventTypeDef, aK as ManifestFilterBySpec, aZ as ManifestImport, H as ManifestListResponse, aY as ManifestOperation, aP as ManifestPostConditionSpec, aH as ManifestPropertySpec, aT as ManifestRelationshipDef, aR as ManifestReverseSpec, aO as ManifestStateMachineSpec, aM as ManifestStateMachineStateSpec, aN as ManifestStateMachineTransitionSpec, aI as ManifestValidationOperator, aL as ManifestValidationRuleSpec, a_ as ManifestVolume, au as ModelRef, r as PermissionProfile, t as PermissionProfileListResponse, q as PermissionRules, a3 as PublishEffectsResult, g as PublishToolsResult, ao as RPCRequest, ar as RPCRequestFromServer, ap as RPCResponse, aF as RecordImport, aE as RecordImportItem, aC as RecordImportItemStatus, aD as RecordImportStats, aB as RecordImportStatus, ax as RecordObjectOptions, ay as RecordObjectResult, az as RecordObjectsChunkInfo, aA as RecordObjectsOptions, k as RecordUserOptions, av as RelationshipInfo, _ as ResolvedEffectApprovalRequired, Y as ResolvedEffectDryRun, X as ResolvedEffectPostCondition, Z as ResolvedEffectReverse, n as Sandbox, p as SandboxListResponse, Q as SemanticVersionDiff, O as SemanticVersionDiffEntry, e as Session, ai as SessionHeapFieldType, aj as SessionHeapFieldValue, ak as SessionHeapVariable, b3 as StreamEvent, b5 as StreamStats, b4 as StreamSubscription, l as Subject, aq as SyncMessage, h as ToolHandler, a4 as ToolInfo, as as ToolInvokeParams, at as ToolResultParams, f as ToolSchema, a6 as ToolsChangedEvent, U as User, L as Version, w as VersionTag, V as VersionTracking, W as WSClient, an as WSClientOptions, al as WSDisconnectInfo, am as WSReconnectErrorInfo } from './client-DLGC0mJk.js';
3
3
  export { BuildGranularAgentSystemPromptInput, GeneratedJobCodeIssue, GranularAgentExecutionCheckpoint, GranularAgentHeapSummaryOptions, GranularAgentSessionContext, GranularAgentToolInfo, GranularAgentWorkflowFocus, HarnessContinuationDecision, HarnessControllerBudgets, HarnessProjectionOptions, HarnessPromptLike, HarnessVerifierSnapshot, HarnessVerifierSnapshotInput, buildContinuationInstruction, buildGranularAgentCheckpointBlock, buildGranularAgentDomainBlock, buildGranularAgentHeapBlock, buildGranularAgentLoopBlock, buildGranularAgentSessionBlock, buildGranularAgentSystemPrompt, buildGranularAgentToolBlock, buildGranularAgentWorkflowBlock, createHarnessVerifierSnapshot, evaluateContinuation, getCurrentClosureId, getExclusivePromptTarget, hasOpenPrompt, projectHeapSummary, projectLoopSummary, projectWorkflowFocus, projectWorkflowSummary, reviewGeneratedJobCode } from './agent-harness.js';
4
4
  import '@automerge/automerge';
5
5
  import '@automerge/automerge/slim';
6
6
 
7
+ declare function isLocalApiUrl(url: string): boolean;
8
+ /**
9
+ * Local dev + `sk_*` (WorkOS org key in env): map to the local gn_sk e2e key by default so every
10
+ * request (HTTP + WebSocket) uses the same tenant as the v2 UI on localhost (`default`). Without
11
+ * this, the SDK passes `sk_*` through → gateway resolves org_… while the UI still uses gn_sk →
12
+ * you only see old default-tenant sandboxes and new ingest data looks “missing”.
13
+ *
14
+ * - `GRANULAR_LOCAL_API_KEY` — explicit key to use instead (e.g. another gn_sk).
15
+ * - `GRANULAR_DISABLE_LOCAL_API_KEY_FALLBACK=1` — do not swap; send the real `sk_*` (org tenant +
16
+ * WorkOS validation on the gateway). Use when the UI is also on that org (e.g. session auth +
17
+ * NEXT_PUBLIC_DISABLE_LOCAL_API_KEY_FALLBACK on the app).
18
+ */
19
+ declare function resolveAuthTokenForApiUrl(authToken: string, apiUrl: string): string;
20
+ declare function resolveApiUrl(explicitApiUrl?: string, mode?: EndpointMode): string;
21
+
7
22
  type EffectRuntimeRequest = {
8
23
  effectKey: string;
9
24
  effectName: string;
@@ -41,4 +56,4 @@ declare function normalizePromptType(raw: Record<string, unknown> | null | undef
41
56
  declare function normalizePrompt(rawValue: unknown): Prompt | null;
42
57
  declare function resolvePromptAnswer(prompt: Prompt | undefined, answer: unknown): unknown;
43
58
 
44
- export { EffectHandlerContext, type JobPresentation, ManifestEffectMetamodelSpec, Prompt, ResolvedEffectBehaviors, SessionHeapEntry, SessionHeapList, SessionHeapSnapshot, ToolWithHandler, extractPromptTokens, invokeRegisteredEffect, normalizeEffectBehaviors, normalizePrompt, normalizePromptText, normalizePromptType, resolveJobPresentation, resolvePromptAnswer, scorePromptChoiceMatch };
59
+ export { EffectHandlerContext, EndpointMode, type JobPresentation, ManifestEffectMetamodelSpec, Prompt, ResolvedEffectBehaviors, SessionHeapEntry, SessionHeapList, SessionHeapSnapshot, ToolWithHandler, extractPromptTokens, invokeRegisteredEffect, isLocalApiUrl, normalizeEffectBehaviors, normalizePrompt, normalizePromptText, normalizePromptType, resolveApiUrl, resolveAuthTokenForApiUrl, resolveJobPresentation, resolvePromptAnswer, scorePromptChoiceMatch };
package/dist/index.js CHANGED
@@ -4682,10 +4682,15 @@ var Session = class {
4682
4682
  * ```typescript
4683
4683
  * import { Author, Book, global_search } from './sandbox-tools';
4684
4684
  *
4685
- * const authors = await Author.list({ limit: 10, saveAs: 'recent_authors' });
4685
+ * const totalAuthors = await Author.count();
4686
+ * const firstAuthorsPage = await Author.page({ page: 1, perPage: 10, saveAs: 'recent_authors' });
4687
+ * const authors = firstAuthorsPage.items;
4686
4688
  * const tolkien = await Author.get({ path: 'author_tolkien' });
4687
4689
  * const bio = await tolkien.get_bio({ detailed: true });
4688
4690
  * const books = await tolkien.get_books();
4691
+ * for await (const author of Author.iterate({ perPage: 100, maxItems: 500 })) {
4692
+ * console.log(author.id);
4693
+ * }
4689
4694
  * ```
4690
4695
  *
4691
4696
  * Effect calls (instance methods, static methods, global functions) trigger
@@ -11243,9 +11248,9 @@ var STANDARD_MODULES_OPERATIONS = [
11243
11248
  { create: "class", extends: "entity", has: {} },
11244
11249
  { create: "user", extends: "entity", has: { email: { value: void 0 }, firstName: { value: void 0 }, lastName: { value: void 0 } } },
11245
11250
  { create: "company", extends: "entity", has: { name: { value: void 0 }, website: { value: void 0 } } },
11246
- { create: "string", has: { value: { value: void 0 } } },
11247
- { create: "number", has: { value: { value: 0 } } },
11248
- { create: "boolean", has: { value: { value: false } } },
11251
+ { create: "string", has: {} },
11252
+ { create: "number", has: {} },
11253
+ { create: "boolean", has: {} },
11249
11254
  { create: "tool_parameter", has: { name: { value: void 0 }, type: { value: "string" }, description: { value: void 0 }, required: { value: false } } }
11250
11255
  ];
11251
11256
  var BUILTIN_MODULES = {
@@ -11255,6 +11260,8 @@ var DEFAULT_DIRECT_RECORD_OBJECTS_REQUEST_BATCH_SIZE = 100;
11255
11260
  var MAX_RECORD_OBJECTS_CONCURRENCY = 16;
11256
11261
  var DEFAULT_DIRECT_RECORD_OBJECTS_RETRY_COUNT = 3;
11257
11262
  var DEFAULT_DIRECT_RECORD_OBJECTS_RETRY_DELAY_MS = 1e3;
11263
+ var LOCAL_CONTROL_REQUEST_RETRY_COUNT = 4;
11264
+ var LOCAL_CONTROL_REQUEST_RETRY_DELAY_MS = 500;
11258
11265
  function planRecordObjectsChunks(records, batchSize) {
11259
11266
  const total = records.length;
11260
11267
  const size = Math.max(1, Math.min(batchSize, total));
@@ -11269,6 +11276,17 @@ function planRecordObjectsChunks(records, batchSize) {
11269
11276
  function sleep(ms) {
11270
11277
  return new Promise((resolve) => setTimeout(resolve, ms));
11271
11278
  }
11279
+ function isLocalControlUrl(url) {
11280
+ try {
11281
+ const parsed = new URL(url);
11282
+ return parsed.hostname === "127.0.0.1" || parsed.hostname === "localhost" || parsed.hostname === "::1";
11283
+ } catch {
11284
+ return false;
11285
+ }
11286
+ }
11287
+ function isRetryableLocalWorkerRestart(status, body, url) {
11288
+ return isLocalControlUrl(url) && (status === 503 && body.includes("Your worker restarted mid-request") || status === 500 && body.includes("Network connection lost"));
11289
+ }
11272
11290
  function isRetryableRecordObjectsError(error) {
11273
11291
  const message = error instanceof Error ? error.message : String(error);
11274
11292
  return /worker restarted mid-request|econnreset|network|socket connection was closed unexpectedly|timed out/i.test(message);
@@ -13292,23 +13310,36 @@ var Granular = class _Granular {
13292
13310
  if (this.debugHttp) {
13293
13311
  console.log(`[SDK] Requesting: ${url}`);
13294
13312
  }
13295
- const response = await fetch(url, {
13296
- ...options,
13297
- headers: {
13298
- "Authorization": `Bearer ${this.apiKey}`,
13299
- "Content-Type": "application/json",
13300
- "Connection": "close",
13301
- ...options.headers
13313
+ for (let attempt = 1; attempt <= LOCAL_CONTROL_REQUEST_RETRY_COUNT; attempt += 1) {
13314
+ const response = await fetch(url, {
13315
+ ...options,
13316
+ headers: {
13317
+ "Authorization": `Bearer ${this.apiKey}`,
13318
+ "Content-Type": "application/json",
13319
+ "Connection": "close",
13320
+ ...options.headers
13321
+ }
13322
+ });
13323
+ if (response.ok) {
13324
+ if (response.status === 204) {
13325
+ return { deleted: true };
13326
+ }
13327
+ return response.json();
13302
13328
  }
13303
- });
13304
- if (!response.ok) {
13305
13329
  const errorText = await response.text();
13330
+ const retryable = isRetryableLocalWorkerRestart(response.status, errorText, url);
13331
+ if (retryable && attempt < LOCAL_CONTROL_REQUEST_RETRY_COUNT) {
13332
+ if (this.debugHttp) {
13333
+ console.warn(
13334
+ `[SDK] Retrying local control request after worker restart (${attempt}/${LOCAL_CONTROL_REQUEST_RETRY_COUNT - 1} retries used): ${url}`
13335
+ );
13336
+ }
13337
+ await sleep(LOCAL_CONTROL_REQUEST_RETRY_DELAY_MS * attempt);
13338
+ continue;
13339
+ }
13306
13340
  throw new Error(`Granular API Error (${response.status}): ${errorText}`);
13307
13341
  }
13308
- if (response.status === 204) {
13309
- return { deleted: true };
13310
- }
13311
- return response.json();
13342
+ throw new Error(`Granular API Error: exhausted retries for ${url}`);
13312
13343
  }
13313
13344
  };
13314
13345
 
@@ -14234,7 +14265,10 @@ ${loopBlock}
14234
14265
  - Only use classes, methods, and parameter shapes that are explicitly declared in those typedefs.
14235
14266
  - Never invent helper methods such as \`find(...)\` or unsupported parameters such as \`id\` when the typedefs require \`path\`.
14236
14267
  - Use \`ClassName.get({ path })\` only when you already know an object's graph path.
14237
- - Use \`ClassName.list({ limit, saveAs })\` to load typed lists and persist reusable named lists in the heap.
14268
+ - Use \`ClassName.count()\` when you only need a total.
14269
+ - Use \`ClassName.page({ page, perPage, saveAs })\` when you need both records and pagination metadata like \`totalCount\` or \`hasMore\`.
14270
+ - Use \`ClassName.list({ page, perPage, saveAs })\` to load one typed page of records. \`limit\` is only a legacy alias for \`perPage\`.
14271
+ - Use \`for await (const item of ClassName.iterate({ perPage, maxItems }))\` for large batch jobs so you do not materialize the whole result set at once.
14238
14272
  - Instance methods: \`await instance.method_name(params)\`.
14239
14273
  - Static methods: \`await ClassName.static_method(params)\`.
14240
14274
  - Global effects: \`await effect_name(params)\`.
@@ -14246,7 +14280,7 @@ ${loopBlock}
14246
14280
  - Status fields are free-form operational strings, not strict enums. Normalize spelling mentally and do not rely on brittle hard-coded sets that miss variants like \`in-progress\`, \`in_progress\`, \`awaiting-part\`, or \`approval-submitted\`.
14247
14281
  - Do not discard a case, work order, part request, or shipment only because its status string does not match your preferred "open" spelling. If the record is otherwise the clear match, inspect it.
14248
14282
  - Reuse \`heap.getVar(name)\`, \`heap.setVar(name, value)\`, and \`heap.deleteVar(name)\` only when it clearly helps the next step. Do not mirror data into the heap just for completeness.
14249
- - Prefer \`heap.setVar(name, value)\` for scalars or one selected instance. Prefer \`ClassName.list({ saveAs })\` for lists instead of \`heap.setVar(name, array)\`.
14283
+ - Prefer \`heap.setVar(name, value)\` for scalars or one selected instance. Prefer \`ClassName.list({ page, perPage, saveAs })\` for reusable list pages instead of \`heap.setVar(name, array)\`.
14250
14284
  - Never write an empty array into the heap. If a filtered list is empty, keep it local or clear the previous heap value with \`heap.deleteVar(name)\`.
14251
14285
  - Prefer heap-backed state that represents the current choice or recommendation. Avoid storing extra scalar bookkeeping unless it is needed for the next concrete step.
14252
14286
  - Only store true sandbox instances, typed lists of sandbox instances, or scalars in the heap. Results returned by static effects like availability/search helpers are often plain JSON, not sandbox instances.
@@ -14502,6 +14536,7 @@ exports.getCurrentClosureId = getCurrentClosureId;
14502
14536
  exports.getExclusivePromptTarget = getExclusivePromptTarget;
14503
14537
  exports.hasOpenPrompt = hasOpenPrompt;
14504
14538
  exports.invokeRegisteredEffect = invokeRegisteredEffect;
14539
+ exports.isLocalApiUrl = isLocalApiUrl;
14505
14540
  exports.normalizeEffectBehaviors = normalizeEffectBehaviors;
14506
14541
  exports.normalizePrompt = normalizePrompt;
14507
14542
  exports.normalizePromptText = normalizePromptText;
@@ -14510,6 +14545,8 @@ exports.projectHeapSummary = projectHeapSummary;
14510
14545
  exports.projectLoopSummary = projectLoopSummary;
14511
14546
  exports.projectWorkflowFocus = projectWorkflowFocus;
14512
14547
  exports.projectWorkflowSummary = projectWorkflowSummary;
14548
+ exports.resolveApiUrl = resolveApiUrl;
14549
+ exports.resolveAuthTokenForApiUrl = resolveAuthTokenForApiUrl;
14513
14550
  exports.resolveJobPresentation = resolveJobPresentation;
14514
14551
  exports.resolvePromptAnswer = resolvePromptAnswer;
14515
14552
  exports.reviewGeneratedJobCode = reviewGeneratedJobCode;