@caplets/core 0.29.0 → 0.29.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import { r as __exportAll } from "./rolldown-runtime-CE-6LUnI.js";
2
- import { Dt as loadConfigWithSources, en as DEFAULT_AUTH_DIR, fn as resolveCapletsRoot, hn as resolveProjectConfigPath, pn as resolveConfigPath, tn as DEFAULT_COMPLETION_CACHE_DIR } from "./service-CnVGCjpT.js";
2
+ import { Dt as loadConfigWithSources, en as DEFAULT_AUTH_DIR, fn as resolveCapletsRoot, hn as resolveProjectConfigPath, pn as resolveConfigPath, tn as DEFAULT_COMPLETION_CACHE_DIR } from "./service-DxPo2KUs.js";
3
3
  import { d as CapletsError } from "./validation-CWzd2gtn.js";
4
4
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
5
5
  import { dirname, join } from "node:path";
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { t as __commonJSMin } from "./rolldown-runtime-CE-6LUnI.js";
2
- import { $ as redactCodeModeLogText, $n as isJSONRPCRequest, $t as readTokenBundle, A as resolveRemoteMode, At as loadProjectConfig, Bn as ListResourceTemplatesRequestSchema, Bt as discoverCapletFiles, C as CapletsCloudClient, Cn as toJsonSchemaCompat, Ct as ServerRegistry, D as normalizeRemoteProfileHostUrl, Dn as CreateMessageResultSchema, Dt as loadConfigWithSources, E as isCapletsCloudUrl, En as CompleteRequestSchema, Et as loadConfig, F as resolveCapletsServer, Fn as InitializeRequestSchema, Ft as FileVaultStore, G as runCodeMode, Gn as McpError, Gt as markdownStructuredContent, H as codeModeRunInputSchema, Hn as ListRootsResultSchema, Ht as loadCapletFilesFromMap, I as nativeCapletPromptGuidance, In as InitializedNotificationSchema, It as VAULT_MAX_VALUE_BYTES, J as diagnoseCodeModeTypeScript, Jn as SetLevelRequestSchema, Jt as runOAuthFlow, K as CodeModeSessionManager, Kn as ReadResourceRequestSchema, Kt as refreshOAuthTokenBundle, L as nativeCapletToolDescription, Ln as JSONRPCMessageSchema, Lt as validateVaultKeyName, M as controlUrlForBase, Mn as EmptyResultSchema, Mt as vaultBootstrapResolver, N as isLoopbackHost, Nn as ErrorCode, Nt as vaultResolverForAuthDir, O as resolveCapletsRemote, On as CreateMessageResultWithToolsSchema, Ot as loadGlobalConfig, P as parseServerBaseUrl, Pn as GetPromptRequestSchema, Pt as vaultStoreForAuthDir, Q as CodeModeLogStore, Qn as isJSONRPCErrorResponse, Qt as isTokenBundleExpired, R as nativeCapletToolName, Rn as LATEST_PROTOCOL_VERSION, Rt as decryptVaultValue, S as buildProjectSyncManifest, Sn as mergeCapabilities, St as handleServerTool, T as hostedCloudWorkspaceFromRemoteUrl, Tn as CallToolResultSchema, Tt as GoogleDiscoveryManager, U as codeModeRunParamsSchema, Un as ListToolsRequestSchema, Ut as hasRenderableStructuredContent, Vn as ListResourcesRequestSchema, Vt as validateCapletFile, W as emptyCodeModeRunMeta, Wn as LoggingLevelSchema, Wt as markdownCallToolResultContent, X as listCodeModeCallableCaplets, Xn as assertCompleteRequestResourceTemplate, Xt as startOAuthFlow, Y as createCodeModeCapletsApi, Yn as assertCompleteRequestPrompt, Yt as startGenericOAuthFlow, Z as CodeModeJournalStore, Zn as isInitializeRequest, Zt as deleteTokenBundle, _ as attachErrorResponse, _n as serializeMessage, _t as rotateTelemetryIdentity, a as CloudAuthStore, an as defaultCacheBaseDir, ar as isSchemaOptional, at as version, b as invokeAttachExport, bn as AjvJsonSchemaValidator, bt as findProjectRoot, c as redactedCloudAuthStatus, cn as defaultStateBaseDir, cr as objectFromShape, ct as buildProductTelemetryEvent, d as projectBindingError, dn as defaultUpdateCheckStateDir, dt as maybePrintTelemetryNotice, en as DEFAULT_AUTH_DIR, er as isJSONRPCResultResponse, et as codeModeDeclarationHash, f as projectBindingRecovery, fn as resolveCapletsRoot, ft as resolveTelemetryState, g as CAPLETS_ATTACH_SESSION_HEADER, gn as ReadBuffer, gt as readTelemetryNotice, hn as resolveProjectConfigPath, ht as readTelemetryIdentity, i as createRemoteProfileStore, in as DEFAULT_UPDATE_CHECK_STATE_DIR, ir as getSchemaDescription, it as CapletsEngine, j as appendBasePath, jn as ElicitResultSchema, jt as parseConfig, k as resolveHostedCloudRemote, kn as CreateTaskResultSchema, kt as loadLocalOverlayConfigWithSources, l as PROJECT_BINDING_ERROR_CODES, ln as defaultTelemetryStateDir, lr as safeParse, lt as buildReliabilityTelemetryEvent, mn as resolveProjectCapletsRoot, mt as readTelemetryDeliveryHealth, n as resolveRemoteSelection, nn as DEFAULT_OBSERVED_OUTPUT_SHAPE_CACHE_DIR, nr as getObjectShape, nt as generateCodeModeRunToolDescription, o as cloudAuthPath, on as defaultConfigBaseDir, or as isZ4Schema, ot as createTelemetryDispatcher, p as CloudAuthClient, pn as resolveConfigPath, pt as deleteTelemetryIdentity, q as QuickJsCodeModeSandbox, qn as SUPPORTED_PROTOCOL_VERSIONS, qt as runGenericOAuthFlow, r as cloudCredentialsFromRemoteProfile, rn as DEFAULT_UPDATE_CHECK_CACHE_DIR, rr as getParseErrorMessage, rt as minifyCodeModeDeclarationText, s as migrateCredentials, sn as defaultConfigPath, sr as normalizeObjectSchema, st as TelemetryDebugSink, t as createNativeCapletsService, tr as getLiteralValue, tt as generateCodeModeDeclarations, u as ProjectBindingError, un as defaultUpdateCheckCacheDir, ur as safeParseAsync, ut as durationBucket, v as buildAttachProjection, vn as assertClientRequestTaskCapability, vt as resolveExposure, wn as CallToolRequestSchema, wt as capabilityDescription, x as invokeNativeAttachExport, xn as Protocol, xt as fingerprintProjectRoot, y as buildNativeAttachProjection, yn as assertToolsCallTaskCapability, yt as decodeDirectResourceUri, zn as ListPromptsRequestSchema, zt as encryptVaultValue } from "./service-CnVGCjpT.js";
2
+ import { $ as redactCodeModeLogText, $n as isJSONRPCRequest, $t as readTokenBundle, A as resolveRemoteMode, At as loadProjectConfig, Bn as ListResourceTemplatesRequestSchema, Bt as discoverCapletFiles, C as CapletsCloudClient, Cn as toJsonSchemaCompat, Ct as ServerRegistry, D as normalizeRemoteProfileHostUrl, Dn as CreateMessageResultSchema, Dt as loadConfigWithSources, E as isCapletsCloudUrl, En as CompleteRequestSchema, Et as loadConfig, F as resolveCapletsServer, Fn as InitializeRequestSchema, Ft as FileVaultStore, G as runCodeMode, Gn as McpError, Gt as markdownStructuredContent, H as codeModeRunInputSchema, Hn as ListRootsResultSchema, Ht as loadCapletFilesFromMap, I as nativeCapletPromptGuidance, In as InitializedNotificationSchema, It as VAULT_MAX_VALUE_BYTES, J as diagnoseCodeModeTypeScript, Jn as SetLevelRequestSchema, Jt as runOAuthFlow, K as CodeModeSessionManager, Kn as ReadResourceRequestSchema, Kt as refreshOAuthTokenBundle, L as nativeCapletToolDescription, Ln as JSONRPCMessageSchema, Lt as validateVaultKeyName, M as controlUrlForBase, Mn as EmptyResultSchema, Mt as vaultBootstrapResolver, N as isLoopbackHost, Nn as ErrorCode, Nt as vaultResolverForAuthDir, O as resolveCapletsRemote, On as CreateMessageResultWithToolsSchema, Ot as loadGlobalConfig, P as parseServerBaseUrl, Pn as GetPromptRequestSchema, Pt as vaultStoreForAuthDir, Q as CodeModeLogStore, Qn as isJSONRPCErrorResponse, Qt as isTokenBundleExpired, R as nativeCapletToolName, Rn as LATEST_PROTOCOL_VERSION, Rt as decryptVaultValue, S as buildProjectSyncManifest, Sn as mergeCapabilities, St as handleServerTool, T as hostedCloudWorkspaceFromRemoteUrl, Tn as CallToolResultSchema, Tt as GoogleDiscoveryManager, U as codeModeRunParamsSchema, Un as ListToolsRequestSchema, Ut as hasRenderableStructuredContent, Vn as ListResourcesRequestSchema, Vt as validateCapletFile, W as emptyCodeModeRunMeta, Wn as LoggingLevelSchema, Wt as markdownCallToolResultContent, X as listCodeModeCallableCaplets, Xn as assertCompleteRequestResourceTemplate, Xt as startOAuthFlow, Y as createCodeModeCapletsApi, Yn as assertCompleteRequestPrompt, Yt as startGenericOAuthFlow, Z as CodeModeJournalStore, Zn as isInitializeRequest, Zt as deleteTokenBundle, _ as attachErrorResponse, _n as serializeMessage, _t as rotateTelemetryIdentity, a as CloudAuthStore, an as defaultCacheBaseDir, ar as isSchemaOptional, at as version, b as invokeAttachExport, bn as AjvJsonSchemaValidator, bt as findProjectRoot, c as redactedCloudAuthStatus, cn as defaultStateBaseDir, cr as objectFromShape, ct as buildProductTelemetryEvent, d as projectBindingError, dn as defaultUpdateCheckStateDir, dt as maybePrintTelemetryNotice, en as DEFAULT_AUTH_DIR, er as isJSONRPCResultResponse, et as codeModeDeclarationHash, f as projectBindingRecovery, fn as resolveCapletsRoot, ft as resolveTelemetryState, g as CAPLETS_ATTACH_SESSION_HEADER, gn as ReadBuffer, gt as readTelemetryNotice, hn as resolveProjectConfigPath, ht as readTelemetryIdentity, i as createRemoteProfileStore, in as DEFAULT_UPDATE_CHECK_STATE_DIR, ir as getSchemaDescription, it as CapletsEngine, j as appendBasePath, jn as ElicitResultSchema, jt as parseConfig, k as resolveHostedCloudRemote, kn as CreateTaskResultSchema, kt as loadLocalOverlayConfigWithSources, l as PROJECT_BINDING_ERROR_CODES, ln as defaultTelemetryStateDir, lr as safeParse, lt as buildReliabilityTelemetryEvent, mn as resolveProjectCapletsRoot, mt as readTelemetryDeliveryHealth, n as resolveRemoteSelection, nn as DEFAULT_OBSERVED_OUTPUT_SHAPE_CACHE_DIR, nr as getObjectShape, nt as generateCodeModeRunToolDescription, o as cloudAuthPath, on as defaultConfigBaseDir, or as isZ4Schema, ot as createTelemetryDispatcher, p as CloudAuthClient, pn as resolveConfigPath, pt as deleteTelemetryIdentity, q as QuickJsCodeModeSandbox, qn as SUPPORTED_PROTOCOL_VERSIONS, qt as runGenericOAuthFlow, r as cloudCredentialsFromRemoteProfile, rn as DEFAULT_UPDATE_CHECK_CACHE_DIR, rr as getParseErrorMessage, rt as minifyCodeModeDeclarationText, s as migrateCredentials, sn as defaultConfigPath, sr as normalizeObjectSchema, st as TelemetryDebugSink, t as createNativeCapletsService, tr as getLiteralValue, tt as generateCodeModeDeclarations, u as ProjectBindingError, un as defaultUpdateCheckCacheDir, ur as safeParseAsync, ut as durationBucket, v as buildAttachProjection, vn as assertClientRequestTaskCapability, vt as resolveExposure, wn as CallToolRequestSchema, wt as capabilityDescription, x as invokeNativeAttachExport, xn as Protocol, xt as fingerprintProjectRoot, y as buildNativeAttachProjection, yn as assertToolsCallTaskCapability, yt as decodeDirectResourceUri, zn as ListPromptsRequestSchema, zt as encryptVaultValue } from "./service-DxPo2KUs.js";
3
3
  import { _ as record, b as unknown, d as literal, m as object, n as ZodOptional, o as array, p as number, r as _enum, s as boolean, v as string, x as url } from "./schemas-BoqMu4MG.js";
