@granular-software/sdk 0.4.75 → 0.4.76

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/index.mjs CHANGED
@@ -3990,6 +3990,34 @@ var init_wrapper = __esm({
3990
3990
  }
3991
3991
  });
3992
3992
 
3993
+ // src/api-error.ts
3994
+ var GranularApiError = class extends Error {
3995
+ constructor(message, status, path, details = {}) {
3996
+ super(message);
3997
+ this.status = status;
3998
+ this.path = path;
3999
+ this.name = "GranularApiError";
4000
+ this.idempotencyKey = details.idempotencyKey;
4001
+ let body = details.body;
4002
+ if (typeof body === "string") {
4003
+ try {
4004
+ body = JSON.parse(body);
4005
+ } catch {
4006
+ }
4007
+ }
4008
+ this.body = body;
4009
+ const payload = body && typeof body === "object" ? body : void 0;
4010
+ const firstError = Array.isArray(payload?.errors) ? payload.errors[0] : void 0;
4011
+ const extensions = firstError && typeof firstError === "object" ? firstError.extensions : void 0;
4012
+ this.code = [payload?.code, extensions?.code, firstError?.code].find(
4013
+ (value) => typeof value === "string" && value.length > 0
4014
+ ) ?? `HTTP_${status}`;
4015
+ }
4016
+ code;
4017
+ body;
4018
+ idempotencyKey;
4019
+ };
4020
+
3993
4021
  // ../../node_modules/zod/v3/external.js
3994
4022
  var external_exports = {};
3995
4023
  __export(external_exports, {
@@ -18041,8 +18069,12 @@ var Environment = class _Environment {
18041
18069
  }
18042
18070
  });
