@granular-software/sdk 0.4.75 → 0.4.77

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, {
@@ -15206,8 +15234,11 @@ import { ${tools[0]?.name || "example"} } from "@granular/actions/backend";
15206
15234
  this.emit("prompt:answered", { ...prompt, status: "answered" });
15207
15235
  return;
15208
15236
  }
15237
+ const previous = this.promptCache.get(prompt.id);
15209
15238
  this.promptCache.set(prompt.id, prompt);
15210
- this.emit("prompt", prompt);
15239
+ if (!previous || promptSnapshotFingerprint(previous) !== promptSnapshotFingerprint(prompt)) {
15240
+ this.emit("prompt", prompt);
15241
+ }
15211
15242
  };
15212
15243
  this.client.on("prompt", emitPrompt);
15213
15244
  this.client.on("prompt.request", emitPrompt);
@@ -18041,8 +18072,12 @@ var Environment = class _Environment {
18041
18072
  }
18042
18073
  });
18043
18074
  if (!response.ok) {
18044
- throw new Error(
18045
- `Control Plane API Error (${response.status}): ${await response.text()}`
18075
+ const errorText = await response.text();
18076
+ throw new GranularApiError(
18077
+ `Control Plane API Error (${response.status}): ${errorText}`,
18078
+ response.status,
18079
+ path,
18080
+ { body: errorText }
18046
18081
  );
18047
18082
  }
18048
18083
  return response.json();
@@ -18099,12 +18134,12 @@ var Environment = class _Environment {
18099
18134
  * );
18100
18135
  * ```
18101
18136
  */
18102
- async graphql(query, variables) {
18137
+ async graphql(query, variables, options) {
18103
18138
  const authToken = await this.resolveAuthToken();
18104
18139
  if (this._beforeMutationSend && isGraphQLMutationDocument(query)) {
18105
18140
  this._beforeMutationSend?.();
18106
18141
  }
18107
- const idempotencyKey = this._graphqlIdempotencyKey?.(query, variables);
18142
+ const idempotencyKey = options?.idempotencyKey || this._graphqlIdempotencyKey?.(query, variables) || `gr1:${Date.now()}:${crypto.randomUUID()}`;
18108
18143
  const response = await fetch(this._apiEndpoint, {
18109
18144
  method: "POST",
18110
18145
  headers: {
@@ -18115,12 +18150,18 @@ var Environment = class _Environment {
18115
18150
  body: JSON.stringify({
18116
18151
  environmentId: this.environmentId,
18117
18152
  query,
18118
- variables
18153
+ variables,
18154
+ ...options?.readPreference ? { readPreference: options.readPreference } : {}
18119
18155
  })
18120
18156
  });
18121
18157
  if (!response.ok) {
18122
18158
  const errorText = await response.text();
18123
- throw new Error(`GraphQL API Error (${response.status}): ${errorText}`);
18159
+ throw new GranularApiError(
18160
+ `GraphQL API Error (${response.status}): ${errorText}`,
18161
+ response.status,
18162
+ this._apiEndpoint,
18163
+ { body: errorText, idempotencyKey }
18164
+ );
18124
18165
  }
18125
18166
  return response.json();
18126
18167
  }
@@ -20272,7 +20313,7 @@ var Granular = class _Granular {
20272
20313
  const outdatedMatches = this.sortEnvironmentsByRecency(
20273
20314
  userEnvironments.filter((environment2) => environment2.tagId === tag.tagId)
20274
20315
  );
20275
- if (outdatedMatches.length > 0 && options.createFreshIfOutdated !== true) {
20316
+ if (!resetKey && outdatedMatches.length > 0 && options.createFreshIfOutdated !== true) {
20276
20317
  requireMatchingEnvironmentProfile(outdatedMatches[0]);
20277
20318
  const environment2 = requireMatchingEnvironmentProfile(
20278
20319
  await activate(outdatedMatches[0])
@@ -21436,6 +21477,9 @@ var Granular = class _Granular {
21436
21477
  )
21437
21478
  );
21438
21479
  },
21480
+ /** Retire a settled environment and release its named slot. Ordinary
21481
+ * access is revoked; durable graph data and history are retained.
21482
+ * Mounted or unsettled environments reject with HTTP409. */
21439
21483
  delete: async (environmentId) => {
21440
21484
  return this.request(
21441
21485
  `/control/environments/${environmentId}`,
@@ -21650,7 +21694,12 @@ var Granular = class _Granular {
21650
21694
  await sleep(LOCAL_CONTROL_REQUEST_RETRY_DELAY_MS * attempt);
21651
21695
  continue;
21652
21696
  }
21653
- throw new Error(`Granular API Error (${response.status}): ${errorText}`);
21697
+ throw new GranularApiError(
21698
+ `Granular API Error (${response.status}): ${errorText}`,
21699
+ response.status,
21700
+ path,
21701
+ { body: errorText }
21702
+ );
21654
21703
  }
21655
21704
  throw new Error(`Granular API Error: exhausted retries for ${url}`);
21656
21705
  }
@@ -25169,6 +25218,6 @@ function selectArtifactSurface(artifact, context = {}) {
25169
25218
  };
25170
25219
  }
25171
25220
 
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 };
25221
+ 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
25222
  //# sourceMappingURL=index.mjs.map
25174
25223
  //# sourceMappingURL=index.mjs.map