4
4
  import { a as SERVER_ID_PATTERN, d as CapletsError, m as toSafeError, p as redactSecrets$1, u as CAPLETS_ERROR_CODES } from "./validation-CWzd2gtn.js";
5
5
  import { generatedToolInputSchema, generatedToolInputSchemaForCaplet } from "./generated-tool-input-schema.js";
6
6
  import { f as observedOutputShapeKey, i as observeOutputShape, u as FileObservedOutputShapeStore } from "./observed-output-shapes-DuP7mJQf.js";
7
- import { a as formatCapletList, c as resolveCliConfigPaths, l as cliCommands$1, n as completionScript, o as formatConfigPaths, s as listCaplets, t as completeCliWords, u as completionShells } from "./completion-YRQc_o-I.js";
7
+ import { a as formatCapletList, c as resolveCliConfigPaths, l as cliCommands$1, n as completionScript, o as formatConfigPaths, s as listCaplets, t as completeCliWords, u as completionShells } from "./completion-CcNgCYzl.js";
8
8
  import { n as normalizeCapletSourcePath, t as FilesystemCapletSource } from "./filesystem-Kkg32TOJ.js";
9
9
  import { parseConfig as parseConfig$1 } from "./config-runtime.js";
10
10
  import fs, { accessSync, chmodSync, closeSync, constants, copyFileSync, cpSync, existsSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, watch, writeFileSync, writeSync } from "node:fs";