18043
18071
  if (!response.ok) {
18044
- throw new Error(
18045
- `Control Plane API Error (${response.status}): ${await response.text()}`
18072
+ const errorText = await response.text();
18073
+ throw new GranularApiError(
18074
+ `Control Plane API Error (${response.status}): ${errorText}`,
18075
+ response.status,
18076
+ path,
18077
+ { body: errorText }
18046
18078
  );
18047
18079
  }
18048
18080
  return response.json();
@@ -18099,12 +18131,12 @@ var Environment = class _Environment {
18099
18131
  * );
18100
18132
  * ```
18101
18133
  */
18102
- async graphql(query, variables) {
18134
+ async graphql(query, variables, options) {
18103
18135
  const authToken = await this.resolveAuthToken();
18104
18136
  if (this._beforeMutationSend && isGraphQLMutationDocument(query)) {
18105
18137
  this._beforeMutationSend?.();
18106
18138
  }
18107
- const idempotencyKey = this._graphqlIdempotencyKey?.(query, variables);
18139
+ const idempotencyKey = options?.idempotencyKey || this._graphqlIdempotencyKey?.(query, variables) || `gr1:${Date.now()}:${crypto.randomUUID()}`;
18108
18140
  const response = await fetch(this._apiEndpoint, {
18109
18141
  method: "POST",
18110
18142
  headers: {
@@ -18115,12 +18147,18 @@ var Environment = class _Environment {
18115
18147
  body: JSON.stringify({
18116
18148
  environmentId: this.environmentId,
18117
18149
  query,
18118
- variables
18150
+ variables,
18151
+ ...options?.readPreference ? { readPreference: options.readPreference } : {}
18119
18152
  })
18120
18153
  });
18121
18154
  if (!response.ok) {
18122
18155
  const errorText = await response.text();
18123
- throw new Error(`GraphQL API Error (${response.status}): ${errorText}`);
18156
+ throw new GranularApiError(
18157
+ `GraphQL API Error (${response.status}): ${errorText}`,
18158
+ response.status,
18159
+ this._apiEndpoint,
18160
+ { body: errorText, idempotencyKey }
18161
+ );
18124
18162
  }
18125
18163
  return response.json();
18126
18164
  }
@@ -20272,7 +20310,7 @@ var Granular = class _Granular {
20272
20310
  const outdatedMatches = this.sortEnvironmentsByRecency(
20273
20311
  userEnvironments.filter((environment2) => environment2.tagId === tag.tagId)
20274
20312
  );
20275
- if (outdatedMatches.length > 0 && options.createFreshIfOutdated !== true) {
20313
+ if (!resetKey && outdatedMatches.length > 0 && options.createFreshIfOutdated !== true) {
20276
20314
  requireMatchingEnvironmentProfile(outdatedMatches[0]);
20277
20315
  const environment2 = requireMatchingEnvironmentProfile(
20278
20316
  await activate(outdatedMatches[0])
@@ -21436,6 +21474,9 @@ var Granular = class _Granular {
21436
21474
  )
21437
21475
  );
21438
21476
  },
21477
+ /** Retire a settled environment and release its named slot. Ordinary
21478
+ * access is revoked; durable graph data and history are retained.
21479
+ * Mounted or unsettled environments reject with HTTP409. */
21439
21480
  delete: async (environmentId) => {
21440
21481
  return this.request(
21441
21482
  `/control/environments/${environmentId}`,
@@ -21650,7 +21691,12 @@ var Granular = class _Granular {
21650
21691
  await sleep(LOCAL_CONTROL_REQUEST_RETRY_DELAY_MS * attempt);
21651
21692
  continue;
21652
21693
  }
21653
- throw new Error(`Granular API Error (${response.status}): ${errorText}`);
21694
+ throw new GranularApiError(
21695
+ `Granular API Error (${response.status}): ${errorText}`,
21696
+ response.status,
21697
+ path,
21698
+ { body: errorText }
21699
+ );
21654
21700
  }
21655
21701
  throw new Error(`Granular API Error: exhausted retries for ${url}`);
21656
21702
  }
@@ -25169,6 +25215,6 @@ function selectArtifactSurface(artifact, context = {}) {
25169
25215
  };
25170
25216
  }
25171
25217
 
25172
- export { Environment, EnvironmentSession, GRANULAR_FEED_DIAGNOSTIC_EVENT, Granular, OPENAI_MODEL_PRICING_USD_PER_MILLION, OntologyHandle, Session, SessionFeedController, WSClient, artifactReviewedOperation, assertArtifactWorkflow, buildContinuationInstruction, buildContinuationInstructionFromTemplate, buildGranularAgentCheckpointBlock, buildGranularAgentDomainBlock, buildGranularAgentFileBlock, buildGranularAgentHeapBlock, buildGranularAgentLoopBlock, buildGranularAgentManualActionBlock, buildGranularAgentManualActionMemorySummary, buildGranularAgentReferentBlock, buildGranularAgentRuntimeImportsBlock, buildGranularAgentSessionBlock, buildGranularAgentSystemPrompt, buildGranularAgentSystemPromptFromTemplate, buildGranularAgentToolBlock, buildGranularAgentWorkflowBlock, buildOpenAISpendEventId, buildSessionTranscript, buildSessionTranscriptFromFeedItems, calculateOpenAITokenSpend, canInspectArtifactWorkflowNode, canonicalizeCommitValue, changedRecordSnapshots, consumeGranularReasoningOnlyChunk, consumeGranularReasoningTraceChunk, createFeedPublisher, createHarnessVerifierSnapshot, defineEffect, defineProjection, defineStateMachine, emitFeedDiagnostic, emitFeedDiagnosticToDefaultSink, emptyFeedSnapshot, environmentSetupProgressFromError, environmentSetupProgressFromResponse, evaluateContinuation, evaluateValidationRule, extractPromptTokens, getArtifactWorkflowNavigationLeaves, getArtifactWorkflowNavigationTarget, getArtifactWorkflowNodes, getCurrentArtifactWorkflowNode, getCurrentClosureId, getDefaultHarnessTemplateId, getExclusivePromptTarget, getOpenAIModelPricing, hasCanonicalSessionFeedActivation, hasOpenPrompt, hashHarnessTemplateValue, invokeRegisteredEffect, isArtifactWorkflowNodeNavigableLeaf, isArtifactWorkflowNodeTerminal, isCanonicalSessionFeedDocument, isGraphQLMutationDocument, isLocalApiUrl, listHarnessTemplates, mergeFeedItemsBySequence, normalizeEffectBehaviors, normalizeFeedDiagnostic, normalizeFeedDiagnosticKind, normalizeFeedPage, normalizeOpenAIUsage, normalizePrompt, normalizePromptChoiceOption, normalizePromptText, normalizePromptType, orderTransientFeedItems, pollEnvironmentSetup, projectArtifactWorkflow, projectConversationReferentFocus, projectConversationReferentSummary, projectHeapSummary, projectLoopSummary, projectRecordSnapshotMutation, projectSessionFileSummary, projectWorkflowFocus, projectWorkflowSummary, readSessionFeedSnapshot, recordOpenAIUsageSpend, renderContinuationInstructionFromTemplate, renderGranularAgentSystemPromptFromTemplate, requireArtifactWorkflow, requireArtifactWorkflowResult, resolveApiUrl, resolveAuthTokenForApiUrl, resolveHarnessTemplate, resolveJobPresentation, resolvePromptAnswer, reviewGeneratedJobCode, scorePromptChoiceMatch, selectArtifactSurface, stripGranularReasoningTrace, toGranularHttpBase, validateHarnessTemplateManifest, validateProjectionResult, validationRuleFailureMessage };
25218
+ export { Environment, EnvironmentSession, GRANULAR_FEED_DIAGNOSTIC_EVENT, Granular, GranularApiError, OPENAI_MODEL_PRICING_USD_PER_MILLION, OntologyHandle, Session, SessionFeedController, WSClient, artifactReviewedOperation, assertArtifactWorkflow, buildContinuationInstruction, buildContinuationInstructionFromTemplate, buildGranularAgentCheckpointBlock, buildGranularAgentDomainBlock, buildGranularAgentFileBlock, buildGranularAgentHeapBlock, buildGranularAgentLoopBlock, buildGranularAgentManualActionBlock, buildGranularAgentManualActionMemorySummary, buildGranularAgentReferentBlock, buildGranularAgentRuntimeImportsBlock, buildGranularAgentSessionBlock, buildGranularAgentSystemPrompt, buildGranularAgentSystemPromptFromTemplate, buildGranularAgentToolBlock, buildGranularAgentWorkflowBlock, buildOpenAISpendEventId, buildSessionTranscript, buildSessionTranscriptFromFeedItems, calculateOpenAITokenSpend, canInspectArtifactWorkflowNode, canonicalizeCommitValue, changedRecordSnapshots, consumeGranularReasoningOnlyChunk, consumeGranularReasoningTraceChunk, createFeedPublisher, createHarnessVerifierSnapshot, defineEffect, defineProjection, defineStateMachine, emitFeedDiagnostic, emitFeedDiagnosticToDefaultSink, emptyFeedSnapshot, environmentSetupProgressFromError, environmentSetupProgressFromResponse, evaluateContinuation, evaluateValidationRule, extractPromptTokens, getArtifactWorkflowNavigationLeaves, getArtifactWorkflowNavigationTarget, getArtifactWorkflowNodes, getCurrentArtifactWorkflowNode, getCurrentClosureId, getDefaultHarnessTemplateId, getExclusivePromptTarget, getOpenAIModelPricing, hasCanonicalSessionFeedActivation, hasOpenPrompt, hashHarnessTemplateValue, invokeRegisteredEffect, isArtifactWorkflowNodeNavigableLeaf, isArtifactWorkflowNodeTerminal, isCanonicalSessionFeedDocument, isGraphQLMutationDocument, isLocalApiUrl, listHarnessTemplates, mergeFeedItemsBySequence, normalizeEffectBehaviors, normalizeFeedDiagnostic, normalizeFeedDiagnosticKind, normalizeFeedPage, normalizeOpenAIUsage, normalizePrompt, normalizePromptChoiceOption, normalizePromptText, normalizePromptType, orderTransientFeedItems, pollEnvironmentSetup, projectArtifactWorkflow, projectConversationReferentFocus, projectConversationReferentSummary, projectHeapSummary, projectLoopSummary, projectRecordSnapshotMutation, projectSessionFileSummary, projectWorkflowFocus, projectWorkflowSummary, readSessionFeedSnapshot, recordOpenAIUsageSpend, renderContinuationInstructionFromTemplate, renderGranularAgentSystemPromptFromTemplate, requireArtifactWorkflow, requireArtifactWorkflowResult, resolveApiUrl, resolveAuthTokenForApiUrl, resolveHarnessTemplate, resolveJobPresentation, resolvePromptAnswer, reviewGeneratedJobCode, scorePromptChoiceMatch, selectArtifactSurface, stripGranularReasoningTrace, toGranularHttpBase, validateHarnessTemplateManifest, validateProjectionResult, validationRuleFailureMessage };
25173
25219
  //# sourceMappingURL=index.mjs.map
25174
25220
  //# sourceMappingURL=index.mjs.map