@@ -13451,9 +13451,10 @@ async function doctorJsonReport(options = {}) {
13451
13451
  authMode: remoteLogin.authenticated ? remoteLogin.kind === "cloud" ? "hosted_cloud" : "self_hosted_remote" : remote.configured || remoteLogin.configured ? "remote_login_required" : "unconfigured",
13452
13452
  selectedWorkspace: remoteLogin.selectedWorkspace ?? remote.workspace ?? null,
13453
13453
  webSocketUrl: remote.webSocketUrl,
13454
+ sessionSupport: remoteLogin.kind === "self-hosted" ? "unsupported" : "unknown",
13454
13455
  lease: null,
13455
13456
  lastUpgradeError: null,
13456
- recoveryCommand: remoteLogin.authenticated ? "caplets attach --once" : remote.configured || remoteLogin.configured ? `caplets remote login ${remoteLogin.hostUrl ?? "<url>"}` : "caplets remote login <url>"
13457
+ recoveryCommand: projectBindingRecovery$1(remoteLogin, remote)
13457
13458
  },
13458
13459
  sync: {
13459
13460
  state: options.syncStatus?.state ?? "idle",
@@ -13494,6 +13495,7 @@ async function formatDoctorReport(options = {}) {
13494
13495
  ` Auth mode: ${report.projectBinding.authMode}`,
13495
13496
  ` Selected Workspace: ${report.projectBinding.selectedWorkspace ?? "none"}`,
13496
13497
  ` Binding Session: ${report.projectBinding.state}`,
13498
+ ...report.projectBinding.sessionSupport !== "unknown" ? [` Session support: ${report.projectBinding.sessionSupport}`] : [],
13497
13499
  ` Recovery: ${report.projectBinding.recoveryCommand}`,
13498
13500
  "",
13499
13501
  "Project sync",
@@ -13568,6 +13570,11 @@ function vaultIssueFromWarning(message, path) {
13568
13570
  recoveryCommand
13569
13571
  };
13570
13572
  }
13573
+ function projectBindingRecovery$1(remoteLogin, remote) {
13574
+ if (remoteLogin.authenticated) return remoteLogin.kind === "self-hosted" ? "Self-hosted Project Binding sessions are not implemented by this runtime." : "caplets attach --once";
13575
+ if (remote.configured || remoteLogin.configured) return `caplets remote login ${remoteLogin.hostUrl ?? "<url>"}`;
13576
+ return "caplets remote login <url>";
13577
+ }
13571
13578
  async function resolveDaemonSection(env, options) {
13572
13579
  try {
13573
13580
  const status = await daemonStatus({
@@ -18792,17 +18799,16 @@ function createProgram(io = {}) {
18792
18799
  writeOut(await runSetup(integration, setupOptions));
18793
18800
  });
18794
18801
  program.command(cliCommands$1.doctor).description("Diagnose Caplets local, remote, and project-sync configuration.").option("--json", "print JSON output").action(async (options) => {
18802
+ const doctorOptions = {
18803
+ env,
18804
+ ...io.authDir ? { authDir: io.authDir } : {},
18805
+ ...io.daemon ? { daemon: io.daemon } : {}
18806
+ };
18795
18807
  if (options.json) {
18796
- writeOut(`${JSON.stringify(await doctorJsonReport({
18797
- env,
18798
- ...io.daemon ? { daemon: io.daemon } : {}
18799
- }), null, 2)}\n`);
18808
+ writeOut(`${JSON.stringify(await doctorJsonReport(doctorOptions), null, 2)}\n`);
18800
18809
  return;
18801
18810
  }
18802
- writeOut(await formatDoctorReport({
18803
- env,
18804
- ...io.daemon ? { daemon: io.daemon } : {}
18805
- }));
18811
+ writeOut(await formatDoctorReport(doctorOptions));
18806
18812
  });
18807
18813
  const vault = program.command(cliCommands$1.vault).description("Manage Caplets Vault values.");
18808
18814
  vault.command("set").description("Set a local/global Vault value.").argument("<name>", "Vault key name").option("-g, --global", "target the local/global Vault").option("--remote", "target the selected remote Vault").option("--force", "overwrite an existing Vault value").option("--grant <capletId>", "grant this key to a configured Caplet after setting it").option("--as <referenceName>", "reference name the Caplet uses in config").option("--json", "print JSON output").action(async (name, options) => {
package/dist/native.js CHANGED
@@ -1,4 +1,4 @@
1
- import { B as nativeCodeModeToolId, I as nativeCapletPromptGuidance, L as nativeCapletToolDescription, R as nativeCapletToolName, V as nativeCodeModeToolName, h as createSdkRemoteCapletsClient, m as RemoteNativeCapletsService, t as createNativeCapletsService, w as resolveNativeCapletsServiceOptions, z as nativeCapletsSystemGuidance } from "./service-CnVGCjpT.js";
1
+ import { B as nativeCodeModeToolId, I as nativeCapletPromptGuidance, L as nativeCapletToolDescription, R as nativeCapletToolName, V as nativeCodeModeToolName, h as createSdkRemoteCapletsClient, m as RemoteNativeCapletsService, t as createNativeCapletsService, w as resolveNativeCapletsServiceOptions, z as nativeCapletsSystemGuidance } from "./service-DxPo2KUs.js";
2
2
  import { generatedToolInputJsonSchema, generatedToolInputSchema } from "./generated-tool-input-schema.js";
3
3
  //#region src/native/process-cleanup.ts
4
4
  function registerNativeCapletsProcessCleanup(service, options = {}) {
@@ -64515,7 +64515,7 @@ async function defaultSentryFactory(dsn) {
64515
64515
  }
64516
64516
  //#endregion
64517
64517
  //#region package.json
64518
- var version = "0.29.0";
64518
+ var version = "0.29.1";
64519
64519
  //#endregion
64520
64520
  //#region src/telemetry/runtime.ts
64521
64521
  function createRuntimeTelemetryContext(options) {
@@ -64892,7 +64892,7 @@ var CapletsEngine = class {
64892
64892
  }
64893
64893
  }
64894
64894
  async completeCliWords(words) {
64895
- const { completeCliWords } = await import("./completion-YRQc_o-I.js").then((n) => n.r);
64895
+ const { completeCliWords } = await import("./completion-CcNgCYzl.js").then((n) => n.r);
64896
64896
  return await completeCliWords(words, {
64897
64897
  config: this.registry.config,
64898
64898
  managers: {
@@ -82265,6 +82265,8 @@ function downstreamResourceUri$1(capletId, uri) {
82265
82265
  //#endregion
82266
82266
  //#region src/native/remote.ts
82267
82267
  const ATTACH_SESSION_UNSUPPORTED_RETRY_MS = 6e4;
82268
+ const ATTACH_SESSION_CREATE_TIMEOUT_MS = 5e3;
82269
+ const ATTACH_SESSION_CREATE_TIMED_OUT = Symbol("attach session create timed out");
82268
82270
  function createSdkRemoteCapletsClient(options) {
82269
82271
  const listeners = /* @__PURE__ */ new Set();
82270
82272
  let manifest;
@@ -82295,10 +82297,15 @@ function createSdkRemoteCapletsClient(options) {
82295
82297
  if (attachSessionsUnsupportedUntil > Date.now()) return void 0;
82296
82298
  attachSessionsUnsupportedUntil = 0;
82297
82299
  if (attachSessionId) return attachSessionId;
82298
- if (attachSessionInFlight) return await attachSessionInFlight;
82300
+ if (attachSessionInFlight) {
82301
+ const inFlightSessionId = await attachSessionInFlight;
82302
+ return inFlightSessionId === ATTACH_SESSION_CREATE_TIMED_OUT ? void 0 : inFlightSessionId;
82303
+ }
82299
82304
  attachSessionInFlight = createAttachSession(runtimeOptions.url, runtimeOptions.requestInit, fetchFor(runtimeOptions), options.attachSessionMetadata);
82300
82305
  try {
82301
- attachSessionId = await attachSessionInFlight;
82306
+ const createdSessionId = await attachSessionInFlight;
82307
+ if (createdSessionId === ATTACH_SESSION_CREATE_TIMED_OUT) return;
82308
+ attachSessionId = createdSessionId;
82302
82309
  if (!attachSessionId) attachSessionsUnsupportedUntil = Date.now() + ATTACH_SESSION_UNSUPPORTED_RETRY_MS;
82303
82310
  return attachSessionId;
82304
82311
  } finally {
@@ -82419,8 +82426,8 @@ function createSdkRemoteCapletsClient(options) {
82419
82426
  eventsAbort?.abort();
82420
82427
  eventsAbort = void 0;
82421
82428
  listeners.clear();
82422
- const pendingSessionId = await attachSessionInFlight?.catch(() => void 0);
82423
- const sessionId = attachSessionId ?? pendingSessionId;
82429
+ const pendingSessionResult = await attachSessionInFlight?.catch(() => void 0);
82430
+ const sessionId = attachSessionId ?? (typeof pendingSessionResult === "string" ? pendingSessionResult : void 0);
82424
82431
  attachSessionId = void 0;
82425
82432
  if (sessionId) await (async () => {
82426
82433
  const runtimeOptions = await resolveRuntimeOptions();
@@ -82643,12 +82650,39 @@ async function fetchAttachManifest(attachUrl, requestInit, attachSessionId, fetc
82643
82650
  async function createAttachSession(attachUrl, requestInit, fetchImpl, metadata) {
82644
82651
  const headers = new Headers(requestInit?.headers);
82645
82652
  headers.set("content-type", "application/json");
82646
- const response = await fetchImpl(new URL("sessions", slashUrl(attachUrl)), {
82653
+ let timeout;
82654
+ let timedOut = false;
82655
+ const sessionUrl = new URL("sessions", slashUrl(attachUrl));
82656
+ const timeoutReached = new Promise((resolve) => {
82657
+ timeout = setTimeout(() => {
82658
+ timedOut = true;
82659
+ resolve(ATTACH_SESSION_CREATE_TIMED_OUT);
82660
+ }, ATTACH_SESSION_CREATE_TIMEOUT_MS);
82661
+ timeout.unref?.();
82662
+ });
82663
+ const fetchSession = fetchImpl(sessionUrl, {
82647
82664
  ...requestInit,
82648
82665
  method: "POST",
82649
82666
  headers,
82650
82667
  body: JSON.stringify(metadata)
82668
+ }).catch((error) => {
82669
+ if (timedOut) return void 0;
82670
+ throw error;
82651
82671
  });
82672
+ fetchSession.then(async (response) => {
82673
+ if (!timedOut || !response?.ok) return;
82674
+ const lateSessionId = await attachSessionIdFromResponse(response).catch(() => void 0);
82675
+ if (!lateSessionId) return;
82676
+ await closeAttachSession(attachUrl, requestInit, fetchImpl, lateSessionId).catch(() => void 0);
82677
+ }).catch(() => void 0);
82678
+ let response;
82679
+ try {
82680
+ response = await Promise.race([fetchSession, timeoutReached]);
82681
+ } finally {
82682
+ if (timeout) clearTimeout(timeout);
82683
+ }
82684
+ if (response === ATTACH_SESSION_CREATE_TIMED_OUT) return ATTACH_SESSION_CREATE_TIMED_OUT;
82685
+ if (!response) return void 0;
82652
82686
  if (!response.ok) {
82653
82687
  if (response.status === 404) return void 0;
82654
82688
  let payload;
@@ -82660,9 +82694,16 @@ async function createAttachSession(attachUrl, requestInit, fetchImpl, metadata)
82660
82694
  if (response.status === 400 && isAttachSessionProjectContextRejected(payload)) return;
82661
82695
  throw new CapletsError("SERVER_UNAVAILABLE", `Caplets attach session returned HTTP ${response.status}.`);
82662
82696
  }
82697
+ return await parseAttachSessionIdResponse(response);
82698
+ }
82699
+ async function parseAttachSessionIdResponse(response) {
82700
+ const sessionId = await attachSessionIdFromResponse(response);
82701
+ if (!sessionId) throw new CapletsError("SERVER_UNAVAILABLE", "Caplets attach session response was invalid.");
82702
+ return sessionId;
82703
+ }
82704
+ async function attachSessionIdFromResponse(response) {
82663
82705
  const payload = await response.json();
82664
- if (!isPlainObject(payload) || typeof payload.sessionId !== "string") throw new CapletsError("SERVER_UNAVAILABLE", "Caplets attach session response was invalid.");
82665
- return payload.sessionId;
82706
+ return isPlainObject(payload) && typeof payload.sessionId === "string" ? payload.sessionId : void 0;
82666
82707
  }
82667
82708
  async function closeAttachSession(attachUrl, requestInit, fetchImpl, attachSessionId) {
82668
82709
  await fetchImpl(new URL(`sessions/${encodeURIComponent(attachSessionId)}`, slashUrl(attachUrl)), {
@@ -83668,10 +83709,12 @@ var FileRemoteProfileStore = class {
83668
83709
  kind: "self-hosted",
83669
83710
  hostUrl: normalizeRemoteProfileHostUrl(input.hostUrl)
83670
83711
  });
83712
+ const snapshot = await this.withMutationLock(async () => this.selfHostedRefreshSnapshot(key, input));
83713
+ if (!snapshot || !snapshot.needsRefresh) return snapshot?.result;
83671
83714
  return await this.withRefreshLock(key, async () => {
83672
- const snapshot = await this.withMutationLock(async () => this.selfHostedRefreshSnapshot(key, input));
83673
- if (!snapshot || !snapshot.needsRefresh) return snapshot?.result;
83674
- const refreshed = await input.refresh(snapshot.result.status, snapshot.result.credential);
83715
+ const lockedSnapshot = await this.withMutationLock(async () => this.selfHostedRefreshSnapshot(key, input));
83716
+ if (!lockedSnapshot || !lockedSnapshot.needsRefresh) return lockedSnapshot?.result;
83717
+ const refreshed = await input.refresh(lockedSnapshot.result.status, lockedSnapshot.result.credential);
83675
83718
  return await this.withMutationLock(async () => {
83676
83719
  const current = await this.selfHostedRefreshSnapshot(key, input);
83677
83720
  if (!current || !current.needsRefresh) return current?.result;
@@ -84319,6 +84362,7 @@ function requiredHostedCloudAttachScopes() {
84319
84362
  //#endregion
84320
84363
  //#region src/native/service.ts
84321
84364
  const REMOTE_PROJECT_BINDING_FALLBACK_WARNING = "Remote project binding unavailable; using local Caplets only. Run caplets doctor for details.\n";
84365
+ const SELF_HOSTED_PROJECT_BINDING_UNSUPPORTED_MESSAGE = "Self-hosted Project Binding sessions are not implemented by this runtime.";
84322
84366
  let hasWarnedRemoteProjectBindingFallback = false;
84323
84367
  function createNativeCapletsService(options = {}) {
84324
84368
  const resolved = resolveNativeCapletsServiceOptions(options);
@@ -85230,6 +85274,7 @@ var CompositeNativeCapletsService = class {
85230
85274
  }
85231
85275
  startPresence() {
85232
85276
  this.presence?.start().catch((error) => {
85277
+ if (isUnsupportedProjectBinding(error)) return;
85233
85278
  writeErr(this.options, `Could not start upstream Project Binding: ${errorMessage(error)}\n`);
85234
85279
  });
85235
85280
  }
@@ -85468,7 +85513,7 @@ var RemoteProjectBindingSessionManager = class {
85468
85513
  }
85469
85514
  };
85470
85515
  function isUnsupportedProjectBinding(error) {
85471
- return isRecord(error) && error.code === "UNSUPPORTED_CAPABILITY";
85516
+ return isRecord(error) && error.code === "UNSUPPORTED_CAPABILITY" && error.message === SELF_HOSTED_PROJECT_BINDING_UNSUPPORTED_MESSAGE;
85472
85517
  }
85473
85518
  function projectBindingUrl(attachUrl, ...segments) {
85474
85519
  const url = new URL(attachUrl);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@caplets/core",
3
- "version": "0.29.0",
3
+ "version": "0.29.1",
4
4
  "description": "Core runtime library for Caplets Code Mode and progressive disclosure gateways.",
5
5
  "keywords": [
6
6
  "caplets",