openmeld 0.3.220 → 0.3.221
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/{add-me-membership-GzOoooxS.js → add-me-membership-DpckwGof.js} +2 -2
- package/dist/{add-me-membership-GzOoooxS.js.map → add-me-membership-DpckwGof.js.map} +1 -1
- package/dist/{agents-C8ATowD6.js → agents-2TzCubpV.js} +7 -7
- package/dist/{agents-C8ATowD6.js.map → agents-2TzCubpV.js.map} +1 -1
- package/dist/{api-client-foundation-Dv2OE-Pi.js → api-client-foundation-CGImd4c8.js} +1 -1
- package/dist/{api-client-foundation-CDlVc0zT.js → api-client-foundation-D-Cb6EVg.js} +2 -2
- package/dist/{api-client-foundation-CDlVc0zT.js.map → api-client-foundation-D-Cb6EVg.js.map} +1 -1
- package/dist/{cli-space-api-skevaFSC.js → cli-space-api-B2l1xMPn.js} +4 -4
- package/dist/{cli-space-api-skevaFSC.js.map → cli-space-api-B2l1xMPn.js.map} +1 -1
- package/dist/{command-CmlgCUU2.js → command-MlrjQYq5.js} +11 -11
- package/dist/{command-CmlgCUU2.js.map → command-MlrjQYq5.js.map} +1 -1
- package/dist/{computer-connection-review-Bjyn3UbU.js → computer-connection-review-mO6vn3C3.js} +2 -2
- package/dist/{computer-connection-review-Bjyn3UbU.js.map → computer-connection-review-mO6vn3C3.js.map} +1 -1
- package/dist/{computer-disconnect-CRWsoihu.js → computer-disconnect-CLtQwKDS.js} +3 -3
- package/dist/{computer-disconnect-CRWsoihu.js.map → computer-disconnect-CLtQwKDS.js.map} +1 -1
- package/dist/{computer-setup-continuation-D0kC6-l2.js → computer-setup-continuation-PVwPXc5i.js} +2 -2
- package/dist/{computer-setup-continuation-D0kC6-l2.js.map → computer-setup-continuation-PVwPXc5i.js.map} +1 -1
- package/dist/{daemon-frame-transport-E-H3DjWA.js → daemon-frame-transport-D-4StENt.js} +3 -3
- package/dist/{daemon-frame-transport-E-H3DjWA.js.map → daemon-frame-transport-D-4StENt.js.map} +1 -1
- package/dist/{daemon-lifecycle-journal-DDrWgEzN.js → daemon-lifecycle-journal-DcrVY0xb.js} +2 -2
- package/dist/{daemon-lifecycle-journal-DDrWgEzN.js.map → daemon-lifecycle-journal-DcrVY0xb.js.map} +1 -1
- package/dist/{daemon-service-runtime-M-kfrWro.js → daemon-service-runtime-Kr6Bs2J2.js} +2 -2
- package/dist/{daemon-service-runtime-M-kfrWro.js.map → daemon-service-runtime-Kr6Bs2J2.js.map} +1 -1
- package/dist/{daemon-service-update-coordinator-Clqxj3A1.js → daemon-service-update-coordinator-RJO997me.js} +6 -6
- package/dist/{daemon-service-update-coordinator-Clqxj3A1.js.map → daemon-service-update-coordinator-RJO997me.js.map} +1 -1
- package/dist/{dist-kTVDInkZ.js → dist-B6VsppM7.js} +1 -1
- package/dist/{dist-YPzkhLLp.js → dist-BewA9srP.js} +17 -3
- package/dist/dist-BewA9srP.js.map +1 -0
- package/dist/{elapsed-time-4PuBjDUi.js → elapsed-time-Cw6b9rYy.js} +4 -4
- package/dist/{elapsed-time-4PuBjDUi.js.map → elapsed-time-Cw6b9rYy.js.map} +1 -1
- package/dist/{entry-q_QHht2-.js → entry-BE8uqbkD.js} +2 -2
- package/dist/{entry-q_QHht2-.js.map → entry-BE8uqbkD.js.map} +1 -1
- package/dist/{installation-inventory-CuPmLaLZ.js → installation-inventory-Dwn8FoKT.js} +3 -3
- package/dist/{installation-inventory-CuPmLaLZ.js.map → installation-inventory-Dwn8FoKT.js.map} +1 -1
- package/dist/{installer-mSB-Oiwx.js → installer-CsQ4vNjT.js} +2 -2
- package/dist/{installer-mSB-Oiwx.js.map → installer-CsQ4vNjT.js.map} +1 -1
- package/dist/{openmeld-CFXnmBH6.js → openmeld-Tkp17vPg.js} +24 -24
- package/dist/{openmeld-CFXnmBH6.js.map → openmeld-Tkp17vPg.js.map} +1 -1
- package/dist/{openmeld-maintenance-worker-K-nEox6k.js → openmeld-maintenance-worker-C1J_ISOh.js} +9 -9
- package/dist/{openmeld-maintenance-worker-K-nEox6k.js.map → openmeld-maintenance-worker-C1J_ISOh.js.map} +1 -1
- package/dist/{openmeld-tools-update-join-CN4mjp4-.js → openmeld-tools-update-join-ZLpRTHO3.js} +4 -4
- package/dist/{openmeld-tools-update-join-CN4mjp4-.js.map → openmeld-tools-update-join-ZLpRTHO3.js.map} +1 -1
- package/dist/openmeld.js +4 -4
- package/dist/{prepare-provider-runtime-iA3g-8MS.js → prepare-provider-runtime-CD5ZI-ct.js} +6 -6
- package/dist/{prepare-provider-runtime-iA3g-8MS.js.map → prepare-provider-runtime-CD5ZI-ct.js.map} +1 -1
- package/dist/{prepare-session-executor-DbewUeyQ.js → prepare-session-executor-C2nNM2yb.js} +15 -15
- package/dist/{prepare-session-executor-DbewUeyQ.js.map → prepare-session-executor-C2nNM2yb.js.map} +1 -1
- package/dist/{runtime-D_AGEH9G.js → runtime-DMYoB5_x.js} +11 -11
- package/dist/{runtime-D_AGEH9G.js.map → runtime-DMYoB5_x.js.map} +1 -1
- package/dist/{runtime-agent-controller-reporting-submission-CB25cpq0.js → runtime-agent-controller-reporting-submission-DGm8O4q_.js} +5 -5
- package/dist/{runtime-agent-controller-reporting-submission-CB25cpq0.js.map → runtime-agent-controller-reporting-submission-DGm8O4q_.js.map} +1 -1
- package/dist/{runtime-reporting-health-state-205lHdBE.js → runtime-reporting-health-state-BWZgy4pF.js} +6 -6
- package/dist/{runtime-reporting-health-state-205lHdBE.js.map → runtime-reporting-health-state-BWZgy4pF.js.map} +1 -1
- package/dist/{service-yziCG6lR.js → service-C72KhNft.js} +11 -11
- package/dist/{service-yziCG6lR.js.map → service-C72KhNft.js.map} +1 -1
- package/dist/{service-account-control-BQ1e5Y1X.js → service-account-control-DZjUR3I_.js} +5 -5
- package/dist/{service-account-control-BQ1e5Y1X.js.map → service-account-control-DZjUR3I_.js.map} +1 -1
- package/dist/{service-control-capabilities-C4520NIi.js → service-control-capabilities-C2MF5FUD.js} +3 -3
- package/dist/{service-control-capabilities-C4520NIi.js.map → service-control-capabilities-C2MF5FUD.js.map} +1 -1
- package/dist/{service-control-capabilities-DPYmrWgX.js → service-control-capabilities-Y4CGrchz.js} +1 -1
- package/dist/{state-DLMkZqd8.js → state-CK1WXIsI.js} +2 -2
- package/dist/{state-DLMkZqd8.js.map → state-CK1WXIsI.js.map} +1 -1
- package/dist/{upgrade-BmM1hEB3.js → upgrade-BTIKVek7.js} +6 -6
- package/dist/{upgrade-BmM1hEB3.js.map → upgrade-BTIKVek7.js.map} +1 -1
- package/dist/upgrade-DTB0ZmxI.js +4 -0
- package/package.json +11 -11
- package/dist/dist-YPzkhLLp.js.map +0 -1
- package/dist/upgrade-neqPXWyw.js +0 -4
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import { t as normalizeBaseUrl } from "./urls-CY2uzH2-.js";
|
|
4
4
|
import { t as isLoopbackHostname } from "./loopback-hostname-DHQPKq8N.js";
|
|
5
|
-
import { Jn as OPENMELD_HEADER_REQUESTED_ORGANIZATION_ID, Zn as buildOpenMeldRequestContextHeaders, qt as createOpenMeldApiClient } from "./dist-
|
|
5
|
+
import { Jn as OPENMELD_HEADER_REQUESTED_ORGANIZATION_ID, Zn as buildOpenMeldRequestContextHeaders, qt as createOpenMeldApiClient } from "./dist-BewA9srP.js";
|
|
6
6
|
import { K as MIN_SPACE_REQUEST_TIMEOUT_MS, M as resolveAuthSessionExpiryEligibility, V as DEFAULT_SPACE_REQUEST_TIMEOUT_MS, W as MAX_SPACE_REQUEST_TIMEOUT_MS, d as getAuthSessionState } from "./auth-session-CDhQANWx.js";
|
|
7
7
|
import crypto, { createHash } from "node:crypto";
|
|
8
8
|
//#region src/config/auth-request-compatibility.ts
|
|
@@ -452,4 +452,4 @@ function createCliApiClientFoundation(baseUrl, options = {}) {
|
|
|
452
452
|
//#endregion
|
|
453
453
|
export { buildOpenMeldProfileIdentityRequestHeadersWithAuth as a, buildRequestAuthHeaders as c, buildOpenMeldRequestContextFromProfile as d, buildOpenMeldRequestContextFromProfileIdentity as f, AuthRequestCredentialError as i, canAttachAuthTokenToRequest as l, resolveAuthRequestCompatibility as m, fetchSpaceRequestWithTimeout as n, buildOpenMeldProfileRequestHeadersWithAuth as o, deriveAuthBaseUrlFromGatewayUrl as p, resolveSpaceRequestTimeoutMsForDiagnostics as r, buildOpenMeldRequestContextHeadersWithAuth as s, createCliApiClientFoundation as t, fingerprintRequestAuthorization as u };
|
|
454
454
|
|
|
455
|
-
//# sourceMappingURL=api-client-foundation-
|
|
455
|
+
//# sourceMappingURL=api-client-foundation-D-Cb6EVg.js.map
|
package/dist/{api-client-foundation-CDlVc0zT.js.map → api-client-foundation-D-Cb6EVg.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-client-foundation-CDlVc0zT.js","names":["resolveSpaceRequestTimeoutMsForDiagnostics","resolveSpaceRequestTimeoutMsForCliDiagnostics"],"sources":["../src/config/auth-request-compatibility.ts","../src/config/openmeld-request-context.ts","../src/config/request-headers.ts","../src/space/request-timeout.ts","../src/space/fetch-with-timeout.ts","../src/space/api-client-foundation.ts"],"sourcesContent":["import { normalizeBaseUrl } from \"../protocol/urls\";\nimport type { StoredAuthSession } from \"./auth-session\";\nimport { isLoopbackHostname } from \"./loopback-hostname\";\n\nexport type AuthRequestCompatibilityReason =\n | \"invalid_request_url\"\n | \"invalid_auth_url\"\n | \"insecure_transport\"\n | \"host_mismatch\"\n | \"loopback\"\n | \"same_host\"\n | \"gateway_sibling\";\n\nexport type AuthRequestCompatibility = {\n compatible: boolean;\n reason: AuthRequestCompatibilityReason;\n requestHost: string | null;\n authHost: string | null;\n expectedGatewayHost: string | null;\n};\n\nexport function resolveAuthRequestCompatibility(input: {\n session: StoredAuthSession;\n requestUrl: string;\n}): AuthRequestCompatibility {\n const requestUrl = parseUrlOrNull(input.requestUrl);\n if (!requestUrl) {\n return {\n compatible: false,\n reason: \"invalid_request_url\",\n requestHost: null,\n authHost: null,\n expectedGatewayHost: null,\n };\n }\n\n const authBaseUrl = parseUrlOrNull(input.session.authBaseUrl);\n if (!authBaseUrl) {\n return {\n compatible: false,\n reason: \"invalid_auth_url\",\n requestHost: requestUrl.host,\n authHost: null,\n expectedGatewayHost: null,\n };\n }\n\n const expectedGatewayHost = deriveGatewayHost(authBaseUrl);\n const requestHost = requestUrl.host;\n const authHost = authBaseUrl.host;\n\n if (\n (isLoopbackHostname(requestUrl.hostname) &&\n isLoopbackHostname(authBaseUrl.hostname)) ||\n // Isolated worktrees share a hostname across Auth and Gateway ports.\n // Never treat different named localhost lanes as interchangeable.\n (requestUrl.hostname.endsWith(\".localhost\") &&\n requestUrl.hostname === authBaseUrl.hostname &&\n isHttpTransportProtocol(authBaseUrl.protocol) &&\n [\"http:\", \"https:\", \"ws:\", \"wss:\"].includes(requestUrl.protocol))\n ) {\n return {\n compatible: true,\n reason: \"loopback\",\n requestHost,\n authHost,\n expectedGatewayHost,\n };\n }\n\n if (!isSecureTransportProtocol(requestUrl.protocol)) {\n return {\n compatible: false,\n reason: \"insecure_transport\",\n requestHost,\n authHost,\n expectedGatewayHost,\n };\n }\n\n if (requestHost === authHost) {\n return {\n compatible: true,\n reason: \"same_host\",\n requestHost,\n authHost,\n expectedGatewayHost,\n };\n }\n\n if (expectedGatewayHost && requestHost === expectedGatewayHost) {\n return {\n compatible: true,\n reason: \"gateway_sibling\",\n requestHost,\n authHost,\n expectedGatewayHost,\n };\n }\n\n return {\n compatible: false,\n reason: \"host_mismatch\",\n requestHost,\n authHost,\n expectedGatewayHost,\n };\n}\n\nexport function deriveAuthBaseUrlFromGatewayUrl(\n gatewayUrl: string\n): string | null {\n const parsed = parseUrlOrNull(gatewayUrl);\n if (!parsed) {\n return null;\n }\n if (!isHttpTransportProtocol(parsed.protocol)) {\n return null;\n }\n if (!parsed.hostname.startsWith(\"gateway.\")) {\n return null;\n }\n\n const authUrl = new URL(parsed.toString());\n authUrl.hostname = `auth.${parsed.hostname.slice(\"gateway.\".length)}`;\n authUrl.pathname = \"/\";\n authUrl.search = \"\";\n authUrl.hash = \"\";\n return normalizeBaseUrl(authUrl.toString());\n}\n\nfunction deriveGatewayHost(authBaseUrl: URL): string | null {\n if (!authBaseUrl.hostname.startsWith(\"auth.\")) {\n return null;\n }\n\n const gatewayUrl = new URL(authBaseUrl.toString());\n gatewayUrl.hostname = `gateway.${authBaseUrl.hostname.slice(\"auth.\".length)}`;\n return gatewayUrl.host;\n}\n\nfunction parseUrlOrNull(value: string): URL | null {\n try {\n return new URL(value);\n } catch {\n return null;\n }\n}\n\nfunction isSecureTransportProtocol(protocol: string): boolean {\n return protocol === \"https:\" || protocol === \"wss:\";\n}\n\nfunction isHttpTransportProtocol(protocol: string): boolean {\n return protocol === \"http:\" || protocol === \"https:\";\n}\n","import crypto from \"node:crypto\";\nimport type { OpenMeldRequestContext } from \"@openmeld/schemas/types\";\nimport type { OpenMeldProfile } from \"./openmeld-profiles-api\";\n\nexport type OpenMeldRequestContextProfileIdentity = {\n openMeldProfileId: string;\n profileKind?: \"human\" | \"agent\" | \"system\";\n kind?: \"human\" | \"agent\";\n profileHandle?: string;\n profileName: string;\n ownerUserId?: string;\n ownerName?: string;\n agentControllerConversationId?: string;\n};\n\nexport function buildOpenMeldRequestContextFromProfile(input: {\n openMeldProfile: OpenMeldProfile;\n requestId?: string;\n agentControllerConversationId?: string;\n}): OpenMeldRequestContext {\n const requestId =\n normalizeOptionalText(input.requestId) ?? crypto.randomUUID();\n const agentControllerConversationId = normalizeOptionalText(\n input.agentControllerConversationId\n );\n const ownerName = normalizeOptionalText(input.openMeldProfile.ownerName);\n\n return {\n actorContext: {\n requestId,\n openMeldProfileId: input.openMeldProfile.openMeldProfileId,\n profileKind: input.openMeldProfile.profileKind,\n profileHandle: input.openMeldProfile.profileHandle,\n profileName: input.openMeldProfile.profileName,\n ownerUserId: input.openMeldProfile.ownerUserId,\n ...(ownerName ? { ownerName } : {}),\n },\n ...(agentControllerConversationId ? { agentControllerConversationId } : {}),\n };\n}\n\nexport function buildOpenMeldRequestContextFromProfileIdentity(input: {\n profileIdentity: OpenMeldRequestContextProfileIdentity;\n requestId?: string;\n}): OpenMeldRequestContext {\n const requestId =\n normalizeOptionalText(input.requestId) ?? crypto.randomUUID();\n const profileHandle = normalizeOptionalText(\n input.profileIdentity.profileHandle\n );\n const ownerUserId = normalizeOptionalText(input.profileIdentity.ownerUserId);\n const ownerName = normalizeOptionalText(input.profileIdentity.ownerName);\n const agentControllerConversationId = normalizeOptionalText(\n input.profileIdentity.agentControllerConversationId\n );\n const profileKind =\n input.profileIdentity.profileKind ??\n (input.profileIdentity.kind === \"human\" ||\n input.profileIdentity.kind === \"agent\"\n ? input.profileIdentity.kind\n : \"system\");\n\n return {\n actorContext: {\n requestId,\n openMeldProfileId: input.profileIdentity.openMeldProfileId,\n profileKind,\n ...(profileHandle ? { profileHandle } : {}),\n profileName: input.profileIdentity.profileName,\n ...(ownerUserId ? { ownerUserId } : {}),\n ...(ownerName ? { ownerName } : {}),\n },\n ...(agentControllerConversationId ? { agentControllerConversationId } : {}),\n };\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n","import { createHash } from \"node:crypto\";\nimport {\n buildOpenMeldRequestContextHeaders,\n type OpenMeldRequestContextHeadersInput,\n} from \"@openmeld/gateway-contract\";\nimport type { OpenMeldRequestContext } from \"@openmeld/schemas/types\";\nimport {\n type AuthRequestCompatibilityReason,\n resolveAuthRequestCompatibility,\n} from \"./auth-request-compatibility\";\nimport {\n type AuthSessionStateReasonCode,\n getAuthSessionState,\n type StoredAuthSession,\n} from \"./auth-session\";\nimport { resolveAuthSessionExpiryEligibility } from \"./auth-session-expiry\";\nimport type { OpenMeldProfile } from \"./openmeld-profiles-api\";\nimport {\n buildOpenMeldRequestContextFromProfile,\n buildOpenMeldRequestContextFromProfileIdentity,\n type OpenMeldRequestContextProfileIdentity,\n} from \"./openmeld-request-context\";\n\nconst DEFAULT_TOKEN_TYPE = \"Bearer\";\nconst AUTHORIZATION_HEADER = \"Authorization\";\n\n// Ephemeral correlation for the exact credential attached to a request/socket.\n// Never include this fingerprint in persisted or uploaded diagnostics.\nexport function fingerprintRequestAuthorization(authorization: string): string {\n return createHash(\"sha256\").update(authorization).digest(\"hex\");\n}\n\ntype RequestAuthHeadersInput = {\n authSession?: StoredAuthSession | null;\n expectedOwnerUserId?: string;\n requestUrl: string;\n};\n\ntype OpenMeldRequestContextHeadersWithAuthInput =\n OpenMeldRequestContextHeadersInput & {\n authSession?: StoredAuthSession | null;\n requestUrl: string;\n };\n\nexport type AuthTokenAttachment =\n | {\n status: \"attachable\";\n token: string;\n tokenType: string;\n }\n | {\n status: \"dropped\";\n reason:\n | \"empty_token\"\n | \"session_expired\"\n | \"session_expiry_invalid\"\n | AuthRequestCompatibilityReason;\n requestHost: string | null;\n authHost: string | null;\n expectedGatewayHost: string | null;\n };\n\nexport type DroppedAuthTokenAttachment = Extract<\n AuthTokenAttachment,\n { status: \"dropped\" }\n>;\n\nexport type AuthRequestCredentialFailureReason =\n | DroppedAuthTokenAttachment[\"reason\"]\n | AuthSessionStateReasonCode\n | \"session_invalid\"\n | \"session_revoked\";\n\nexport class AuthRequestCredentialError extends Error {\n readonly retryAfterMs?: number;\n readonly authHost: string | null;\n readonly expectedGatewayHost: string | null;\n readonly reason: AuthRequestCredentialFailureReason;\n readonly requestHost: string | null;\n readonly droppedAttachment?: DroppedAuthTokenAttachment;\n\n constructor(input: {\n retryAfterMs?: number;\n authHost: string | null;\n expectedGatewayHost: string | null;\n reason: AuthRequestCredentialFailureReason;\n requestHost: string | null;\n droppedAttachment?: DroppedAuthTokenAttachment;\n }) {\n super(\n `OpenMeld refused to send a request with unusable stored credentials (${input.reason}).`\n );\n this.name = \"AuthRequestCredentialError\";\n this.authHost = input.authHost;\n this.expectedGatewayHost = input.expectedGatewayHost;\n this.reason = input.reason;\n this.requestHost = input.requestHost;\n this.droppedAttachment = input.droppedAttachment;\n this.retryAfterMs = input.retryAfterMs;\n }\n}\n\nexport async function buildRequestAuthHeaders(\n input: RequestAuthHeadersInput\n): Promise<Record<string, string>> {\n const headers: Record<string, string> = {};\n await attachAuthHeader(headers, input);\n return headers;\n}\n\nexport async function buildOpenMeldRequestContextHeadersWithAuth(\n input: OpenMeldRequestContextHeadersWithAuthInput\n): Promise<Record<string, string>> {\n const headers = buildOpenMeldRequestContextHeaders(input);\n await attachAuthHeader(headers, input);\n return headers;\n}\n\nexport async function buildOpenMeldProfileRequestHeadersWithAuth(input: {\n openMeldProfile: OpenMeldProfile;\n requestUrl: string;\n authSession?: StoredAuthSession | null;\n agentControllerConversationId?: string;\n spacePassword?: string;\n}): Promise<Record<string, string>> {\n return await buildOpenMeldRequestContextHeadersWithAuth({\n requestContext: buildOpenMeldRequestContextFromProfile({\n openMeldProfile: input.openMeldProfile,\n agentControllerConversationId: input.agentControllerConversationId,\n }),\n requestUrl: input.requestUrl,\n ...(input.authSession === undefined\n ? {}\n : { authSession: input.authSession }),\n ...(input.spacePassword === undefined\n ? {}\n : { spacePassword: input.spacePassword }),\n });\n}\n\nexport async function buildOpenMeldProfileIdentityRequestHeadersWithAuth(input: {\n profileIdentity: OpenMeldRequestContextProfileIdentity;\n requestUrl: string;\n authSession?: StoredAuthSession | null;\n spacePassword?: string;\n}): Promise<Record<string, string>> {\n return await buildOpenMeldRequestContextHeadersWithAuth({\n requestContext: buildOpenMeldRequestContextFromProfileIdentity({\n profileIdentity: input.profileIdentity,\n }),\n requestUrl: input.requestUrl,\n ...(input.authSession === undefined\n ? {}\n : { authSession: input.authSession }),\n ...(input.spacePassword === undefined\n ? {}\n : { spacePassword: input.spacePassword }),\n });\n}\n\nexport function withSpacePassword(\n requestContext: OpenMeldRequestContext,\n spacePassword?: string\n): OpenMeldRequestContextHeadersInput {\n return {\n requestContext,\n ...(spacePassword === undefined ? {} : { spacePassword }),\n };\n}\n\n// One decision for \"can this stored session authenticate this request\", with\n// the drop reason preserved. Header building and the daemon stream connect\n// gate must share this so they cannot drift apart.\nexport function resolveAuthTokenAttachment(input: {\n session: StoredAuthSession;\n requestUrl: string;\n}): AuthTokenAttachment {\n const compatibility = resolveAuthRequestCompatibility({\n session: input.session,\n requestUrl: input.requestUrl,\n });\n const token = normalizeAccessToken(input.session);\n if (!token) {\n return {\n status: \"dropped\",\n reason: \"empty_token\",\n requestHost: compatibility.requestHost,\n authHost: compatibility.authHost,\n expectedGatewayHost: compatibility.expectedGatewayHost,\n };\n }\n if (!compatibility.compatible) {\n return {\n status: \"dropped\",\n reason: compatibility.reason,\n requestHost: compatibility.requestHost,\n authHost: compatibility.authHost,\n expectedGatewayHost: compatibility.expectedGatewayHost,\n };\n }\n const expiryReason = resolveSessionExpiryReason(input.session);\n if (expiryReason) {\n return {\n status: \"dropped\",\n reason: expiryReason,\n requestHost: compatibility.requestHost,\n authHost: compatibility.authHost,\n expectedGatewayHost: compatibility.expectedGatewayHost,\n };\n }\n return {\n status: \"attachable\",\n token,\n tokenType: normalizeTokenType(input.session.tokenType),\n };\n}\n\nexport function requireAuthTokenAttachment(input: {\n session: StoredAuthSession;\n requestUrl: string;\n}): Extract<AuthTokenAttachment, { status: \"attachable\" }> {\n const attachment = resolveAuthTokenAttachment(input);\n if (attachment.status === \"dropped\") {\n throw createAuthRequestCredentialError(attachment);\n }\n return attachment;\n}\n\nasync function attachAuthHeader(\n headers: Record<string, string>,\n input: RequestAuthHeadersInput\n): Promise<void> {\n const session = await resolveAuthSessionForHeaders(input);\n if (\n input.expectedOwnerUserId &&\n session?.user?.id !== input.expectedOwnerUserId\n ) {\n throw new Error(\"auth.session_owner_changed\");\n }\n if (session === null) {\n // No stored credentials exist, so there is nothing to strip: the caller\n // is knowingly sending an unauthenticated request.\n return;\n }\n\n let attachment: Extract<AuthTokenAttachment, { status: \"attachable\" }>;\n try {\n attachment = requireAuthTokenAttachment({\n session,\n requestUrl: input.requestUrl,\n });\n } catch (error) {\n if (error instanceof AuthRequestCredentialError) {\n logRejectedAuthRequestCredential(error);\n }\n throw error;\n }\n headers[AUTHORIZATION_HEADER] = `${attachment.tokenType} ${attachment.token}`;\n}\n\nfunction logRejectedAuthRequestCredential(\n error: AuthRequestCredentialError\n): void {\n console.error(\"[openmeld.auth.request_credential_rejected]\", {\n authHost: error.authHost,\n expectedGatewayHost: error.expectedGatewayHost,\n reason: error.reason,\n requestHost: error.requestHost,\n });\n}\n\nasync function resolveAuthSessionForHeaders(\n input: RequestAuthHeadersInput\n): Promise<StoredAuthSession | null> {\n if (input.authSession !== undefined) {\n return input.authSession;\n }\n\n const sessionState = await getAuthSessionState({ refreshExpired: true });\n if (sessionState.state === \"missing\") {\n return null;\n }\n if (sessionState.state !== \"valid\" || sessionState.session === null) {\n const error = new AuthRequestCredentialError({\n retryAfterMs: sessionState.retryAfterMs,\n authHost: null,\n expectedGatewayHost: null,\n reason:\n sessionState.reasonCode ??\n (sessionState.state === \"revoked\"\n ? \"session_revoked\"\n : \"session_invalid\"),\n requestHost: parseRequestHost(input.requestUrl),\n });\n logRejectedAuthRequestCredential(error);\n throw error;\n }\n\n return sessionState.session;\n}\n\nfunction createAuthRequestCredentialError(\n attachment: DroppedAuthTokenAttachment\n): AuthRequestCredentialError {\n return new AuthRequestCredentialError({\n authHost: attachment.authHost,\n expectedGatewayHost: attachment.expectedGatewayHost,\n reason: attachment.reason,\n requestHost: attachment.requestHost,\n droppedAttachment: attachment,\n });\n}\n\nfunction parseRequestHost(requestUrl: string): string | null {\n try {\n return new URL(requestUrl).host || null;\n } catch {\n return null;\n }\n}\n\nfunction normalizeAccessToken(session: StoredAuthSession): string {\n return String(session.accessToken ?? \"\").trim();\n}\n\nfunction normalizeTokenType(tokenType: string | undefined): string {\n const normalized = String(tokenType ?? \"\").trim();\n return normalized.length > 0 ? normalized : DEFAULT_TOKEN_TYPE;\n}\n\nfunction resolveSessionExpiryReason(\n session: StoredAuthSession\n): \"session_expired\" | \"session_expiry_invalid\" | null {\n const eligibility = resolveAuthSessionExpiryEligibility(session.expiresAt);\n if (eligibility.status === \"invalid\") {\n return \"session_expiry_invalid\";\n }\n return eligibility.status === \"expired\" ? \"session_expired\" : null;\n}\n\nexport function canAttachAuthTokenToRequest(\n session: StoredAuthSession,\n requestUrl: string\n): boolean {\n return (\n resolveAuthTokenAttachment({\n session,\n requestUrl,\n }).status === \"attachable\"\n );\n}\n","import {\n DEFAULT_SPACE_CONVERSATION_VALIDATE_TIMEOUT_MS,\n DEFAULT_SPACE_REQUEST_TIMEOUT_MS,\n MAX_SPACE_REQUEST_TIMEOUT_MS,\n MIN_SPACE_REQUEST_TIMEOUT_MS,\n} from \"../strategy-constants\";\n\nconst SPACE_REQUEST_TIMEOUT_ENV_KEY = \"OPENMELD_SPACE_REQUEST_TIMEOUT_MS\";\n\nexport function resolveSpaceRequestTimeoutMs(override?: number): number {\n if (isFinitePositiveNumber(override)) {\n return clampSpaceRequestTimeoutMs(override);\n }\n\n const fromEnv = Number.parseInt(\n String(process.env[SPACE_REQUEST_TIMEOUT_ENV_KEY] ?? \"\"),\n 10\n );\n if (isFinitePositiveNumber(fromEnv)) {\n return clampSpaceRequestTimeoutMs(fromEnv);\n }\n\n return DEFAULT_SPACE_REQUEST_TIMEOUT_MS;\n}\n\nexport function resolveSpaceRequestTimeoutMsForDiagnostics(): number {\n return resolveSpaceRequestTimeoutMs(undefined);\n}\n\nexport function resolveSpaceConversationValidateTimeoutMs(): number {\n return Math.max(\n resolveSpaceRequestTimeoutMs(undefined),\n DEFAULT_SPACE_CONVERSATION_VALIDATE_TIMEOUT_MS\n );\n}\n\nfunction clampSpaceRequestTimeoutMs(value: number): number {\n const normalized = Math.trunc(value);\n return Math.max(\n MIN_SPACE_REQUEST_TIMEOUT_MS,\n Math.min(MAX_SPACE_REQUEST_TIMEOUT_MS, normalized)\n );\n}\n\nfunction isFinitePositiveNumber(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0;\n}\n","import {\n resolveSpaceRequestTimeoutMs,\n resolveSpaceRequestTimeoutMsForDiagnostics as resolveSpaceRequestTimeoutMsForCliDiagnostics,\n} from \"./request-timeout\";\n\nexport async function fetchSpaceRequestWithTimeout(input: {\n url: string;\n operation: string;\n init?: RequestInit;\n timeoutMs?: number;\n}): Promise<Response> {\n const timeoutMs = resolveSpaceRequestTimeoutMs(input.timeoutMs);\n const timeoutSignal = AbortSignal.timeout(timeoutMs);\n const composed = composeAbortSignals(input.init?.signal, timeoutSignal);\n\n try {\n try {\n return await fetch(input.url, {\n ...input.init,\n signal: composed.signal,\n });\n } catch (error) {\n // A keep-alive connection that a proxy silently dropped fails exactly\n // once and undici evicts it; the retry rides a fresh connection. This\n // is what keeps a long-lived service working behind flaky proxies\n // without asking users to touch their network config.\n if (\n timeoutSignal.aborted ||\n composed.signal.aborted ||\n !shouldWrapNetworkRequestError(error)\n ) {\n throw error;\n }\n return await fetch(input.url, {\n ...input.init,\n signal: composed.signal,\n });\n }\n } catch (error) {\n if (timeoutSignal.aborted) {\n throw createSpaceRequestTimeoutError({\n operation: input.operation,\n timeoutMs,\n cause: error,\n });\n }\n if (shouldWrapNetworkRequestError(error)) {\n throw createSpaceRequestNetworkError({\n operation: input.operation,\n url: input.url,\n cause: error,\n });\n }\n throw error;\n } finally {\n composed.cleanup();\n }\n}\n\nexport function resolveSpaceRequestTimeoutMsForDiagnostics(): number {\n return resolveSpaceRequestTimeoutMsForCliDiagnostics();\n}\n\nfunction createSpaceRequestTimeoutError(input: {\n operation: string;\n timeoutMs: number;\n cause: unknown;\n}): Error {\n const error = new Error(\n `${input.operation} request timed out after ${input.timeoutMs}ms`,\n { cause: input.cause }\n ) as Error & { code?: string };\n error.code = \"network.timeout\";\n return error;\n}\n\nfunction createSpaceRequestNetworkError(input: {\n operation: string;\n url: string;\n cause: unknown;\n}): Error {\n const error = new Error(\n `${input.operation} request could not reach ${describeRequestTarget(input.url)} (${toErrorMessage(input.cause)})`,\n { cause: input.cause }\n ) as Error & { code?: string };\n error.code = \"network.request_failed\";\n return error;\n}\n\nfunction composeAbortSignals(\n parent: AbortSignal | null | undefined,\n timeout: AbortSignal\n): { signal: AbortSignal; cleanup: () => void } {\n if (!parent) {\n return {\n signal: timeout,\n cleanup: () => undefined,\n };\n }\n\n if (parent.aborted || timeout.aborted) {\n const controller = new AbortController();\n controller.abort();\n return {\n signal: controller.signal,\n cleanup: () => undefined,\n };\n }\n\n const controller = new AbortController();\n const abort = () => {\n controller.abort();\n };\n\n parent.addEventListener(\"abort\", abort, { once: true });\n timeout.addEventListener(\"abort\", abort, { once: true });\n\n return {\n signal: controller.signal,\n cleanup: () => {\n parent.removeEventListener(\"abort\", abort);\n timeout.removeEventListener(\"abort\", abort);\n },\n };\n}\n\nfunction describeRequestTarget(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return url;\n }\n}\n\nfunction toErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n const message = error.message.trim();\n return message.length > 0 ? message : \"request failed\";\n }\n const message = String(error ?? \"\").trim();\n return message.length > 0 ? message : \"request failed\";\n}\n\nfunction shouldWrapNetworkRequestError(error: unknown): boolean {\n if (error instanceof TypeError) {\n return true;\n }\n if (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n typeof error.code === \"string\" &&\n error.code.startsWith(\"ERR_SSL_\")\n ) {\n return true;\n }\n const message = toErrorMessage(error).toLowerCase();\n return (\n message.includes(\"fetch failed\") ||\n message.includes(\"failed to fetch\") ||\n message.includes(\"network request failed\") ||\n message.includes(\"ssl_decryption_failed_or_bad_record_mac\")\n );\n}\n","import {\n createOpenMeldApiClient,\n type OpenMeldApiClientFoundation,\n} from \"@openmeld/api-client\";\nimport {\n buildOpenMeldRequestContextHeaders,\n OPENMELD_HEADER_REQUESTED_ORGANIZATION_ID,\n} from \"@openmeld/gateway-contract\";\nimport { buildRequestAuthHeaders } from \"../config/request-headers\";\nimport { fetchSpaceRequestWithTimeout } from \"./fetch-with-timeout\";\n\nexport function createCliApiClientFoundation(\n baseUrl: string,\n options: {\n onAuthHeadersResolved?: (headers: Record<string, string>) => void;\n organizationId?: string;\n expectedOwnerUserId?: string;\n } = {}\n): OpenMeldApiClientFoundation {\n return createOpenMeldApiClient({\n baseUrl,\n transport: async (request) =>\n await fetchSpaceRequestWithTimeout({\n url: request.url,\n operation: request.operation,\n init: request.init,\n timeoutMs: request.timeoutMs,\n }),\n getAuthHeaders: async ({ requestUrl }) => {\n const headers = await buildRequestAuthHeaders({\n requestUrl,\n expectedOwnerUserId: options.expectedOwnerUserId,\n });\n if (options.organizationId) {\n headers[OPENMELD_HEADER_REQUESTED_ORGANIZATION_ID] =\n options.organizationId;\n }\n options.onAuthHeadersResolved?.(headers);\n return headers;\n },\n getRequestContextHeaders: async ({ requestContext, spacePassword }) =>\n buildOpenMeldRequestContextHeaders({\n requestContext,\n ...(spacePassword === undefined ? {} : { spacePassword }),\n }),\n });\n}\n"],"mappings":";;;;;;;;AAqBA,SAAgB,gCAAgC,OAGnB;CAC3B,MAAM,aAAa,eAAe,MAAM,UAAU;CAClD,IAAI,CAAC,YACH,OAAO;EACL,YAAY;EACZ,QAAQ;EACR,aAAa;EACb,UAAU;EACV,qBAAqB;CACvB;CAGF,MAAM,cAAc,eAAe,MAAM,QAAQ,WAAW;CAC5D,IAAI,CAAC,aACH,OAAO;EACL,YAAY;EACZ,QAAQ;EACR,aAAa,WAAW;EACxB,UAAU;EACV,qBAAqB;CACvB;CAGF,MAAM,sBAAsB,kBAAkB,WAAW;CACzD,MAAM,cAAc,WAAW;CAC/B,MAAM,WAAW,YAAY;CAE7B,IACG,mBAAmB,WAAW,QAAQ,KACrC,mBAAmB,YAAY,QAAQ,KAGxC,WAAW,SAAS,SAAS,YAAY,KACxC,WAAW,aAAa,YAAY,YACpC,wBAAwB,YAAY,QAAQ,KAC5C;EAAC;EAAS;EAAU;EAAO;CAAM,CAAC,CAAC,SAAS,WAAW,QAAQ,GAEjE,OAAO;EACL,YAAY;EACZ,QAAQ;EACR;EACA;EACA;CACF;CAGF,IAAI,CAAC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AQ,SAAS,IAAI,UAAU;AACxC;AAEA,SAAS,8BAA8B,OAAyB;CAC9D,IAAI,iBAAiB,WACnB,OAAO;CAET,IACE,OAAO,UAAU,YACjB,UAAU,QACV,UAAU,SACV,OAAO,MAAM,SAAS,YACtB,MAAM,KAAK,WAAW,UAAU,GAEhC,OAAO;CAET,MAAM,UAAU,eAAe,KAAK,CAAC,CAAC,YAAY;CAClD,OACE,QAAQ,SAAS,cAAc,KAC/B,QAAQ,SAAS,iBAAiB,KAClC,QAAQ,SAAS,wBAAwB,KACzC,QAAQ,SAAS,yCAAyC;AAE9D;;;ACxJA,SAAgB,6BACd,SACA,UAII,CAAC,GACwB;CAC7B,OAAO,wBAAwB;EAC7B;EACA,WAAW,OAAO,YAChB,MAAM,6BAA6B;GACjC,KAAK,QAAQ;GACb,WAAW,QAAQ;GACnB,MAAM,QAAQ;GACd,WAAW,QAAQ;EACrB,CAAC;EACH,gBAAgB,OAAO,EAAE,iBAAiB;GACxC,MAAM,UAAU,MAAM,wBAAwB;IAC5C;IACA,qBAAqB,QAAQ;GAC/B,CAAC;GACD,IAAI,QAAQ,gBACV,QAAQ,6CACN,QAAQ;GAEZ,QAAQ,wBAAwB,OAAO;GACvC,OAAO;EACT;EACA,0BAA0B,OAAO,EAAE,gBAAgB,oBACjD,mCAAmC;GACjC;GACA,GAAI,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc;EACzD,CAAC;CACL,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"api-client-foundation-D-Cb6EVg.js","names":["resolveSpaceRequestTimeoutMsForDiagnostics","resolveSpaceRequestTimeoutMsForCliDiagnostics"],"sources":["../src/config/auth-request-compatibility.ts","../src/config/openmeld-request-context.ts","../src/config/request-headers.ts","../src/space/request-timeout.ts","../src/space/fetch-with-timeout.ts","../src/space/api-client-foundation.ts"],"sourcesContent":["import { normalizeBaseUrl } from \"../protocol/urls\";\nimport type { StoredAuthSession } from \"./auth-session\";\nimport { isLoopbackHostname } from \"./loopback-hostname\";\n\nexport type AuthRequestCompatibilityReason =\n | \"invalid_request_url\"\n | \"invalid_auth_url\"\n | \"insecure_transport\"\n | \"host_mismatch\"\n | \"loopback\"\n | \"same_host\"\n | \"gateway_sibling\";\n\nexport type AuthRequestCompatibility = {\n compatible: boolean;\n reason: AuthRequestCompatibilityReason;\n requestHost: string | null;\n authHost: string | null;\n expectedGatewayHost: string | null;\n};\n\nexport function resolveAuthRequestCompatibility(input: {\n session: StoredAuthSession;\n requestUrl: string;\n}): AuthRequestCompatibility {\n const requestUrl = parseUrlOrNull(input.requestUrl);\n if (!requestUrl) {\n return {\n compatible: false,\n reason: \"invalid_request_url\",\n requestHost: null,\n authHost: null,\n expectedGatewayHost: null,\n };\n }\n\n const authBaseUrl = parseUrlOrNull(input.session.authBaseUrl);\n if (!authBaseUrl) {\n return {\n compatible: false,\n reason: \"invalid_auth_url\",\n requestHost: requestUrl.host,\n authHost: null,\n expectedGatewayHost: null,\n };\n }\n\n const expectedGatewayHost = deriveGatewayHost(authBaseUrl);\n const requestHost = requestUrl.host;\n const authHost = authBaseUrl.host;\n\n if (\n (isLoopbackHostname(requestUrl.hostname) &&\n isLoopbackHostname(authBaseUrl.hostname)) ||\n // Isolated worktrees share a hostname across Auth and Gateway ports.\n // Never treat different named localhost lanes as interchangeable.\n (requestUrl.hostname.endsWith(\".localhost\") &&\n requestUrl.hostname === authBaseUrl.hostname &&\n isHttpTransportProtocol(authBaseUrl.protocol) &&\n [\"http:\", \"https:\", \"ws:\", \"wss:\"].includes(requestUrl.protocol))\n ) {\n return {\n compatible: true,\n reason: \"loopback\",\n requestHost,\n authHost,\n expectedGatewayHost,\n };\n }\n\n if (!isSecureTransportProtocol(requestUrl.protocol)) {\n return {\n compatible: false,\n reason: \"insecure_transport\",\n requestHost,\n authHost,\n expectedGatewayHost,\n };\n }\n\n if (requestHost === authHost) {\n return {\n compatible: true,\n reason: \"same_host\",\n requestHost,\n authHost,\n expectedGatewayHost,\n };\n }\n\n if (expectedGatewayHost && requestHost === expectedGatewayHost) {\n return {\n compatible: true,\n reason: \"gateway_sibling\",\n requestHost,\n authHost,\n expectedGatewayHost,\n };\n }\n\n return {\n compatible: false,\n reason: \"host_mismatch\",\n requestHost,\n authHost,\n expectedGatewayHost,\n };\n}\n\nexport function deriveAuthBaseUrlFromGatewayUrl(\n gatewayUrl: string\n): string | null {\n const parsed = parseUrlOrNull(gatewayUrl);\n if (!parsed) {\n return null;\n }\n if (!isHttpTransportProtocol(parsed.protocol)) {\n return null;\n }\n if (!parsed.hostname.startsWith(\"gateway.\")) {\n return null;\n }\n\n const authUrl = new URL(parsed.toString());\n authUrl.hostname = `auth.${parsed.hostname.slice(\"gateway.\".length)}`;\n authUrl.pathname = \"/\";\n authUrl.search = \"\";\n authUrl.hash = \"\";\n return normalizeBaseUrl(authUrl.toString());\n}\n\nfunction deriveGatewayHost(authBaseUrl: URL): string | null {\n if (!authBaseUrl.hostname.startsWith(\"auth.\")) {\n return null;\n }\n\n const gatewayUrl = new URL(authBaseUrl.toString());\n gatewayUrl.hostname = `gateway.${authBaseUrl.hostname.slice(\"auth.\".length)}`;\n return gatewayUrl.host;\n}\n\nfunction parseUrlOrNull(value: string): URL | null {\n try {\n return new URL(value);\n } catch {\n return null;\n }\n}\n\nfunction isSecureTransportProtocol(protocol: string): boolean {\n return protocol === \"https:\" || protocol === \"wss:\";\n}\n\nfunction isHttpTransportProtocol(protocol: string): boolean {\n return protocol === \"http:\" || protocol === \"https:\";\n}\n","import crypto from \"node:crypto\";\nimport type { OpenMeldRequestContext } from \"@openmeld/schemas/types\";\nimport type { OpenMeldProfile } from \"./openmeld-profiles-api\";\n\nexport type OpenMeldRequestContextProfileIdentity = {\n openMeldProfileId: string;\n profileKind?: \"human\" | \"agent\" | \"system\";\n kind?: \"human\" | \"agent\";\n profileHandle?: string;\n profileName: string;\n ownerUserId?: string;\n ownerName?: string;\n agentControllerConversationId?: string;\n};\n\nexport function buildOpenMeldRequestContextFromProfile(input: {\n openMeldProfile: OpenMeldProfile;\n requestId?: string;\n agentControllerConversationId?: string;\n}): OpenMeldRequestContext {\n const requestId =\n normalizeOptionalText(input.requestId) ?? crypto.randomUUID();\n const agentControllerConversationId = normalizeOptionalText(\n input.agentControllerConversationId\n );\n const ownerName = normalizeOptionalText(input.openMeldProfile.ownerName);\n\n return {\n actorContext: {\n requestId,\n openMeldProfileId: input.openMeldProfile.openMeldProfileId,\n profileKind: input.openMeldProfile.profileKind,\n profileHandle: input.openMeldProfile.profileHandle,\n profileName: input.openMeldProfile.profileName,\n ownerUserId: input.openMeldProfile.ownerUserId,\n ...(ownerName ? { ownerName } : {}),\n },\n ...(agentControllerConversationId ? { agentControllerConversationId } : {}),\n };\n}\n\nexport function buildOpenMeldRequestContextFromProfileIdentity(input: {\n profileIdentity: OpenMeldRequestContextProfileIdentity;\n requestId?: string;\n}): OpenMeldRequestContext {\n const requestId =\n normalizeOptionalText(input.requestId) ?? crypto.randomUUID();\n const profileHandle = normalizeOptionalText(\n input.profileIdentity.profileHandle\n );\n const ownerUserId = normalizeOptionalText(input.profileIdentity.ownerUserId);\n const ownerName = normalizeOptionalText(input.profileIdentity.ownerName);\n const agentControllerConversationId = normalizeOptionalText(\n input.profileIdentity.agentControllerConversationId\n );\n const profileKind =\n input.profileIdentity.profileKind ??\n (input.profileIdentity.kind === \"human\" ||\n input.profileIdentity.kind === \"agent\"\n ? input.profileIdentity.kind\n : \"system\");\n\n return {\n actorContext: {\n requestId,\n openMeldProfileId: input.profileIdentity.openMeldProfileId,\n profileKind,\n ...(profileHandle ? { profileHandle } : {}),\n profileName: input.profileIdentity.profileName,\n ...(ownerUserId ? { ownerUserId } : {}),\n ...(ownerName ? { ownerName } : {}),\n },\n ...(agentControllerConversationId ? { agentControllerConversationId } : {}),\n };\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n","import { createHash } from \"node:crypto\";\nimport {\n buildOpenMeldRequestContextHeaders,\n type OpenMeldRequestContextHeadersInput,\n} from \"@openmeld/gateway-contract\";\nimport type { OpenMeldRequestContext } from \"@openmeld/schemas/types\";\nimport {\n type AuthRequestCompatibilityReason,\n resolveAuthRequestCompatibility,\n} from \"./auth-request-compatibility\";\nimport {\n type AuthSessionStateReasonCode,\n getAuthSessionState,\n type StoredAuthSession,\n} from \"./auth-session\";\nimport { resolveAuthSessionExpiryEligibility } from \"./auth-session-expiry\";\nimport type { OpenMeldProfile } from \"./openmeld-profiles-api\";\nimport {\n buildOpenMeldRequestContextFromProfile,\n buildOpenMeldRequestContextFromProfileIdentity,\n type OpenMeldRequestContextProfileIdentity,\n} from \"./openmeld-request-context\";\n\nconst DEFAULT_TOKEN_TYPE = \"Bearer\";\nconst AUTHORIZATION_HEADER = \"Authorization\";\n\n// Ephemeral correlation for the exact credential attached to a request/socket.\n// Never include this fingerprint in persisted or uploaded diagnostics.\nexport function fingerprintRequestAuthorization(authorization: string): string {\n return createHash(\"sha256\").update(authorization).digest(\"hex\");\n}\n\ntype RequestAuthHeadersInput = {\n authSession?: StoredAuthSession | null;\n expectedOwnerUserId?: string;\n requestUrl: string;\n};\n\ntype OpenMeldRequestContextHeadersWithAuthInput =\n OpenMeldRequestContextHeadersInput & {\n authSession?: StoredAuthSession | null;\n requestUrl: string;\n };\n\nexport type AuthTokenAttachment =\n | {\n status: \"attachable\";\n token: string;\n tokenType: string;\n }\n | {\n status: \"dropped\";\n reason:\n | \"empty_token\"\n | \"session_expired\"\n | \"session_expiry_invalid\"\n | AuthRequestCompatibilityReason;\n requestHost: string | null;\n authHost: string | null;\n expectedGatewayHost: string | null;\n };\n\nexport type DroppedAuthTokenAttachment = Extract<\n AuthTokenAttachment,\n { status: \"dropped\" }\n>;\n\nexport type AuthRequestCredentialFailureReason =\n | DroppedAuthTokenAttachment[\"reason\"]\n | AuthSessionStateReasonCode\n | \"session_invalid\"\n | \"session_revoked\";\n\nexport class AuthRequestCredentialError extends Error {\n readonly retryAfterMs?: number;\n readonly authHost: string | null;\n readonly expectedGatewayHost: string | null;\n readonly reason: AuthRequestCredentialFailureReason;\n readonly requestHost: string | null;\n readonly droppedAttachment?: DroppedAuthTokenAttachment;\n\n constructor(input: {\n retryAfterMs?: number;\n authHost: string | null;\n expectedGatewayHost: string | null;\n reason: AuthRequestCredentialFailureReason;\n requestHost: string | null;\n droppedAttachment?: DroppedAuthTokenAttachment;\n }) {\n super(\n `OpenMeld refused to send a request with unusable stored credentials (${input.reason}).`\n );\n this.name = \"AuthRequestCredentialError\";\n this.authHost = input.authHost;\n this.expectedGatewayHost = input.expectedGatewayHost;\n this.reason = input.reason;\n this.requestHost = input.requestHost;\n this.droppedAttachment = input.droppedAttachment;\n this.retryAfterMs = input.retryAfterMs;\n }\n}\n\nexport async function buildRequestAuthHeaders(\n input: RequestAuthHeadersInput\n): Promise<Record<string, string>> {\n const headers: Record<string, string> = {};\n await attachAuthHeader(headers, input);\n return headers;\n}\n\nexport async function buildOpenMeldRequestContextHeadersWithAuth(\n input: OpenMeldRequestContextHeadersWithAuthInput\n): Promise<Record<string, string>> {\n const headers = buildOpenMeldRequestContextHeaders(input);\n await attachAuthHeader(headers, input);\n return headers;\n}\n\nexport async function buildOpenMeldProfileRequestHeadersWithAuth(input: {\n openMeldProfile: OpenMeldProfile;\n requestUrl: string;\n authSession?: StoredAuthSession | null;\n agentControllerConversationId?: string;\n spacePassword?: string;\n}): Promise<Record<string, string>> {\n return await buildOpenMeldRequestContextHeadersWithAuth({\n requestContext: buildOpenMeldRequestContextFromProfile({\n openMeldProfile: input.openMeldProfile,\n agentControllerConversationId: input.agentControllerConversationId,\n }),\n requestUrl: input.requestUrl,\n ...(input.authSession === undefined\n ? {}\n : { authSession: input.authSession }),\n ...(input.spacePassword === undefined\n ? {}\n : { spacePassword: input.spacePassword }),\n });\n}\n\nexport async function buildOpenMeldProfileIdentityRequestHeadersWithAuth(input: {\n profileIdentity: OpenMeldRequestContextProfileIdentity;\n requestUrl: string;\n authSession?: StoredAuthSession | null;\n spacePassword?: string;\n}): Promise<Record<string, string>> {\n return await buildOpenMeldRequestContextHeadersWithAuth({\n requestContext: buildOpenMeldRequestContextFromProfileIdentity({\n profileIdentity: input.profileIdentity,\n }),\n requestUrl: input.requestUrl,\n ...(input.authSession === undefined\n ? {}\n : { authSession: input.authSession }),\n ...(input.spacePassword === undefined\n ? {}\n : { spacePassword: input.spacePassword }),\n });\n}\n\nexport function withSpacePassword(\n requestContext: OpenMeldRequestContext,\n spacePassword?: string\n): OpenMeldRequestContextHeadersInput {\n return {\n requestContext,\n ...(spacePassword === undefined ? {} : { spacePassword }),\n };\n}\n\n// One decision for \"can this stored session authenticate this request\", with\n// the drop reason preserved. Header building and the daemon stream connect\n// gate must share this so they cannot drift apart.\nexport function resolveAuthTokenAttachment(input: {\n session: StoredAuthSession;\n requestUrl: string;\n}): AuthTokenAttachment {\n const compatibility = resolveAuthRequestCompatibility({\n session: input.session,\n requestUrl: input.requestUrl,\n });\n const token = normalizeAccessToken(input.session);\n if (!token) {\n return {\n status: \"dropped\",\n reason: \"empty_token\",\n requestHost: compatibility.requestHost,\n authHost: compatibility.authHost,\n expectedGatewayHost: compatibility.expectedGatewayHost,\n };\n }\n if (!compatibility.compatible) {\n return {\n status: \"dropped\",\n reason: compatibility.reason,\n requestHost: compatibility.requestHost,\n authHost: compatibility.authHost,\n expectedGatewayHost: compatibility.expectedGatewayHost,\n };\n }\n const expiryReason = resolveSessionExpiryReason(input.session);\n if (expiryReason) {\n return {\n status: \"dropped\",\n reason: expiryReason,\n requestHost: compatibility.requestHost,\n authHost: compatibility.authHost,\n expectedGatewayHost: compatibility.expectedGatewayHost,\n };\n }\n return {\n status: \"attachable\",\n token,\n tokenType: normalizeTokenType(input.session.tokenType),\n };\n}\n\nexport function requireAuthTokenAttachment(input: {\n session: StoredAuthSession;\n requestUrl: string;\n}): Extract<AuthTokenAttachment, { status: \"attachable\" }> {\n const attachment = resolveAuthTokenAttachment(input);\n if (attachment.status === \"dropped\") {\n throw createAuthRequestCredentialError(attachment);\n }\n return attachment;\n}\n\nasync function attachAuthHeader(\n headers: Record<string, string>,\n input: RequestAuthHeadersInput\n): Promise<void> {\n const session = await resolveAuthSessionForHeaders(input);\n if (\n input.expectedOwnerUserId &&\n session?.user?.id !== input.expectedOwnerUserId\n ) {\n throw new Error(\"auth.session_owner_changed\");\n }\n if (session === null) {\n // No stored credentials exist, so there is nothing to strip: the caller\n // is knowingly sending an unauthenticated request.\n return;\n }\n\n let attachment: Extract<AuthTokenAttachment, { status: \"attachable\" }>;\n try {\n attachment = requireAuthTokenAttachment({\n session,\n requestUrl: input.requestUrl,\n });\n } catch (error) {\n if (error instanceof AuthRequestCredentialError) {\n logRejectedAuthRequestCredential(error);\n }\n throw error;\n }\n headers[AUTHORIZATION_HEADER] = `${attachment.tokenType} ${attachment.token}`;\n}\n\nfunction logRejectedAuthRequestCredential(\n error: AuthRequestCredentialError\n): void {\n console.error(\"[openmeld.auth.request_credential_rejected]\", {\n authHost: error.authHost,\n expectedGatewayHost: error.expectedGatewayHost,\n reason: error.reason,\n requestHost: error.requestHost,\n });\n}\n\nasync function resolveAuthSessionForHeaders(\n input: RequestAuthHeadersInput\n): Promise<StoredAuthSession | null> {\n if (input.authSession !== undefined) {\n return input.authSession;\n }\n\n const sessionState = await getAuthSessionState({ refreshExpired: true });\n if (sessionState.state === \"missing\") {\n return null;\n }\n if (sessionState.state !== \"valid\" || sessionState.session === null) {\n const error = new AuthRequestCredentialError({\n retryAfterMs: sessionState.retryAfterMs,\n authHost: null,\n expectedGatewayHost: null,\n reason:\n sessionState.reasonCode ??\n (sessionState.state === \"revoked\"\n ? \"session_revoked\"\n : \"session_invalid\"),\n requestHost: parseRequestHost(input.requestUrl),\n });\n logRejectedAuthRequestCredential(error);\n throw error;\n }\n\n return sessionState.session;\n}\n\nfunction createAuthRequestCredentialError(\n attachment: DroppedAuthTokenAttachment\n): AuthRequestCredentialError {\n return new AuthRequestCredentialError({\n authHost: attachment.authHost,\n expectedGatewayHost: attachment.expectedGatewayHost,\n reason: attachment.reason,\n requestHost: attachment.requestHost,\n droppedAttachment: attachment,\n });\n}\n\nfunction parseRequestHost(requestUrl: string): string | null {\n try {\n return new URL(requestUrl).host || null;\n } catch {\n return null;\n }\n}\n\nfunction normalizeAccessToken(session: StoredAuthSession): string {\n return String(session.accessToken ?? \"\").trim();\n}\n\nfunction normalizeTokenType(tokenType: string | undefined): string {\n const normalized = String(tokenType ?? \"\").trim();\n return normalized.length > 0 ? normalized : DEFAULT_TOKEN_TYPE;\n}\n\nfunction resolveSessionExpiryReason(\n session: StoredAuthSession\n): \"session_expired\" | \"session_expiry_invalid\" | null {\n const eligibility = resolveAuthSessionExpiryEligibility(session.expiresAt);\n if (eligibility.status === \"invalid\") {\n return \"session_expiry_invalid\";\n }\n return eligibility.status === \"expired\" ? \"session_expired\" : null;\n}\n\nexport function canAttachAuthTokenToRequest(\n session: StoredAuthSession,\n requestUrl: string\n): boolean {\n return (\n resolveAuthTokenAttachment({\n session,\n requestUrl,\n }).status === \"attachable\"\n );\n}\n","import {\n DEFAULT_SPACE_CONVERSATION_VALIDATE_TIMEOUT_MS,\n DEFAULT_SPACE_REQUEST_TIMEOUT_MS,\n MAX_SPACE_REQUEST_TIMEOUT_MS,\n MIN_SPACE_REQUEST_TIMEOUT_MS,\n} from \"../strategy-constants\";\n\nconst SPACE_REQUEST_TIMEOUT_ENV_KEY = \"OPENMELD_SPACE_REQUEST_TIMEOUT_MS\";\n\nexport function resolveSpaceRequestTimeoutMs(override?: number): number {\n if (isFinitePositiveNumber(override)) {\n return clampSpaceRequestTimeoutMs(override);\n }\n\n const fromEnv = Number.parseInt(\n String(process.env[SPACE_REQUEST_TIMEOUT_ENV_KEY] ?? \"\"),\n 10\n );\n if (isFinitePositiveNumber(fromEnv)) {\n return clampSpaceRequestTimeoutMs(fromEnv);\n }\n\n return DEFAULT_SPACE_REQUEST_TIMEOUT_MS;\n}\n\nexport function resolveSpaceRequestTimeoutMsForDiagnostics(): number {\n return resolveSpaceRequestTimeoutMs(undefined);\n}\n\nexport function resolveSpaceConversationValidateTimeoutMs(): number {\n return Math.max(\n resolveSpaceRequestTimeoutMs(undefined),\n DEFAULT_SPACE_CONVERSATION_VALIDATE_TIMEOUT_MS\n );\n}\n\nfunction clampSpaceRequestTimeoutMs(value: number): number {\n const normalized = Math.trunc(value);\n return Math.max(\n MIN_SPACE_REQUEST_TIMEOUT_MS,\n Math.min(MAX_SPACE_REQUEST_TIMEOUT_MS, normalized)\n );\n}\n\nfunction isFinitePositiveNumber(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0;\n}\n","import {\n resolveSpaceRequestTimeoutMs,\n resolveSpaceRequestTimeoutMsForDiagnostics as resolveSpaceRequestTimeoutMsForCliDiagnostics,\n} from \"./request-timeout\";\n\nexport async function fetchSpaceRequestWithTimeout(input: {\n url: string;\n operation: string;\n init?: RequestInit;\n timeoutMs?: number;\n}): Promise<Response> {\n const timeoutMs = resolveSpaceRequestTimeoutMs(input.timeoutMs);\n const timeoutSignal = AbortSignal.timeout(timeoutMs);\n const composed = composeAbortSignals(input.init?.signal, timeoutSignal);\n\n try {\n try {\n return await fetch(input.url, {\n ...input.init,\n signal: composed.signal,\n });\n } catch (error) {\n // A keep-alive connection that a proxy silently dropped fails exactly\n // once and undici evicts it; the retry rides a fresh connection. This\n // is what keeps a long-lived service working behind flaky proxies\n // without asking users to touch their network config.\n if (\n timeoutSignal.aborted ||\n composed.signal.aborted ||\n !shouldWrapNetworkRequestError(error)\n ) {\n throw error;\n }\n return await fetch(input.url, {\n ...input.init,\n signal: composed.signal,\n });\n }\n } catch (error) {\n if (timeoutSignal.aborted) {\n throw createSpaceRequestTimeoutError({\n operation: input.operation,\n timeoutMs,\n cause: error,\n });\n }\n if (shouldWrapNetworkRequestError(error)) {\n throw createSpaceRequestNetworkError({\n operation: input.operation,\n url: input.url,\n cause: error,\n });\n }\n throw error;\n } finally {\n composed.cleanup();\n }\n}\n\nexport function resolveSpaceRequestTimeoutMsForDiagnostics(): number {\n return resolveSpaceRequestTimeoutMsForCliDiagnostics();\n}\n\nfunction createSpaceRequestTimeoutError(input: {\n operation: string;\n timeoutMs: number;\n cause: unknown;\n}): Error {\n const error = new Error(\n `${input.operation} request timed out after ${input.timeoutMs}ms`,\n { cause: input.cause }\n ) as Error & { code?: string };\n error.code = \"network.timeout\";\n return error;\n}\n\nfunction createSpaceRequestNetworkError(input: {\n operation: string;\n url: string;\n cause: unknown;\n}): Error {\n const error = new Error(\n `${input.operation} request could not reach ${describeRequestTarget(input.url)} (${toErrorMessage(input.cause)})`,\n { cause: input.cause }\n ) as Error & { code?: string };\n error.code = \"network.request_failed\";\n return error;\n}\n\nfunction composeAbortSignals(\n parent: AbortSignal | null | undefined,\n timeout: AbortSignal\n): { signal: AbortSignal; cleanup: () => void } {\n if (!parent) {\n return {\n signal: timeout,\n cleanup: () => undefined,\n };\n }\n\n if (parent.aborted || timeout.aborted) {\n const controller = new AbortController();\n controller.abort();\n return {\n signal: controller.signal,\n cleanup: () => undefined,\n };\n }\n\n const controller = new AbortController();\n const abort = () => {\n controller.abort();\n };\n\n parent.addEventListener(\"abort\", abort, { once: true });\n timeout.addEventListener(\"abort\", abort, { once: true });\n\n return {\n signal: controller.signal,\n cleanup: () => {\n parent.removeEventListener(\"abort\", abort);\n timeout.removeEventListener(\"abort\", abort);\n },\n };\n}\n\nfunction describeRequestTarget(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return url;\n }\n}\n\nfunction toErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n const message = error.message.trim();\n return message.length > 0 ? message : \"request failed\";\n }\n const message = String(error ?? \"\").trim();\n return message.length > 0 ? message : \"request failed\";\n}\n\nfunction shouldWrapNetworkRequestError(error: unknown): boolean {\n if (error instanceof TypeError) {\n return true;\n }\n if (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n typeof error.code === \"string\" &&\n error.code.startsWith(\"ERR_SSL_\")\n ) {\n return true;\n }\n const message = toErrorMessage(error).toLowerCase();\n return (\n message.includes(\"fetch failed\") ||\n message.includes(\"failed to fetch\") ||\n message.includes(\"network request failed\") ||\n message.includes(\"ssl_decryption_failed_or_bad_record_mac\")\n );\n}\n","import {\n createOpenMeldApiClient,\n type OpenMeldApiClientFoundation,\n} from \"@openmeld/api-client\";\nimport {\n buildOpenMeldRequestContextHeaders,\n OPENMELD_HEADER_REQUESTED_ORGANIZATION_ID,\n} from \"@openmeld/gateway-contract\";\nimport { buildRequestAuthHeaders } from \"../config/request-headers\";\nimport { fetchSpaceRequestWithTimeout } from \"./fetch-with-timeout\";\n\nexport function createCliApiClientFoundation(\n baseUrl: string,\n options: {\n onAuthHeadersResolved?: (headers: Record<string, string>) => void;\n organizationId?: string;\n expectedOwnerUserId?: string;\n } = {}\n): OpenMeldApiClientFoundation {\n return createOpenMeldApiClient({\n baseUrl,\n transport: async (request) =>\n await fetchSpaceRequestWithTimeout({\n url: request.url,\n operation: request.operation,\n init: request.init,\n timeoutMs: request.timeoutMs,\n }),\n getAuthHeaders: async ({ requestUrl }) => {\n const headers = await buildRequestAuthHeaders({\n requestUrl,\n expectedOwnerUserId: options.expectedOwnerUserId,\n });\n if (options.organizationId) {\n headers[OPENMELD_HEADER_REQUESTED_ORGANIZATION_ID] =\n options.organizationId;\n }\n options.onAuthHeadersResolved?.(headers);\n return headers;\n },\n getRequestContextHeaders: async ({ requestContext, spacePassword }) =>\n buildOpenMeldRequestContextHeaders({\n requestContext,\n ...(spacePassword === undefined ? {} : { spacePassword }),\n }),\n });\n}\n"],"mappings":";;;;;;;;AAqBA,SAAgB,gCAAgC,OAGnB;CAC3B,MAAM,aAAa,eAAe,MAAM,UAAU;CAClD,IAAI,CAAC,YACH,OAAO;EACL,YAAY;EACZ,QAAQ;EACR,aAAa;EACb,UAAU;EACV,qBAAqB;CACvB;CAGF,MAAM,cAAc,eAAe,MAAM,QAAQ,WAAW;CAC5D,IAAI,CAAC,aACH,O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AAE,gBAAgB,oBACjD,mCAAmC;GACjC;GACA,GAAI,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc;EACzD,CAAC;CACL,CAAC;AACH"}
|
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
import { f as toSpaceMetaUrl } from "./urls-CY2uzH2-.js";
|
|
4
4
|
import { Z as openMeldManagedBinaryPath, ct as resolveOpenMeldEnvPreset } from "./lock-Bsl_ElWy.js";
|
|
5
|
-
import { Wr as spaceMemberDirectoryEntrySchema, Yn as OPENMELD_HEADER_REQUEST_ID, fr as gatewayErrorEnvelopeSchema, oi as spaceMetaSchema, sn as createSpaceApi, t as OpenMeldApiClientHttpError } from "./dist-
|
|
5
|
+
import { Wr as spaceMemberDirectoryEntrySchema, Yn as OPENMELD_HEADER_REQUEST_ID, fr as gatewayErrorEnvelopeSchema, oi as spaceMetaSchema, sn as createSpaceApi, t as OpenMeldApiClientHttpError } from "./dist-BewA9srP.js";
|
|
6
6
|
import { Z as openMeldSpaceEgressActionSchema } from "./runtime-transport-0F5E6So6.js";
|
|
7
7
|
import { g as isSelfWakeSpaceAction } from "./dist-ChS52b_E.js";
|
|
8
|
-
import { _n as OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV, gn as OPENMELD_DISPATCH_RUNTIME_MODE_ENV, hn as OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV, pn as DISPATCH_OWNED_RUNTIME_MODE, vn as OPENMELD_SPACE_ACTION_TOOL_COMMAND_PATH_ENV, yn as OPENMELD_USER_FACING_CLI_COMMAND_ENV } from "./daemon-frame-transport-
|
|
8
|
+
import { _n as OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV, gn as OPENMELD_DISPATCH_RUNTIME_MODE_ENV, hn as OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV, pn as DISPATCH_OWNED_RUNTIME_MODE, vn as OPENMELD_SPACE_ACTION_TOOL_COMMAND_PATH_ENV, yn as OPENMELD_USER_FACING_CLI_COMMAND_ENV } from "./daemon-frame-transport-D-4StENt.js";
|
|
9
9
|
import { n as resolveOpenMeldDistribution } from "./distribution-BDQT2ilb.js";
|
|
10
10
|
import { h as daemonRuntimeRootPath } from "./daemon-state-B44aq2nm.js";
|
|
11
|
-
import { n as fetchSpaceRequestWithTimeout, s as buildOpenMeldRequestContextHeadersWithAuth, t as createCliApiClientFoundation } from "./api-client-foundation-
|
|
11
|
+
import { n as fetchSpaceRequestWithTimeout, s as buildOpenMeldRequestContextHeadersWithAuth, t as createCliApiClientFoundation } from "./api-client-foundation-D-Cb6EVg.js";
|
|
12
12
|
import { randomUUID } from "node:crypto";
|
|
13
13
|
import { delimiter, dirname, join, resolve } from "node:path";
|
|
14
14
|
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
@@ -655,4 +655,4 @@ function createCliSpaceApi(baseUrl, options = {}) {
|
|
|
655
655
|
//#endregion
|
|
656
656
|
export { readDispatchSpaceActionContextForReceiptFromEnv as _, parseSpaceMetaResponse as a, supersedeDispatchSpaceActionRecordForReconsideration as b, readGatewayTextResponse as c, assertDispatchOwnedRuntimePublicWriteAllowed as d, buildDispatchOwnedRuntimeEnv as f, createDispatchSpaceActionContext as g, OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV as h, parseSpaceMetaPayload as i, toStructuredGatewayFailure as l, DispatchSpaceActionClosedError as m, fetchSpaceMeta as n, GatewayHttpError as o, readDispatchOwnedRuntimeGuard as p, updateSpaceMeta as r, readGatewayJsonResponse as s, createCliSpaceApi as t, parseJsonResponse as u, readDispatchSpaceActionContextFromEnv as v, writeDispatchSpaceActionRecord as x, readDispatchSpaceActionRecord as y };
|
|
657
657
|
|
|
658
|
-
//# sourceMappingURL=cli-space-api-
|
|
658
|
+
//# sourceMappingURL=cli-space-api-B2l1xMPn.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli-space-api-skevaFSC.js","names":["normalizeOptionalText","normalizeOptionalText","record"],"sources":["../src/runtime/dispatch-space-action-context.ts","../src/runtime/dispatch-owned-runtime.ts","../src/space/api-json.ts","../src/space/gateway-response.ts","../src/space/space-meta-response.ts","../src/space/meta-api.ts","../src/space/cli-space-api.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport {\n openMeldSpaceEgressActionSchema,\n spaceMemberDirectoryEntrySchema,\n} from \"@openmeld/schemas\";\nimport type {\n DispatchSpaceActionClosedReasonCode,\n OpenMeldSpaceEgressAction,\n SpaceContract,\n SpaceMemberDirectoryEntry,\n} from \"@openmeld/schemas/types\";\nimport { isSelfWakeSpaceAction } from \"@openmeld/space-mesh\";\nimport { daemonRuntimeRootPath } from \"../config/daemon-state\";\nimport type { OpenMeldPathResolutionInput } from \"../config/paths\";\nimport {\n DISPATCH_OWNED_RUNTIME_MODE,\n OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV,\n OPENMELD_DISPATCH_RUNTIME_MODE_ENV,\n OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV,\n} from \"./dispatch-runtime-env\";\n\nexport const OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV =\n \"OPENMELD_SPACE_ACTION_CONTEXT_PATH\";\n\n/** The local action context is known expired/closed/mismatched: a new ordinary action must be rejected, never recorded. */\nexport class DispatchSpaceActionClosedError extends Error {\n readonly receipt = \"rejected_closed\" as const;\n readonly reasonCode: DispatchSpaceActionClosedReasonCode;\n constructor(\n reasonCode: DispatchSpaceActionClosedReasonCode,\n message: string\n ) {\n super(message);\n this.name = \"DispatchSpaceActionClosedError\";\n this.reasonCode = reasonCode;\n }\n}\n\nconst DISPATCH_SPACE_ACTION_CONTEXT_VERSION = 1 as const;\nconst DISPATCH_SPACE_ACTION_RECORD_VERSION = 1 as const;\nconst DEFAULT_CONTEXT_TTL_MS = 12 * 60 * 60 * 1000;\n\nexport type DispatchSpaceActionSendTargetReference =\n | {\n status: \"loaded\";\n projection: SpaceMemberDirectoryEntry[];\n referenceLines: string[];\n }\n | {\n status: \"failed\";\n errorMessage: string;\n projection: null;\n referenceLines: [];\n };\n\nexport type DispatchSpaceActionContext = {\n workingCopyId?: string;\n version: typeof DISPATCH_SPACE_ACTION_CONTEXT_VERSION;\n actionRecordPath: string;\n attemptId: string;\n contextId: string;\n dispatchId: string;\n expiresAtMs: number;\n nonce: string;\n replyToSignalId: string | null;\n sendTargetReference: DispatchSpaceActionSendTargetReference;\n sourceEventId: string;\n spaceContractSnapshot: Pick<\n SpaceContract,\n \"allowedActions\" | \"publicationMode\"\n > | null;\n spaceId: string;\n targetProfileId: string;\n taskId: string;\n};\n\nexport type DispatchSpaceActionRecord = {\n version: typeof DISPATCH_SPACE_ACTION_RECORD_VERSION;\n action: OpenMeldSpaceEgressAction;\n command: string;\n contextId: string;\n createdAtMs: number;\n nonce: string;\n};\n\nexport type DispatchSpaceActionRecordReadResult =\n | {\n status: \"missing\";\n }\n | {\n errorMessage: string;\n status: \"invalid\";\n }\n | {\n record: DispatchSpaceActionRecord;\n status: \"loaded\";\n };\n\nexport function createDispatchSpaceActionContext(input: {\n workingCopyId?: string;\n attemptId: string;\n dispatchId: string;\n env?: Record<string, string | undefined>;\n pathInput?: OpenMeldPathResolutionInput;\n replyToSignalId?: string | null;\n sendTargetReference: DispatchSpaceActionSendTargetReference;\n sourceEventId: string;\n spaceContractSnapshot:\n | Pick<SpaceContract, \"allowedActions\" | \"publicationMode\">\n | null\n | undefined;\n spaceId: string;\n targetProfileId: string;\n taskId: string;\n ttlMs?: number;\n}): {\n context: DispatchSpaceActionContext;\n contextPath: string;\n} {\n const contextId = randomUUID();\n const nonce = randomUUID();\n const contextDir = join(\n daemonRuntimeRootPath(input.pathInput ?? { env: input.env }),\n \"dispatch-space-actions\",\n `${Date.now().toString(36)}-${contextId}`\n );\n mkdirSync(contextDir, { recursive: true, mode: 0o700 });\n chmodSync(contextDir, 0o700);\n\n const contextPath = join(contextDir, \"context.json\");\n const actionRecordPath = join(contextDir, \"action.json\");\n const context: DispatchSpaceActionContext = {\n ...(input.workingCopyId ? { workingCopyId: input.workingCopyId } : {}),\n version: DISPATCH_SPACE_ACTION_CONTEXT_VERSION,\n actionRecordPath,\n attemptId: input.attemptId,\n contextId,\n dispatchId: input.dispatchId,\n expiresAtMs: Date.now() + (input.ttlMs ?? DEFAULT_CONTEXT_TTL_MS),\n nonce,\n replyToSignalId: normalizeOptionalText(input.replyToSignalId),\n sendTargetReference: input.sendTargetReference,\n sourceEventId: input.sourceEventId,\n spaceContractSnapshot: input.spaceContractSnapshot\n ? {\n allowedActions: input.spaceContractSnapshot.allowedActions,\n publicationMode: input.spaceContractSnapshot.publicationMode,\n }\n : null,\n spaceId: input.spaceId,\n targetProfileId: input.targetProfileId,\n taskId: input.taskId,\n };\n\n writeJsonFileExclusive(contextPath, context);\n return { context, contextPath };\n}\n\nexport function readDispatchSpaceActionContextFromEnv(\n env: NodeJS.ProcessEnv = process.env\n): DispatchSpaceActionContext {\n const context = readDispatchSpaceActionContextForReceiptFromEnv(env);\n assertContextActive(context, Date.now());\n return context;\n}\n\n// Expiry does not erase a prior receipt. Callers may use this context to compare\n// an exact existing action; writeDispatchSpaceActionRecord still rejects new\n// actions after expiry. File reads/uploads and target listing use the active\n// context reader instead.\nexport function readDispatchSpaceActionContextForReceiptFromEnv(\n env: NodeJS.ProcessEnv = process.env\n): DispatchSpaceActionContext {\n const contextPath = normalizeOptionalText(\n env[OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV]\n );\n if (!contextPath) {\n throw new Error(\n \"No active OpenMeld Space Action dispatch context was found. Use this command inside an OpenMeld Space Wake dispatch.\"\n );\n }\n const context = readDispatchSpaceActionContext(contextPath);\n assertDispatchRuntimeEnvMatchesContext({ context, env });\n return context;\n}\n\nexport function readDispatchSpaceActionContext(\n contextPath: string\n): DispatchSpaceActionContext {\n return parseDispatchSpaceActionContext(readJsonFile(contextPath));\n}\n\nexport function writeDispatchSpaceActionRecord(input: {\n action: OpenMeldSpaceEgressAction;\n command: string;\n context: DispatchSpaceActionContext;\n nowMs?: number;\n}): DispatchSpaceActionRecord {\n const parsedAction = openMeldSpaceEgressActionSchema.safeParse(input.action);\n if (!parsedAction.success) {\n throw parsedAction.error;\n }\n if (isSelfWakeSpaceAction(parsedAction.data, input.context.targetProfileId)) {\n throw new Error(\n \"An Agent cannot Wake itself. To reply to the current message, omit wakeTargets (CLI: --wake) and submit the reply again. No action was recorded.\"\n );\n }\n\n const existing = readDispatchSpaceActionRecord({ context: input.context });\n if (existing.status === \"invalid\") {\n throw new Error(existing.errorMessage);\n }\n if (\n existing.status === \"loaded\" &&\n isDeepStrictEqual(existing.record.action, parsedAction.data)\n ) {\n return existing.record;\n }\n assertContextActive(input.context, input.nowMs ?? Date.now());\n\n const record: DispatchSpaceActionRecord = {\n version: DISPATCH_SPACE_ACTION_RECORD_VERSION,\n action: parsedAction.data,\n command: input.command,\n contextId: input.context.contextId,\n createdAtMs: input.nowMs ?? Date.now(),\n nonce: input.context.nonce,\n };\n try {\n writeJsonFileExclusive(input.context.actionRecordPath, record);\n } catch (error) {\n if (isNodeErrorCode(error, \"EEXIST\")) {\n const existing = readDispatchSpaceActionRecord({\n context: input.context,\n });\n // A lost acknowledgement may cause the same proposal to be submitted\n // again. Acknowledge that record, never replace it or accept a new action.\n if (\n existing.status === \"loaded\" &&\n isDeepStrictEqual(existing.record.action, parsedAction.data)\n ) {\n return existing.record;\n }\n throw new Error(\n \"An OpenMeld Space Action has already been recorded for this dispatch. A Wake can only have one final Space action.\"\n );\n }\n throw error;\n }\n return record;\n}\n\nexport function readDispatchSpaceActionRecord(input: {\n context: DispatchSpaceActionContext;\n nowMs?: number;\n}): DispatchSpaceActionRecordReadResult {\n if (!existsSync(input.context.actionRecordPath)) {\n return { status: \"missing\" };\n }\n try {\n const record = parseDispatchSpaceActionRecord(\n readJsonFile(input.context.actionRecordPath)\n );\n if (\n record.contextId !== input.context.contextId ||\n record.nonce !== input.context.nonce\n ) {\n return {\n status: \"invalid\",\n errorMessage:\n \"OpenMeld Space Action record does not match the active dispatch context.\",\n };\n }\n if (record.createdAtMs > input.context.expiresAtMs) {\n return {\n status: \"invalid\",\n errorMessage:\n \"OpenMeld Space Action record was created after the active dispatch context expired.\",\n };\n }\n return { status: \"loaded\", record };\n } catch (error) {\n return {\n status: \"invalid\",\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nexport function supersedeDispatchSpaceActionRecordForReconsideration(input: {\n context: DispatchSpaceActionContext;\n nowMs?: number;\n}): { archivedPath: string; record: DispatchSpaceActionRecord } | null {\n const readResult = readDispatchSpaceActionRecord(input);\n if (readResult.status === \"missing\") {\n return null;\n }\n if (readResult.status === \"invalid\") {\n throw new Error(readResult.errorMessage);\n }\n const archivedPath = `${input.context.actionRecordPath}.superseded-${String(input.nowMs ?? Date.now())}-${randomUUID()}`;\n renameSync(input.context.actionRecordPath, archivedPath);\n return { archivedPath, record: readResult.record };\n}\n\nfunction parseDispatchSpaceActionContext(\n value: unknown\n): DispatchSpaceActionContext {\n const record = toRecord(value, \"OpenMeld Space Action context\");\n const version = record.version;\n if (version !== DISPATCH_SPACE_ACTION_CONTEXT_VERSION) {\n throw new Error(\"Unsupported OpenMeld Space Action context version.\");\n }\n const sendTargetReference = parseSendTargetReference(\n record.sendTargetReference\n );\n return {\n version,\n actionRecordPath: requiredString(\n record.actionRecordPath,\n \"actionRecordPath\"\n ),\n attemptId: requiredString(record.attemptId, \"attemptId\"),\n contextId: requiredString(record.contextId, \"contextId\"),\n dispatchId: requiredString(record.dispatchId, \"dispatchId\"),\n expiresAtMs: requiredFiniteNumber(record.expiresAtMs, \"expiresAtMs\"),\n nonce: requiredString(record.nonce, \"nonce\"),\n replyToSignalId: optionalString(record.replyToSignalId),\n sendTargetReference,\n sourceEventId: requiredString(record.sourceEventId, \"sourceEventId\"),\n spaceContractSnapshot: parseSpaceContractSnapshot(\n record.spaceContractSnapshot\n ),\n spaceId: requiredString(record.spaceId, \"spaceId\"),\n targetProfileId: requiredString(record.targetProfileId, \"targetProfileId\"),\n taskId: requiredString(record.taskId, \"taskId\"),\n ...(record.workingCopyId\n ? { workingCopyId: requiredString(record.workingCopyId, \"workingCopyId\") }\n : {}),\n };\n}\n\nfunction assertDispatchRuntimeEnvMatchesContext(input: {\n context: DispatchSpaceActionContext;\n env: NodeJS.ProcessEnv;\n}): void {\n const mode = normalizeOptionalText(\n input.env[OPENMELD_DISPATCH_RUNTIME_MODE_ENV]\n );\n if (mode !== DISPATCH_OWNED_RUNTIME_MODE) {\n return;\n }\n\n const envDispatchId = normalizeOptionalText(\n input.env[OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV]\n );\n if (!envDispatchId) {\n throw new Error(\n \"OpenMeld Space Action dispatch runtime is missing the active dispatch ID.\"\n );\n }\n if (envDispatchId !== input.context.dispatchId) {\n throw new DispatchSpaceActionClosedError(\n \"space_action.context_mismatch\",\n \"OpenMeld Space Action dispatch context does not match the active dispatch runtime.\"\n );\n }\n\n const envTargetProfileId = normalizeOptionalText(\n input.env[OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV]\n );\n if (!envTargetProfileId) {\n throw new Error(\n \"OpenMeld Space Action dispatch runtime is missing the active target profile ID.\"\n );\n }\n if (envTargetProfileId !== input.context.targetProfileId) {\n throw new DispatchSpaceActionClosedError(\n \"space_action.context_mismatch\",\n \"OpenMeld Space Action target profile does not match the active dispatch runtime.\"\n );\n }\n}\n\nfunction parseDispatchSpaceActionRecord(\n value: unknown\n): DispatchSpaceActionRecord {\n const record = toRecord(value, \"OpenMeld Space Action record\");\n const version = record.version;\n if (version !== DISPATCH_SPACE_ACTION_RECORD_VERSION) {\n throw new Error(\"Unsupported OpenMeld Space Action record version.\");\n }\n const parsedAction = openMeldSpaceEgressActionSchema.safeParse(record.action);\n if (!parsedAction.success) {\n throw parsedAction.error;\n }\n return {\n version,\n action: parsedAction.data,\n command: requiredString(record.command, \"command\"),\n contextId: requiredString(record.contextId, \"contextId\"),\n createdAtMs: requiredFiniteNumber(record.createdAtMs, \"createdAtMs\"),\n nonce: requiredString(record.nonce, \"nonce\"),\n };\n}\n\nfunction parseSendTargetReference(\n value: unknown\n): DispatchSpaceActionSendTargetReference {\n const record = toRecord(value, \"sendTargetReference\");\n if (record.status === \"loaded\") {\n if (!Array.isArray(record.projection)) {\n throw new Error(\n \"OpenMeld Space Action send target projection must be an array.\"\n );\n }\n return {\n status: \"loaded\",\n projection: record.projection.map(parseSendTargetProjectionEntry),\n referenceLines: parseStringArray(record.referenceLines),\n };\n }\n if (record.status === \"failed\") {\n return {\n status: \"failed\",\n errorMessage: requiredString(record.errorMessage, \"errorMessage\"),\n projection: null,\n referenceLines: [],\n };\n }\n throw new Error(\n \"Invalid OpenMeld Space Action send target reference status.\"\n );\n}\n\nfunction parseSendTargetProjectionEntry(\n value: unknown,\n index: number\n): SpaceMemberDirectoryEntry {\n const parsed = spaceMemberDirectoryEntrySchema.safeParse(value);\n if (!parsed.success) {\n throw new Error(\n `OpenMeld Space Action target projection entry ${index} is not a valid Space member directory entry.`\n );\n }\n return parsed.data;\n}\n\nfunction parseSpaceContractSnapshot(\n value: unknown\n): Pick<SpaceContract, \"allowedActions\" | \"publicationMode\"> | null {\n if (value === null || value === undefined) {\n return null;\n }\n const record = toRecord(value, \"spaceContractSnapshot\");\n return {\n allowedActions: Array.isArray(record.allowedActions)\n ? (record.allowedActions as SpaceContract[\"allowedActions\"])\n : [],\n publicationMode:\n record.publicationMode === \"raw_context_sharing\"\n ? \"raw_context_sharing\"\n : \"collaboration\",\n };\n}\n\nfunction assertContextActive(\n context: DispatchSpaceActionContext,\n nowMs: number\n): void {\n if (nowMs > context.expiresAtMs) {\n throw new DispatchSpaceActionClosedError(\n \"space_action.context_expired\",\n \"The OpenMeld Space Action dispatch context has expired.\"\n );\n }\n}\n\nfunction readJsonFile(path: string): unknown {\n return JSON.parse(readFileSync(path, \"utf8\")) as unknown;\n}\n\nfunction writeJsonFileExclusive(path: string, value: unknown): void {\n writeFileSync(path, `${JSON.stringify(value, null, 2)}\\n`, {\n encoding: \"utf8\",\n flag: \"wx\",\n mode: 0o600,\n });\n chmodSync(path, 0o600);\n}\n\nfunction toRecord(value: unknown, label: string): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(`${label} must be a JSON object.`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction requiredString(value: unknown, fieldName: string): string {\n const normalized = normalizeOptionalText(value);\n if (!normalized) {\n throw new Error(`${fieldName} must be a non-empty string.`);\n }\n return normalized;\n}\n\nfunction requiredFiniteNumber(value: unknown, fieldName: string): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n throw new Error(`${fieldName} must be a finite number.`);\n }\n return value;\n}\n\nfunction optionalString(value: unknown): string | null {\n if (value === null || value === undefined) {\n return null;\n }\n return normalizeOptionalText(value);\n}\n\nfunction parseStringArray(value: unknown): string[] {\n if (!Array.isArray(value)) {\n return [];\n }\n return value\n .map((item) => normalizeOptionalText(item))\n .filter((item): item is string => Boolean(item));\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction isNodeErrorCode(error: unknown, code: string): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: unknown }).code === code\n );\n}\n","import {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n writeFileSync,\n} from \"node:fs\";\nimport { delimiter, dirname, join, resolve } from \"node:path\";\nimport { daemonRuntimeRootPath } from \"../config/daemon-state\";\nimport {\n type OpenMeldPathResolutionInput,\n openMeldManagedBinaryPath,\n resolveOpenMeldEnvPreset,\n} from \"../config/paths\";\nimport {\n DISPATCH_OWNED_RUNTIME_MODE,\n OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV,\n OPENMELD_DISPATCH_RUNTIME_MODE_ENV,\n OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV,\n OPENMELD_SPACE_ACTION_TOOL_COMMAND_PATH_ENV,\n OPENMELD_USER_FACING_CLI_COMMAND_ENV,\n} from \"./dispatch-runtime-env\";\nimport { OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV } from \"./dispatch-space-action-context\";\nimport {\n type OpenMeldDistribution,\n resolveOpenMeldDistribution,\n} from \"./distribution\";\n\nconst DISPATCH_OWNED_RUNTIME_CLI_SHIM_DIRNAME = \"dispatch-owned-cli\";\nconst DISPATCH_SPACE_ACTION_CLI_SHIM_DIRNAME = \"bin\";\nconst OPENMELD_ENV_PRESET_ENV = \"OPENMELD_ENV_PRESET\";\nconst DISPATCH_OWNED_RUNTIME_CLI_COMMAND_NAMES = [\n \"openmeld\",\n \"openmeld-dev\",\n \"openmeld-canary\",\n] as const;\n\nexport type DispatchOwnedRuntimeGuard = {\n active: boolean;\n dispatchId: string | null;\n targetProfileId: string | null;\n};\n\nexport function buildDispatchOwnedRuntimeEnv(input: {\n dispatchId: string;\n targetProfileId: string;\n distribution?: OpenMeldDistribution;\n env?: Record<string, string | undefined>;\n cliEntryPath?: string;\n spaceActionContextPath?: string | null;\n}): Record<string, string | undefined> {\n // Provider overrides are not a replacement for the carrier's lane. Keep\n // these non-secret installation selectors without copying unrelated Service\n // credentials into the provider environment.\n const env = {\n OPENMELD_HOME: process.env.OPENMELD_HOME,\n OPENMELD_ENV_PRESET: process.env.OPENMELD_ENV_PRESET,\n ...(input.env ?? {}),\n };\n const currentPath = normalizeOptionalText(\n input.env?.PATH ?? process.env.PATH\n );\n const shimDir = ensureDispatchOwnedRuntimeCliShims({\n cliEntryPath: input.cliEntryPath,\n dispatchId: input.dispatchId,\n distribution: input.distribution,\n env,\n spaceActionContextPath: input.spaceActionContextPath,\n targetProfileId: input.targetProfileId,\n });\n const actionCommand = resolveDispatchOwnedRuntimeActionCliEntryCommand({\n env,\n });\n return {\n ...env,\n PATH: prependPathEntry({\n currentPath,\n nextEntry: shimDir,\n }),\n [OPENMELD_DISPATCH_RUNTIME_MODE_ENV]: DISPATCH_OWNED_RUNTIME_MODE,\n [OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV]: input.dispatchId,\n [OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV]: input.targetProfileId,\n [OPENMELD_USER_FACING_CLI_COMMAND_ENV]: actionCommand,\n [OPENMELD_SPACE_ACTION_TOOL_COMMAND_PATH_ENV]: join(shimDir, actionCommand),\n [OPENMELD_ENV_PRESET_ENV]: resolveDispatchOwnedRuntimeEnvPreset({\n env,\n }),\n ...(input.spaceActionContextPath\n ? {\n [OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV]:\n input.spaceActionContextPath,\n }\n : {}),\n };\n}\n\nexport function resolveDispatchOwnedRuntimeActionCliEntryCommand(\n input: OpenMeldPathResolutionInput = {}\n): \"openmeld\" | \"openmeld-dev\" | \"openmeld-canary\" {\n const preset = resolveOpenMeldEnvPreset(input);\n if (preset === \"dev-local\") {\n return \"openmeld-dev\";\n }\n if (preset === \"canary\") {\n return \"openmeld-canary\";\n }\n return \"openmeld\";\n}\n\nexport function resolveDispatchOwnedRuntimeCliShimDir(\n input: OpenMeldPathResolutionInput & {\n spaceActionContextPath?: string | null;\n } = {}\n): string {\n const spaceActionContextPath = normalizeOptionalText(\n input.spaceActionContextPath\n );\n if (spaceActionContextPath) {\n return join(\n dirname(spaceActionContextPath),\n DISPATCH_SPACE_ACTION_CLI_SHIM_DIRNAME\n );\n }\n return join(\n daemonRuntimeRootPath(input),\n \"bin\",\n DISPATCH_OWNED_RUNTIME_CLI_SHIM_DIRNAME\n );\n}\n\nexport function ensureDispatchOwnedRuntimeCliShims(input?: {\n cliEntryPath?: string;\n distribution?: OpenMeldDistribution;\n dispatchId?: string;\n env?: Record<string, string | undefined>;\n spaceActionContextPath?: string | null;\n targetProfileId?: string;\n}): string {\n const distribution = input?.distribution ?? resolveOpenMeldDistribution();\n const cliEntryPath =\n distribution === \"binary\"\n ? resolveDispatchOwnedRuntimeBinaryCliEntryPath({\n cliEntryPath: input?.cliEntryPath,\n env: input?.env,\n })\n : resolveDispatchOwnedRuntimeCliEntryPath(input?.cliEntryPath);\n const shimDir = resolveDispatchOwnedRuntimeCliShimDir({\n env: input?.env,\n spaceActionContextPath: input?.spaceActionContextPath,\n });\n mkdirSync(shimDir, { recursive: true });\n\n for (const commandName of DISPATCH_OWNED_RUNTIME_CLI_COMMAND_NAMES) {\n const shimPath = join(shimDir, commandName);\n const shimSource = buildDispatchOwnedRuntimeCliShimSource({\n cliEntryPath,\n commandName,\n dispatchId: input?.dispatchId,\n distribution,\n nodePath: process.execPath,\n spaceActionContextPath: input?.spaceActionContextPath,\n targetProfileId: input?.targetProfileId,\n });\n if (existsSync(shimPath)) {\n const currentSource = safeReadTextFile(shimPath);\n if (currentSource === shimSource) {\n chmodSync(shimPath, 0o755);\n continue;\n }\n }\n writeFileSync(shimPath, shimSource, {\n encoding: \"utf8\",\n mode: 0o755,\n });\n chmodSync(shimPath, 0o755);\n }\n\n return shimDir;\n}\n\nexport function readDispatchOwnedRuntimeGuard(\n env: NodeJS.ProcessEnv = process.env\n): DispatchOwnedRuntimeGuard {\n const mode = normalizeOptionalText(env[OPENMELD_DISPATCH_RUNTIME_MODE_ENV]);\n if (mode !== DISPATCH_OWNED_RUNTIME_MODE) {\n return {\n active: false,\n dispatchId: null,\n targetProfileId: null,\n };\n }\n\n return {\n active: true,\n dispatchId: normalizeOptionalText(\n env[OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV]\n ),\n targetProfileId: normalizeOptionalText(\n env[OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV]\n ),\n };\n}\n\nexport function assertDispatchOwnedRuntimePublicWriteAllowed(input: {\n commandLabel: string;\n env?: NodeJS.ProcessEnv;\n}): void {\n const guard = readDispatchOwnedRuntimeGuard(input.env);\n if (!guard.active) {\n return;\n }\n\n const dispatchIdSuffix = guard.dispatchId\n ? ` (dispatch ${guard.dispatchId})`\n : \"\";\n throw new Error(\n `${input.commandLabel} is blocked inside a dispatch-owned runtime${dispatchIdSuffix}. Public space writes must be returned through OpenMeld Space structured actions: post_message, post_status, or stay_silent.`\n );\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction resolveDispatchOwnedRuntimeCliEntryPath(\n cliEntryPath?: string\n): string {\n const normalizedCliEntryPath =\n normalizeOptionalText(cliEntryPath) ??\n normalizeOptionalText(process.argv[1]) ??\n null;\n if (!normalizedCliEntryPath) {\n throw new Error(\n \"dispatch-owned runtime CLI shim requires a current CLI entry path\"\n );\n }\n return resolve(normalizedCliEntryPath);\n}\n\nfunction resolveDispatchOwnedRuntimeBinaryCliEntryPath(input: {\n cliEntryPath?: string;\n env?: Record<string, string | undefined>;\n}): string {\n // A background Service may keep running from an executable path that an\n // upgrade later replaces with a launcher. The lane-owned managed CLI is the\n // stable command authority for new Space Action subprocesses.\n const normalizedCliEntryPath =\n normalizeOptionalText(input.cliEntryPath) ??\n normalizeOptionalText(openMeldManagedBinaryPath({ env: input.env })) ??\n null;\n if (!normalizedCliEntryPath) {\n throw new Error(\n \"dispatch-owned runtime CLI shim requires a current binary CLI path\"\n );\n }\n return resolve(normalizedCliEntryPath);\n}\n\nfunction buildDispatchOwnedRuntimeCliShimSource(input: {\n cliEntryPath: string;\n commandName: (typeof DISPATCH_OWNED_RUNTIME_CLI_COMMAND_NAMES)[number];\n distribution: OpenMeldDistribution;\n dispatchId?: string;\n nodePath: string;\n spaceActionContextPath?: string | null;\n targetProfileId?: string;\n}): string {\n const embeddedEnv = {\n [OPENMELD_DISPATCH_RUNTIME_MODE_ENV]: DISPATCH_OWNED_RUNTIME_MODE,\n [OPENMELD_ENV_PRESET_ENV]: resolveEnvPresetForCommandName(\n input.commandName\n ),\n [OPENMELD_USER_FACING_CLI_COMMAND_ENV]: input.commandName,\n ...(normalizeOptionalText(input.dispatchId)\n ? {\n [OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV]: normalizeOptionalText(\n input.dispatchId\n ) as string,\n }\n : {}),\n ...(normalizeOptionalText(input.targetProfileId)\n ? {\n [OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV]:\n normalizeOptionalText(input.targetProfileId) as string,\n }\n : {}),\n ...(normalizeOptionalText(input.spaceActionContextPath)\n ? {\n [OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV]: normalizeOptionalText(\n input.spaceActionContextPath\n ) as string,\n }\n : {}),\n };\n if (input.distribution === \"binary\") {\n const exportRows = Object.entries(embeddedEnv).map(\n ([key, value]) => `export ${key}=${quoteShellValue(value)}`\n );\n return `#!/bin/sh\n${exportRows.join(\"\\n\")}\nexec ${quoteShellValue(input.cliEntryPath)} \"$@\"\n`;\n }\n return `#!/usr/bin/env node\nimport { spawnSync } from \"node:child_process\";\n\nconst result = spawnSync(${JSON.stringify(input.nodePath)}, [${JSON.stringify(\n input.cliEntryPath\n )}, ...process.argv.slice(2)], {\n env: { ...process.env, ...${JSON.stringify(embeddedEnv)} },\n stdio: \"inherit\",\n});\n\nif (result.error) {\n throw result.error;\n}\n\nprocess.exit(result.status ?? 1);\n`;\n}\n\nfunction resolveDispatchOwnedRuntimeEnvPreset(input: {\n env?: Record<string, string | undefined>;\n}): \"prod\" | \"dev-local\" | \"canary\" {\n return resolveEnvPresetForCommandName(\n resolveDispatchOwnedRuntimeActionCliEntryCommand({\n env: input.env,\n })\n );\n}\n\nfunction resolveEnvPresetForCommandName(\n commandName: (typeof DISPATCH_OWNED_RUNTIME_CLI_COMMAND_NAMES)[number]\n): \"prod\" | \"dev-local\" | \"canary\" {\n if (commandName === \"openmeld-dev\") {\n return \"dev-local\";\n }\n if (commandName === \"openmeld-canary\") {\n return \"canary\";\n }\n return \"prod\";\n}\n\nfunction quoteShellValue(value: string): string {\n return `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n\nfunction safeReadTextFile(path: string): string | null {\n try {\n return readFileSync(path, \"utf8\");\n } catch {\n return null;\n }\n}\n\nfunction prependPathEntry(input: {\n currentPath: string | null;\n nextEntry: string;\n}): string {\n const currentEntries = (input.currentPath ?? \"\")\n .split(delimiter)\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n const dedupedEntries = currentEntries.filter(\n (entry) => entry !== input.nextEntry\n );\n return [input.nextEntry, ...dedupedEntries].join(delimiter);\n}\n","export function parseJsonResponse(raw: string): unknown {\n if (!raw.trim()) {\n return null;\n }\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n","import { OpenMeldApiClientHttpError } from \"@openmeld/api-client\";\nimport { OPENMELD_HEADER_REQUEST_ID } from \"@openmeld/gateway-contract\";\nimport { gatewayErrorEnvelopeSchema } from \"@openmeld/schemas\";\nimport type { GatewayErrorCode } from \"@openmeld/schemas/types\";\nimport { parseJsonResponse } from \"./api-json\";\n\nconst FALLBACK_GATEWAY_HTTP_ERROR_CODE = \"gateway.http_error\" as const;\nconst GENERIC_NETWORK_ERROR_CODES = [\n \"network.timeout\",\n \"network.request_failed\",\n] as const;\n\ntype SafeParseResult<T> = { success: true; data: T } | { success: false };\n\ntype GatewayResponseSchema<T> = {\n safeParse: (value: unknown) => SafeParseResult<T>;\n};\n\nexport type GatewayResponseErrorCode =\n | GatewayErrorCode\n | typeof FALLBACK_GATEWAY_HTTP_ERROR_CODE\n | (typeof GENERIC_NETWORK_ERROR_CODES)[number]\n | string;\n\nexport type StructuredGatewayFailure = {\n code: GatewayResponseErrorCode | null;\n message: string;\n requestId: string | null;\n status: number | null;\n upstreamCode: string | null;\n};\n\nexport class GatewayHttpError extends Error {\n readonly code: GatewayResponseErrorCode;\n readonly requestId: string | null;\n readonly status: number;\n readonly rawBody: string;\n readonly upstreamCode: string | null;\n\n constructor(input: {\n code: GatewayResponseErrorCode;\n message: string;\n requestId?: string | null;\n status: number;\n rawBody: string;\n upstreamCode?: string | null;\n }) {\n super(input.message);\n this.name = \"GatewayHttpError\";\n this.code = input.code;\n this.requestId = normalizeOptionalText(input.requestId);\n this.status = input.status;\n this.rawBody = input.rawBody;\n this.upstreamCode = normalizeOptionalText(input.upstreamCode);\n }\n}\n\nexport async function readGatewayJsonResponse<T>(input: {\n response: Response;\n schema: GatewayResponseSchema<T>;\n invalidMessage: string;\n}): Promise<T> {\n const raw = await input.response.text();\n assertGatewayResponseOk({\n response: input.response,\n raw,\n });\n\n const parsed = input.schema.safeParse(parseJsonResponse(raw));\n if (!parsed.success) {\n throw new Error(input.invalidMessage);\n }\n return parsed.data;\n}\n\nexport async function readGatewayTextResponse(input: {\n response: Response;\n}): Promise<string> {\n const raw = await input.response.text();\n assertGatewayResponseOk({\n response: input.response,\n raw,\n });\n return raw;\n}\n\nexport function assertGatewayResponseOk(input: {\n response: Response;\n raw: string;\n}): void {\n if (input.response.ok) {\n return;\n }\n throw parseGatewayErrorResponse(input);\n}\n\nexport function parseGatewayErrorResponse(input: {\n response: Pick<Response, \"headers\" | \"status\">;\n raw: string;\n}): GatewayHttpError {\n const payload = parseJsonResponse(input.raw);\n const parsed = gatewayErrorEnvelopeSchema.safeParse(payload);\n const headerRequestId = normalizeOptionalText(\n input.response.headers.get(OPENMELD_HEADER_REQUEST_ID)\n );\n\n if (parsed.success) {\n return new GatewayHttpError({\n code: parsed.data.error.code,\n message: parsed.data.error.message,\n requestId: parsed.data.error.requestId || headerRequestId,\n status: input.response.status,\n rawBody: input.raw,\n upstreamCode: parsed.data.error.upstreamCode ?? null,\n });\n }\n\n const looseEnvelope = readLooseGatewayErrorEnvelope(payload);\n if (looseEnvelope) {\n return new GatewayHttpError({\n code: looseEnvelope.code ?? FALLBACK_GATEWAY_HTTP_ERROR_CODE,\n message:\n looseEnvelope.message ??\n `Gateway request failed with HTTP ${input.response.status}.`,\n requestId: looseEnvelope.requestId ?? headerRequestId,\n status: input.response.status,\n rawBody: input.raw,\n upstreamCode: looseEnvelope.upstreamCode,\n });\n }\n\n return new GatewayHttpError({\n code: FALLBACK_GATEWAY_HTTP_ERROR_CODE,\n message:\n normalizeOptionalText(input.raw) ??\n `Gateway request failed with HTTP ${input.response.status}.`,\n requestId: headerRequestId,\n status: input.response.status,\n rawBody: input.raw,\n upstreamCode: null,\n });\n}\n\nexport function toStructuredGatewayFailure(\n error: unknown\n): StructuredGatewayFailure {\n if (error instanceof OpenMeldApiClientHttpError) {\n return {\n code: error.code,\n message: normalizeFailureMessage(error.message),\n requestId: error.requestId,\n status: error.status,\n upstreamCode: error.upstreamCode,\n };\n }\n\n if (error instanceof GatewayHttpError) {\n return {\n code: error.code,\n message: normalizeFailureMessage(error.message),\n requestId: error.requestId,\n status: error.status,\n upstreamCode: error.upstreamCode,\n };\n }\n\n const genericErrorCode = readGenericErrorCode(error);\n if (genericErrorCode) {\n return {\n code: genericErrorCode,\n message: normalizeFailureMessage(\n error instanceof Error ? error.message : String(error)\n ),\n requestId: null,\n status: null,\n upstreamCode: null,\n };\n }\n\n return {\n code: null,\n message: normalizeFailureMessage(\n error instanceof Error ? error.message : String(error)\n ),\n requestId: null,\n status: null,\n upstreamCode: null,\n };\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction normalizeFailureMessage(value: unknown): string {\n return normalizeOptionalText(value) ?? \"Unknown error.\";\n}\n\nfunction readGenericErrorCode(value: unknown): GatewayResponseErrorCode | null {\n if (!value || typeof value !== \"object\" || !(\"code\" in value)) {\n return null;\n }\n\n const normalized = normalizeOptionalText(\n (value as { code?: unknown }).code ?? null\n );\n return normalized as GatewayResponseErrorCode | null;\n}\n\nfunction readLooseGatewayErrorEnvelope(value: unknown): {\n code: string | null;\n message: string | null;\n requestId: string | null;\n upstreamCode: string | null;\n} | null {\n if (!value || typeof value !== \"object\") {\n return null;\n }\n\n const record = value as {\n error?: {\n code?: unknown;\n message?: unknown;\n requestId?: unknown;\n upstreamCode?: unknown;\n } | null;\n };\n const error = record.error;\n if (!error || typeof error !== \"object\") {\n return null;\n }\n\n const code = normalizeOptionalText(error.code);\n const message = normalizeOptionalText(error.message);\n const requestId = normalizeOptionalText(error.requestId);\n const upstreamCode = normalizeOptionalText(error.upstreamCode);\n if (!(code || message || requestId || upstreamCode)) {\n return null;\n }\n\n return {\n code,\n message,\n requestId,\n upstreamCode,\n };\n}\n","import type { SpaceMeta } from \"@openmeld/protocol\";\nimport { spaceMetaSchema } from \"@openmeld/schemas\";\n\ntype SpaceMetaParseOperation =\n | \"createSpaceMeta\"\n | \"fetchSpaceMeta\"\n | \"updateSpaceMeta\";\n\nexport function parseSpaceMetaPayload(input: {\n data: unknown;\n endpoint: string;\n operation: SpaceMetaParseOperation;\n}): SpaceMeta {\n try {\n const validation = spaceMetaSchema.safeParse(input.data);\n if (!validation.success) {\n const reason =\n validation.error.issues[0]?.message ??\n \"space meta payload does not match schema\";\n throw new Error(reason);\n }\n return validation.data;\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(\n `${input.operation} received invalid response payload from ${input.endpoint}: ${reason}; raw=${JSON.stringify(input.data)}`\n );\n }\n}\n\nexport function parseSpaceMetaResponse(input: {\n raw: string;\n endpoint: string;\n operation: Extract<\n SpaceMetaParseOperation,\n \"fetchSpaceMeta\" | \"updateSpaceMeta\"\n >;\n}): SpaceMeta {\n try {\n return parseSpaceMetaPayload({\n data: JSON.parse(input.raw) as unknown,\n endpoint: input.endpoint,\n operation: input.operation,\n });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(\n `${input.operation} received invalid response payload from ${input.endpoint}: ${reason}; raw=${input.raw}`\n );\n }\n}\n","import type { SpaceMeta } from \"@openmeld/protocol\";\nimport type { OpenMeldRequestContext } from \"@openmeld/schemas/types\";\nimport { buildOpenMeldRequestContextHeadersWithAuth } from \"../config/request-headers\";\nimport { toSpaceMetaUrl } from \"../protocol/urls\";\nimport { fetchSpaceRequestWithTimeout } from \"./fetch-with-timeout\";\nimport { readGatewayTextResponse } from \"./gateway-response\";\nimport { parseSpaceMetaResponse } from \"./space-meta-response\";\n\ntype SpaceMetaApiInput = {\n requestContext: OpenMeldRequestContext;\n baseUrl: string;\n space: string;\n password?: string;\n};\n\nexport async function fetchSpaceMeta(\n input: SpaceMetaApiInput\n): Promise<SpaceMeta> {\n const endpoint = toSpaceMetaUrl(input.baseUrl, input.space);\n const response = await fetchSpaceRequestWithTimeout({\n url: endpoint,\n operation: \"space.fetch_meta\",\n init: {\n method: \"GET\",\n headers: await buildOpenMeldRequestContextHeadersWithAuth({\n requestUrl: endpoint,\n requestContext: input.requestContext,\n spacePassword: input.password,\n }),\n },\n });\n const raw = await readGatewayTextResponse({ response });\n\n return parseSpaceMetaResponse({\n raw,\n endpoint,\n operation: \"fetchSpaceMeta\",\n });\n}\n\nexport async function updateSpaceMeta(\n input: SpaceMetaApiInput & {\n purpose?: string;\n guide?: string;\n }\n): Promise<SpaceMeta> {\n const endpoint = toSpaceMetaUrl(input.baseUrl, input.space);\n const headers = await buildOpenMeldRequestContextHeadersWithAuth({\n requestUrl: endpoint,\n requestContext: input.requestContext,\n spacePassword: input.password,\n });\n headers[\"content-type\"] = \"application/json\";\n\n const response = await fetchSpaceRequestWithTimeout({\n url: endpoint,\n operation: \"space.update_meta\",\n init: {\n method: \"PATCH\",\n headers,\n body: JSON.stringify({\n ...(input.purpose === undefined ? {} : { purpose: input.purpose }),\n ...(input.guide === undefined ? {} : { guide: input.guide }),\n }),\n },\n });\n const raw = await readGatewayTextResponse({ response });\n\n return parseSpaceMetaResponse({\n raw,\n endpoint,\n operation: \"updateSpaceMeta\",\n });\n}\n","import { createSpaceApi, type SpaceApi } from \"@openmeld/api-client\";\nimport { createCliApiClientFoundation } from \"./api-client-foundation\";\n\nexport type {\n SpaceApi,\n SpaceSignalsReadQuery,\n} from \"@openmeld/api-client\";\n\nexport function createCliSpaceApi(\n baseUrl: string,\n options: Parameters<typeof createCliApiClientFoundation>[1] = {}\n): SpaceApi {\n return createSpaceApi(createCliApiClientFoundation(baseUrl, options));\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA+BA,MAAa,yCACX;;AAGF,IAAa,iCAAb,cAAoD,MAAM;CACxD,UAAmB;CACnB;CACA,YACE,YACA,SACA;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,aAAa;CACpB;AACF;AAEA,MAAM,wCAAwC;AAC9C,MAAM,uCAAuC;AAC7C,MAAM,yBAAyB,MAAU,KAAK;AA0D9C,SAAgB,iCAAiC,OAoB/C;CACA,MAAM,YAAY,WAAW;CAC7B,MAAM,QAAQ,WAAW;CACzB,MAAM,aAAa,KACjB,sBAAsB,MAAM,aAAa,EAAE,KAAK,MAAM,IAAI,CAAC,GAC3D,0BACA,GAAG,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,GAAG,WAChC;CACA,UAAU,YAAY;EAAE,WAAW;EAAM,MAAM;CAAM,CAAC;CACtD,UAAU,YAAY,GAAK;CAE3B,MAAM,cAAc,KAAK,YAAY,cAAc;CACnD,MAAM,mBAAmB,KAAK,YAAY,aAAa;CACvD,MAAM,UAAsC;EAC1C,GAAI,MAAM,gBAAgB,EAAE,eAAe,MAAM,cAAc,IAAI,CAAC;EACpE,SAAS;EACT;EACA,WAAW,MAAM;EACjB;EACA,YAAY,MAAM;EAClB,aAAa,KAAK,IAAI,KAAK,MAAM,SAAS;EAC1C;EACA,iBAAiBA,wBAAsB,MAAM,eAAe;EAC5D,qBAAqB,MAAM;EAC3B,eAAe,MAAM;EACrB,uBAAuB,MAAM,wBACzB;GACE,gBAAgB,MAAM,sBAAsB;GAC5C,iBAAiB,MAAM,sBAAsB;EAC/C,IACA;EACJ,SAAS,MAAM;EACf,iBAAiB,M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;KACnB,GAAI,MAAM,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,MAAM,QAAQ;KAChE,GAAI,MAAM,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,MAAM,MAAM;IAC5D,CAAC;GACH;EACF,CAAC,EACoD,CAAC;EAIpD;EACA,WAAW;CACb,CAAC;AACH;;;ACjEA,SAAgB,kBACd,SACA,UAA8D,CAAC,GACrD;CACV,OAAO,eAAe,6BAA6B,SAAS,OAAO,CAAC;AACtE"}
|
|
1
|
+
{"version":3,"file":"cli-space-api-B2l1xMPn.js","names":["normalizeOptionalText","normalizeOptionalText","record"],"sources":["../src/runtime/dispatch-space-action-context.ts","../src/runtime/dispatch-owned-runtime.ts","../src/space/api-json.ts","../src/space/gateway-response.ts","../src/space/space-meta-response.ts","../src/space/meta-api.ts","../src/space/cli-space-api.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport {\n openMeldSpaceEgressActionSchema,\n spaceMemberDirectoryEntrySchema,\n} from \"@openmeld/schemas\";\nimport type {\n DispatchSpaceActionClosedReasonCode,\n OpenMeldSpaceEgressAction,\n SpaceContract,\n SpaceMemberDirectoryEntry,\n} from \"@openmeld/schemas/types\";\nimport { isSelfWakeSpaceAction } from \"@openmeld/space-mesh\";\nimport { daemonRuntimeRootPath } from \"../config/daemon-state\";\nimport type { OpenMeldPathResolutionInput } from \"../config/paths\";\nimport {\n DISPATCH_OWNED_RUNTIME_MODE,\n OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV,\n OPENMELD_DISPATCH_RUNTIME_MODE_ENV,\n OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV,\n} from \"./dispatch-runtime-env\";\n\nexport const OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV =\n \"OPENMELD_SPACE_ACTION_CONTEXT_PATH\";\n\n/** The local action context is known expired/closed/mismatched: a new ordinary action must be rejected, never recorded. */\nexport class DispatchSpaceActionClosedError extends Error {\n readonly receipt = \"rejected_closed\" as const;\n readonly reasonCode: DispatchSpaceActionClosedReasonCode;\n constructor(\n reasonCode: DispatchSpaceActionClosedReasonCode,\n message: string\n ) {\n super(message);\n this.name = \"DispatchSpaceActionClosedError\";\n this.reasonCode = reasonCode;\n }\n}\n\nconst DISPATCH_SPACE_ACTION_CONTEXT_VERSION = 1 as const;\nconst DISPATCH_SPACE_ACTION_RECORD_VERSION = 1 as const;\nconst DEFAULT_CONTEXT_TTL_MS = 12 * 60 * 60 * 1000;\n\nexport type DispatchSpaceActionSendTargetReference =\n | {\n status: \"loaded\";\n projection: SpaceMemberDirectoryEntry[];\n referenceLines: string[];\n }\n | {\n status: \"failed\";\n errorMessage: string;\n projection: null;\n referenceLines: [];\n };\n\nexport type DispatchSpaceActionContext = {\n workingCopyId?: string;\n version: typeof DISPATCH_SPACE_ACTION_CONTEXT_VERSION;\n actionRecordPath: string;\n attemptId: string;\n contextId: string;\n dispatchId: string;\n expiresAtMs: number;\n nonce: string;\n replyToSignalId: string | null;\n sendTargetReference: DispatchSpaceActionSendTargetReference;\n sourceEventId: string;\n spaceContractSnapshot: Pick<\n SpaceContract,\n \"allowedActions\" | \"publicationMode\"\n > | null;\n spaceId: string;\n targetProfileId: string;\n taskId: string;\n};\n\nexport type DispatchSpaceActionRecord = {\n version: typeof DISPATCH_SPACE_ACTION_RECORD_VERSION;\n action: OpenMeldSpaceEgressAction;\n command: string;\n contextId: string;\n createdAtMs: number;\n nonce: string;\n};\n\nexport type DispatchSpaceActionRecordReadResult =\n | {\n status: \"missing\";\n }\n | {\n errorMessage: string;\n status: \"invalid\";\n }\n | {\n record: DispatchSpaceActionRecord;\n status: \"loaded\";\n };\n\nexport function createDispatchSpaceActionContext(input: {\n workingCopyId?: string;\n attemptId: string;\n dispatchId: string;\n env?: Record<string, string | undefined>;\n pathInput?: OpenMeldPathResolutionInput;\n replyToSignalId?: string | null;\n sendTargetReference: DispatchSpaceActionSendTargetReference;\n sourceEventId: string;\n spaceContractSnapshot:\n | Pick<SpaceContract, \"allowedActions\" | \"publicationMode\">\n | null\n | undefined;\n spaceId: string;\n targetProfileId: string;\n taskId: string;\n ttlMs?: number;\n}): {\n context: DispatchSpaceActionContext;\n contextPath: string;\n} {\n const contextId = randomUUID();\n const nonce = randomUUID();\n const contextDir = join(\n daemonRuntimeRootPath(input.pathInput ?? { env: input.env }),\n \"dispatch-space-actions\",\n `${Date.now().toString(36)}-${contextId}`\n );\n mkdirSync(contextDir, { recursive: true, mode: 0o700 });\n chmodSync(contextDir, 0o700);\n\n const contextPath = join(contextDir, \"context.json\");\n const actionRecordPath = join(contextDir, \"action.json\");\n const context: DispatchSpaceActionContext = {\n ...(input.workingCopyId ? { workingCopyId: input.workingCopyId } : {}),\n version: DISPATCH_SPACE_ACTION_CONTEXT_VERSION,\n actionRecordPath,\n attemptId: input.attemptId,\n contextId,\n dispatchId: input.dispatchId,\n expiresAtMs: Date.now() + (input.ttlMs ?? DEFAULT_CONTEXT_TTL_MS),\n nonce,\n replyToSignalId: normalizeOptionalText(input.replyToSignalId),\n sendTargetReference: input.sendTargetReference,\n sourceEventId: input.sourceEventId,\n spaceContractSnapshot: input.spaceContractSnapshot\n ? {\n allowedActions: input.spaceContractSnapshot.allowedActions,\n publicationMode: input.spaceContractSnapshot.publicationMode,\n }\n : null,\n spaceId: input.spaceId,\n targetProfileId: input.targetProfileId,\n taskId: input.taskId,\n };\n\n writeJsonFileExclusive(contextPath, context);\n return { context, contextPath };\n}\n\nexport function readDispatchSpaceActionContextFromEnv(\n env: NodeJS.ProcessEnv = process.env\n): DispatchSpaceActionContext {\n const context = readDispatchSpaceActionContextForReceiptFromEnv(env);\n assertContextActive(context, Date.now());\n return context;\n}\n\n// Expiry does not erase a prior receipt. Callers may use this context to compare\n// an exact existing action; writeDispatchSpaceActionRecord still rejects new\n// actions after expiry. File reads/uploads and target listing use the active\n// context reader instead.\nexport function readDispatchSpaceActionContextForReceiptFromEnv(\n env: NodeJS.ProcessEnv = process.env\n): DispatchSpaceActionContext {\n const contextPath = normalizeOptionalText(\n env[OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV]\n );\n if (!contextPath) {\n throw new Error(\n \"No active OpenMeld Space Action dispatch context was found. Use this command inside an OpenMeld Space Wake dispatch.\"\n );\n }\n const context = readDispatchSpaceActionContext(contextPath);\n assertDispatchRuntimeEnvMatchesContext({ context, env });\n return context;\n}\n\nexport function readDispatchSpaceActionContext(\n contextPath: string\n): DispatchSpaceActionContext {\n return parseDispatchSpaceActionContext(readJsonFile(contextPath));\n}\n\nexport function writeDispatchSpaceActionRecord(input: {\n action: OpenMeldSpaceEgressAction;\n command: string;\n context: DispatchSpaceActionContext;\n nowMs?: number;\n}): DispatchSpaceActionRecord {\n const parsedAction = openMeldSpaceEgressActionSchema.safeParse(input.action);\n if (!parsedAction.success) {\n throw parsedAction.error;\n }\n if (isSelfWakeSpaceAction(parsedAction.data, input.context.targetProfileId)) {\n throw new Error(\n \"An Agent cannot Wake itself. To reply to the current message, omit wakeTargets (CLI: --wake) and submit the reply again. No action was recorded.\"\n );\n }\n\n const existing = readDispatchSpaceActionRecord({ context: input.context });\n if (existing.status === \"invalid\") {\n throw new Error(existing.errorMessage);\n }\n if (\n existing.status === \"loaded\" &&\n isDeepStrictEqual(existing.record.action, parsedAction.data)\n ) {\n return existing.record;\n }\n assertContextActive(input.context, input.nowMs ?? Date.now());\n\n const record: DispatchSpaceActionRecord = {\n version: DISPATCH_SPACE_ACTION_RECORD_VERSION,\n action: parsedAction.data,\n command: input.command,\n contextId: input.context.contextId,\n createdAtMs: input.nowMs ?? Date.now(),\n nonce: input.context.nonce,\n };\n try {\n writeJsonFileExclusive(input.context.actionRecordPath, record);\n } catch (error) {\n if (isNodeErrorCode(error, \"EEXIST\")) {\n const existing = readDispatchSpaceActionRecord({\n context: input.context,\n });\n // A lost acknowledgement may cause the same proposal to be submitted\n // again. Acknowledge that record, never replace it or accept a new action.\n if (\n existing.status === \"loaded\" &&\n isDeepStrictEqual(existing.record.action, parsedAction.data)\n ) {\n return existing.record;\n }\n throw new Error(\n \"An OpenMeld Space Action has already been recorded for this dispatch. A Wake can only have one final Space action.\"\n );\n }\n throw error;\n }\n return record;\n}\n\nexport function readDispatchSpaceActionRecord(input: {\n context: DispatchSpaceActionContext;\n nowMs?: number;\n}): DispatchSpaceActionRecordReadResult {\n if (!existsSync(input.context.actionRecordPath)) {\n return { status: \"missing\" };\n }\n try {\n const record = parseDispatchSpaceActionRecord(\n readJsonFile(input.context.actionRecordPath)\n );\n if (\n record.contextId !== input.context.contextId ||\n record.nonce !== input.context.nonce\n ) {\n return {\n status: \"invalid\",\n errorMessage:\n \"OpenMeld Space Action record does not match the active dispatch context.\",\n };\n }\n if (record.createdAtMs > input.context.expiresAtMs) {\n return {\n status: \"invalid\",\n errorMessage:\n \"OpenMeld Space Action record was created after the active dispatch context expired.\",\n };\n }\n return { status: \"loaded\", record };\n } catch (error) {\n return {\n status: \"invalid\",\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nexport function supersedeDispatchSpaceActionRecordForReconsideration(input: {\n context: DispatchSpaceActionContext;\n nowMs?: number;\n}): { archivedPath: string; record: DispatchSpaceActionRecord } | null {\n const readResult = readDispatchSpaceActionRecord(input);\n if (readResult.status === \"missing\") {\n return null;\n }\n if (readResult.status === \"invalid\") {\n throw new Error(readResult.errorMessage);\n }\n const archivedPath = `${input.context.actionRecordPath}.superseded-${String(input.nowMs ?? Date.now())}-${randomUUID()}`;\n renameSync(input.context.actionRecordPath, archivedPath);\n return { archivedPath, record: readResult.record };\n}\n\nfunction parseDispatchSpaceActionContext(\n value: unknown\n): DispatchSpaceActionContext {\n const record = toRecord(value, \"OpenMeld Space Action context\");\n const version = record.version;\n if (version !== DISPATCH_SPACE_ACTION_CONTEXT_VERSION) {\n throw new Error(\"Unsupported OpenMeld Space Action context version.\");\n }\n const sendTargetReference = parseSendTargetReference(\n record.sendTargetReference\n );\n return {\n version,\n actionRecordPath: requiredString(\n record.actionRecordPath,\n \"actionRecordPath\"\n ),\n attemptId: requiredString(record.attemptId, \"attemptId\"),\n contextId: requiredString(record.contextId, \"contextId\"),\n dispatchId: requiredString(record.dispatchId, \"dispatchId\"),\n expiresAtMs: requiredFiniteNumber(record.expiresAtMs, \"expiresAtMs\"),\n nonce: requiredString(record.nonce, \"nonce\"),\n replyToSignalId: optionalString(record.replyToSignalId),\n sendTargetReference,\n sourceEventId: requiredString(record.sourceEventId, \"sourceEventId\"),\n spaceContractSnapshot: parseSpaceContractSnapshot(\n record.spaceContractSnapshot\n ),\n spaceId: requiredString(record.spaceId, \"spaceId\"),\n targetProfileId: requiredString(record.targetProfileId, \"targetProfileId\"),\n taskId: requiredString(record.taskId, \"taskId\"),\n ...(record.workingCopyId\n ? { workingCopyId: requiredString(record.workingCopyId, \"workingCopyId\") }\n : {}),\n };\n}\n\nfunction assertDispatchRuntimeEnvMatchesContext(input: {\n context: DispatchSpaceActionContext;\n env: NodeJS.ProcessEnv;\n}): void {\n const mode = normalizeOptionalText(\n input.env[OPENMELD_DISPATCH_RUNTIME_MODE_ENV]\n );\n if (mode !== DISPATCH_OWNED_RUNTIME_MODE) {\n return;\n }\n\n const envDispatchId = normalizeOptionalText(\n input.env[OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV]\n );\n if (!envDispatchId) {\n throw new Error(\n \"OpenMeld Space Action dispatch runtime is missing the active dispatch ID.\"\n );\n }\n if (envDispatchId !== input.context.dispatchId) {\n throw new DispatchSpaceActionClosedError(\n \"space_action.context_mismatch\",\n \"OpenMeld Space Action dispatch context does not match the active dispatch runtime.\"\n );\n }\n\n const envTargetProfileId = normalizeOptionalText(\n input.env[OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV]\n );\n if (!envTargetProfileId) {\n throw new Error(\n \"OpenMeld Space Action dispatch runtime is missing the active target profile ID.\"\n );\n }\n if (envTargetProfileId !== input.context.targetProfileId) {\n throw new DispatchSpaceActionClosedError(\n \"space_action.context_mismatch\",\n \"OpenMeld Space Action target profile does not match the active dispatch runtime.\"\n );\n }\n}\n\nfunction parseDispatchSpaceActionRecord(\n value: unknown\n): DispatchSpaceActionRecord {\n const record = toRecord(value, \"OpenMeld Space Action record\");\n const version = record.version;\n if (version !== DISPATCH_SPACE_ACTION_RECORD_VERSION) {\n throw new Error(\"Unsupported OpenMeld Space Action record version.\");\n }\n const parsedAction = openMeldSpaceEgressActionSchema.safeParse(record.action);\n if (!parsedAction.success) {\n throw parsedAction.error;\n }\n return {\n version,\n action: parsedAction.data,\n command: requiredString(record.command, \"command\"),\n contextId: requiredString(record.contextId, \"contextId\"),\n createdAtMs: requiredFiniteNumber(record.createdAtMs, \"createdAtMs\"),\n nonce: requiredString(record.nonce, \"nonce\"),\n };\n}\n\nfunction parseSendTargetReference(\n value: unknown\n): DispatchSpaceActionSendTargetReference {\n const record = toRecord(value, \"sendTargetReference\");\n if (record.status === \"loaded\") {\n if (!Array.isArray(record.projection)) {\n throw new Error(\n \"OpenMeld Space Action send target projection must be an array.\"\n );\n }\n return {\n status: \"loaded\",\n projection: record.projection.map(parseSendTargetProjectionEntry),\n referenceLines: parseStringArray(record.referenceLines),\n };\n }\n if (record.status === \"failed\") {\n return {\n status: \"failed\",\n errorMessage: requiredString(record.errorMessage, \"errorMessage\"),\n projection: null,\n referenceLines: [],\n };\n }\n throw new Error(\n \"Invalid OpenMeld Space Action send target reference status.\"\n );\n}\n\nfunction parseSendTargetProjectionEntry(\n value: unknown,\n index: number\n): SpaceMemberDirectoryEntry {\n const parsed = spaceMemberDirectoryEntrySchema.safeParse(value);\n if (!parsed.success) {\n throw new Error(\n `OpenMeld Space Action target projection entry ${index} is not a valid Space member directory entry.`\n );\n }\n return parsed.data;\n}\n\nfunction parseSpaceContractSnapshot(\n value: unknown\n): Pick<SpaceContract, \"allowedActions\" | \"publicationMode\"> | null {\n if (value === null || value === undefined) {\n return null;\n }\n const record = toRecord(value, \"spaceContractSnapshot\");\n return {\n allowedActions: Array.isArray(record.allowedActions)\n ? (record.allowedActions as SpaceContract[\"allowedActions\"])\n : [],\n publicationMode:\n record.publicationMode === \"raw_context_sharing\"\n ? \"raw_context_sharing\"\n : \"collaboration\",\n };\n}\n\nfunction assertContextActive(\n context: DispatchSpaceActionContext,\n nowMs: number\n): void {\n if (nowMs > context.expiresAtMs) {\n throw new DispatchSpaceActionClosedError(\n \"space_action.context_expired\",\n \"The OpenMeld Space Action dispatch context has expired.\"\n );\n }\n}\n\nfunction readJsonFile(path: string): unknown {\n return JSON.parse(readFileSync(path, \"utf8\")) as unknown;\n}\n\nfunction writeJsonFileExclusive(path: string, value: unknown): void {\n writeFileSync(path, `${JSON.stringify(value, null, 2)}\\n`, {\n encoding: \"utf8\",\n flag: \"wx\",\n mode: 0o600,\n });\n chmodSync(path, 0o600);\n}\n\nfunction toRecord(value: unknown, label: string): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(`${label} must be a JSON object.`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction requiredString(value: unknown, fieldName: string): string {\n const normalized = normalizeOptionalText(value);\n if (!normalized) {\n throw new Error(`${fieldName} must be a non-empty string.`);\n }\n return normalized;\n}\n\nfunction requiredFiniteNumber(value: unknown, fieldName: string): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n throw new Error(`${fieldName} must be a finite number.`);\n }\n return value;\n}\n\nfunction optionalString(value: unknown): string | null {\n if (value === null || value === undefined) {\n return null;\n }\n return normalizeOptionalText(value);\n}\n\nfunction parseStringArray(value: unknown): string[] {\n if (!Array.isArray(value)) {\n return [];\n }\n return value\n .map((item) => normalizeOptionalText(item))\n .filter((item): item is string => Boolean(item));\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction isNodeErrorCode(error: unknown, code: string): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: unknown }).code === code\n );\n}\n","import {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n writeFileSync,\n} from \"node:fs\";\nimport { delimiter, dirname, join, resolve } from \"node:path\";\nimport { daemonRuntimeRootPath } from \"../config/daemon-state\";\nimport {\n type OpenMeldPathResolutionInput,\n openMeldManagedBinaryPath,\n resolveOpenMeldEnvPreset,\n} from \"../config/paths\";\nimport {\n DISPATCH_OWNED_RUNTIME_MODE,\n OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV,\n OPENMELD_DISPATCH_RUNTIME_MODE_ENV,\n OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV,\n OPENMELD_SPACE_ACTION_TOOL_COMMAND_PATH_ENV,\n OPENMELD_USER_FACING_CLI_COMMAND_ENV,\n} from \"./dispatch-runtime-env\";\nimport { OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV } from \"./dispatch-space-action-context\";\nimport {\n type OpenMeldDistribution,\n resolveOpenMeldDistribution,\n} from \"./distribution\";\n\nconst DISPATCH_OWNED_RUNTIME_CLI_SHIM_DIRNAME = \"dispatch-owned-cli\";\nconst DISPATCH_SPACE_ACTION_CLI_SHIM_DIRNAME = \"bin\";\nconst OPENMELD_ENV_PRESET_ENV = \"OPENMELD_ENV_PRESET\";\nconst DISPATCH_OWNED_RUNTIME_CLI_COMMAND_NAMES = [\n \"openmeld\",\n \"openmeld-dev\",\n \"openmeld-canary\",\n] as const;\n\nexport type DispatchOwnedRuntimeGuard = {\n active: boolean;\n dispatchId: string | null;\n targetProfileId: string | null;\n};\n\nexport function buildDispatchOwnedRuntimeEnv(input: {\n dispatchId: string;\n targetProfileId: string;\n distribution?: OpenMeldDistribution;\n env?: Record<string, string | undefined>;\n cliEntryPath?: string;\n spaceActionContextPath?: string | null;\n}): Record<string, string | undefined> {\n // Provider overrides are not a replacement for the carrier's lane. Keep\n // these non-secret installation selectors without copying unrelated Service\n // credentials into the provider environment.\n const env = {\n OPENMELD_HOME: process.env.OPENMELD_HOME,\n OPENMELD_ENV_PRESET: process.env.OPENMELD_ENV_PRESET,\n ...(input.env ?? {}),\n };\n const currentPath = normalizeOptionalText(\n input.env?.PATH ?? process.env.PATH\n );\n const shimDir = ensureDispatchOwnedRuntimeCliShims({\n cliEntryPath: input.cliEntryPath,\n dispatchId: input.dispatchId,\n distribution: input.distribution,\n env,\n spaceActionContextPath: input.spaceActionContextPath,\n targetProfileId: input.targetProfileId,\n });\n const actionCommand = resolveDispatchOwnedRuntimeActionCliEntryCommand({\n env,\n });\n return {\n ...env,\n PATH: prependPathEntry({\n currentPath,\n nextEntry: shimDir,\n }),\n [OPENMELD_DISPATCH_RUNTIME_MODE_ENV]: DISPATCH_OWNED_RUNTIME_MODE,\n [OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV]: input.dispatchId,\n [OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV]: input.targetProfileId,\n [OPENMELD_USER_FACING_CLI_COMMAND_ENV]: actionCommand,\n [OPENMELD_SPACE_ACTION_TOOL_COMMAND_PATH_ENV]: join(shimDir, actionCommand),\n [OPENMELD_ENV_PRESET_ENV]: resolveDispatchOwnedRuntimeEnvPreset({\n env,\n }),\n ...(input.spaceActionContextPath\n ? {\n [OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV]:\n input.spaceActionContextPath,\n }\n : {}),\n };\n}\n\nexport function resolveDispatchOwnedRuntimeActionCliEntryCommand(\n input: OpenMeldPathResolutionInput = {}\n): \"openmeld\" | \"openmeld-dev\" | \"openmeld-canary\" {\n const preset = resolveOpenMeldEnvPreset(input);\n if (preset === \"dev-local\") {\n return \"openmeld-dev\";\n }\n if (preset === \"canary\") {\n return \"openmeld-canary\";\n }\n return \"openmeld\";\n}\n\nexport function resolveDispatchOwnedRuntimeCliShimDir(\n input: OpenMeldPathResolutionInput & {\n spaceActionContextPath?: string | null;\n } = {}\n): string {\n const spaceActionContextPath = normalizeOptionalText(\n input.spaceActionContextPath\n );\n if (spaceActionContextPath) {\n return join(\n dirname(spaceActionContextPath),\n DISPATCH_SPACE_ACTION_CLI_SHIM_DIRNAME\n );\n }\n return join(\n daemonRuntimeRootPath(input),\n \"bin\",\n DISPATCH_OWNED_RUNTIME_CLI_SHIM_DIRNAME\n );\n}\n\nexport function ensureDispatchOwnedRuntimeCliShims(input?: {\n cliEntryPath?: string;\n distribution?: OpenMeldDistribution;\n dispatchId?: string;\n env?: Record<string, string | undefined>;\n spaceActionContextPath?: string | null;\n targetProfileId?: string;\n}): string {\n const distribution = input?.distribution ?? resolveOpenMeldDistribution();\n const cliEntryPath =\n distribution === \"binary\"\n ? resolveDispatchOwnedRuntimeBinaryCliEntryPath({\n cliEntryPath: input?.cliEntryPath,\n env: input?.env,\n })\n : resolveDispatchOwnedRuntimeCliEntryPath(input?.cliEntryPath);\n const shimDir = resolveDispatchOwnedRuntimeCliShimDir({\n env: input?.env,\n spaceActionContextPath: input?.spaceActionContextPath,\n });\n mkdirSync(shimDir, { recursive: true });\n\n for (const commandName of DISPATCH_OWNED_RUNTIME_CLI_COMMAND_NAMES) {\n const shimPath = join(shimDir, commandName);\n const shimSource = buildDispatchOwnedRuntimeCliShimSource({\n cliEntryPath,\n commandName,\n dispatchId: input?.dispatchId,\n distribution,\n nodePath: process.execPath,\n spaceActionContextPath: input?.spaceActionContextPath,\n targetProfileId: input?.targetProfileId,\n });\n if (existsSync(shimPath)) {\n const currentSource = safeReadTextFile(shimPath);\n if (currentSource === shimSource) {\n chmodSync(shimPath, 0o755);\n continue;\n }\n }\n writeFileSync(shimPath, shimSource, {\n encoding: \"utf8\",\n mode: 0o755,\n });\n chmodSync(shimPath, 0o755);\n }\n\n return shimDir;\n}\n\nexport function readDispatchOwnedRuntimeGuard(\n env: NodeJS.ProcessEnv = process.env\n): DispatchOwnedRuntimeGuard {\n const mode = normalizeOptionalText(env[OPENMELD_DISPATCH_RUNTIME_MODE_ENV]);\n if (mode !== DISPATCH_OWNED_RUNTIME_MODE) {\n return {\n active: false,\n dispatchId: null,\n targetProfileId: null,\n };\n }\n\n return {\n active: true,\n dispatchId: normalizeOptionalText(\n env[OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV]\n ),\n targetProfileId: normalizeOptionalText(\n env[OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV]\n ),\n };\n}\n\nexport function assertDispatchOwnedRuntimePublicWriteAllowed(input: {\n commandLabel: string;\n env?: NodeJS.ProcessEnv;\n}): void {\n const guard = readDispatchOwnedRuntimeGuard(input.env);\n if (!guard.active) {\n return;\n }\n\n const dispatchIdSuffix = guard.dispatchId\n ? ` (dispatch ${guard.dispatchId})`\n : \"\";\n throw new Error(\n `${input.commandLabel} is blocked inside a dispatch-owned runtime${dispatchIdSuffix}. Public space writes must be returned through OpenMeld Space structured actions: post_message, post_status, or stay_silent.`\n );\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction resolveDispatchOwnedRuntimeCliEntryPath(\n cliEntryPath?: string\n): string {\n const normalizedCliEntryPath =\n normalizeOptionalText(cliEntryPath) ??\n normalizeOptionalText(process.argv[1]) ??\n null;\n if (!normalizedCliEntryPath) {\n throw new Error(\n \"dispatch-owned runtime CLI shim requires a current CLI entry path\"\n );\n }\n return resolve(normalizedCliEntryPath);\n}\n\nfunction resolveDispatchOwnedRuntimeBinaryCliEntryPath(input: {\n cliEntryPath?: string;\n env?: Record<string, string | undefined>;\n}): string {\n // A background Service may keep running from an executable path that an\n // upgrade later replaces with a launcher. The lane-owned managed CLI is the\n // stable command authority for new Space Action subprocesses.\n const normalizedCliEntryPath =\n normalizeOptionalText(input.cliEntryPath) ??\n normalizeOptionalText(openMeldManagedBinaryPath({ env: input.env })) ??\n null;\n if (!normalizedCliEntryPath) {\n throw new Error(\n \"dispatch-owned runtime CLI shim requires a current binary CLI path\"\n );\n }\n return resolve(normalizedCliEntryPath);\n}\n\nfunction buildDispatchOwnedRuntimeCliShimSource(input: {\n cliEntryPath: string;\n commandName: (typeof DISPATCH_OWNED_RUNTIME_CLI_COMMAND_NAMES)[number];\n distribution: OpenMeldDistribution;\n dispatchId?: string;\n nodePath: string;\n spaceActionContextPath?: string | null;\n targetProfileId?: string;\n}): string {\n const embeddedEnv = {\n [OPENMELD_DISPATCH_RUNTIME_MODE_ENV]: DISPATCH_OWNED_RUNTIME_MODE,\n [OPENMELD_ENV_PRESET_ENV]: resolveEnvPresetForCommandName(\n input.commandName\n ),\n [OPENMELD_USER_FACING_CLI_COMMAND_ENV]: input.commandName,\n ...(normalizeOptionalText(input.dispatchId)\n ? {\n [OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV]: normalizeOptionalText(\n input.dispatchId\n ) as string,\n }\n : {}),\n ...(normalizeOptionalText(input.targetProfileId)\n ? {\n [OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV]:\n normalizeOptionalText(input.targetProfileId) as string,\n }\n : {}),\n ...(normalizeOptionalText(input.spaceActionContextPath)\n ? {\n [OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV]: normalizeOptionalText(\n input.spaceActionContextPath\n ) as string,\n }\n : {}),\n };\n if (input.distribution === \"binary\") {\n const exportRows = Object.entries(embeddedEnv).map(\n ([key, value]) => `export ${key}=${quoteShellValue(value)}`\n );\n return `#!/bin/sh\n${exportRows.join(\"\\n\")}\nexec ${quoteShellValue(input.cliEntryPath)} \"$@\"\n`;\n }\n return `#!/usr/bin/env node\nimport { spawnSync } from \"node:child_process\";\n\nconst result = spawnSync(${JSON.stringify(input.nodePath)}, [${JSON.stringify(\n input.cliEntryPath\n )}, ...process.argv.slice(2)], {\n env: { ...process.env, ...${JSON.stringify(embeddedEnv)} },\n stdio: \"inherit\",\n});\n\nif (result.error) {\n throw result.error;\n}\n\nprocess.exit(result.status ?? 1);\n`;\n}\n\nfunction resolveDispatchOwnedRuntimeEnvPreset(input: {\n env?: Record<string, string | undefined>;\n}): \"prod\" | \"dev-local\" | \"canary\" {\n return resolveEnvPresetForCommandName(\n resolveDispatchOwnedRuntimeActionCliEntryCommand({\n env: input.env,\n })\n );\n}\n\nfunction resolveEnvPresetForCommandName(\n commandName: (typeof DISPATCH_OWNED_RUNTIME_CLI_COMMAND_NAMES)[number]\n): \"prod\" | \"dev-local\" | \"canary\" {\n if (commandName === \"openmeld-dev\") {\n return \"dev-local\";\n }\n if (commandName === \"openmeld-canary\") {\n return \"canary\";\n }\n return \"prod\";\n}\n\nfunction quoteShellValue(value: string): string {\n return `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n\nfunction safeReadTextFile(path: string): string | null {\n try {\n return readFileSync(path, \"utf8\");\n } catch {\n return null;\n }\n}\n\nfunction prependPathEntry(input: {\n currentPath: string | null;\n nextEntry: string;\n}): string {\n const currentEntries = (input.currentPath ?? \"\")\n .split(delimiter)\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n const dedupedEntries = currentEntries.filter(\n (entry) => entry !== input.nextEntry\n );\n return [input.nextEntry, ...dedupedEntries].join(delimiter);\n}\n","export function parseJsonResponse(raw: string): unknown {\n if (!raw.trim()) {\n return null;\n }\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n","import { OpenMeldApiClientHttpError } from \"@openmeld/api-client\";\nimport { OPENMELD_HEADER_REQUEST_ID } from \"@openmeld/gateway-contract\";\nimport { gatewayErrorEnvelopeSchema } from \"@openmeld/schemas\";\nimport type { GatewayErrorCode } from \"@openmeld/schemas/types\";\nimport { parseJsonResponse } from \"./api-json\";\n\nconst FALLBACK_GATEWAY_HTTP_ERROR_CODE = \"gateway.http_error\" as const;\nconst GENERIC_NETWORK_ERROR_CODES = [\n \"network.timeout\",\n \"network.request_failed\",\n] as const;\n\ntype SafeParseResult<T> = { success: true; data: T } | { success: false };\n\ntype GatewayResponseSchema<T> = {\n safeParse: (value: unknown) => SafeParseResult<T>;\n};\n\nexport type GatewayResponseErrorCode =\n | GatewayErrorCode\n | typeof FALLBACK_GATEWAY_HTTP_ERROR_CODE\n | (typeof GENERIC_NETWORK_ERROR_CODES)[number]\n | string;\n\nexport type StructuredGatewayFailure = {\n code: GatewayResponseErrorCode | null;\n message: string;\n requestId: string | null;\n status: number | null;\n upstreamCode: string | null;\n};\n\nexport class GatewayHttpError extends Error {\n readonly code: GatewayResponseErrorCode;\n readonly requestId: string | null;\n readonly status: number;\n readonly rawBody: string;\n readonly upstreamCode: string | null;\n\n constructor(input: {\n code: GatewayResponseErrorCode;\n message: string;\n requestId?: string | null;\n status: number;\n rawBody: string;\n upstreamCode?: string | null;\n }) {\n super(input.message);\n this.name = \"GatewayHttpError\";\n this.code = input.code;\n this.requestId = normalizeOptionalText(input.requestId);\n this.status = input.status;\n this.rawBody = input.rawBody;\n this.upstreamCode = normalizeOptionalText(input.upstreamCode);\n }\n}\n\nexport async function readGatewayJsonResponse<T>(input: {\n response: Response;\n schema: GatewayResponseSchema<T>;\n invalidMessage: string;\n}): Promise<T> {\n const raw = await input.response.text();\n assertGatewayResponseOk({\n response: input.response,\n raw,\n });\n\n const parsed = input.schema.safeParse(parseJsonResponse(raw));\n if (!parsed.success) {\n throw new Error(input.invalidMessage);\n }\n return parsed.data;\n}\n\nexport async function readGatewayTextResponse(input: {\n response: Response;\n}): Promise<string> {\n const raw = await input.response.text();\n assertGatewayResponseOk({\n response: input.response,\n raw,\n });\n return raw;\n}\n\nexport function assertGatewayResponseOk(input: {\n response: Response;\n raw: string;\n}): void {\n if (input.response.ok) {\n return;\n }\n throw parseGatewayErrorResponse(input);\n}\n\nexport function parseGatewayErrorResponse(input: {\n response: Pick<Response, \"headers\" | \"status\">;\n raw: string;\n}): GatewayHttpError {\n const payload = parseJsonResponse(input.raw);\n const parsed = gatewayErrorEnvelopeSchema.safeParse(payload);\n const headerRequestId = normalizeOptionalText(\n input.response.headers.get(OPENMELD_HEADER_REQUEST_ID)\n );\n\n if (parsed.success) {\n return new GatewayHttpError({\n code: parsed.data.error.code,\n message: parsed.data.error.message,\n requestId: parsed.data.error.requestId || headerRequestId,\n status: input.response.status,\n rawBody: input.raw,\n upstreamCode: parsed.data.error.upstreamCode ?? null,\n });\n }\n\n const looseEnvelope = readLooseGatewayErrorEnvelope(payload);\n if (looseEnvelope) {\n return new GatewayHttpError({\n code: looseEnvelope.code ?? FALLBACK_GATEWAY_HTTP_ERROR_CODE,\n message:\n looseEnvelope.message ??\n `Gateway request failed with HTTP ${input.response.status}.`,\n requestId: looseEnvelope.requestId ?? headerRequestId,\n status: input.response.status,\n rawBody: input.raw,\n upstreamCode: looseEnvelope.upstreamCode,\n });\n }\n\n return new GatewayHttpError({\n code: FALLBACK_GATEWAY_HTTP_ERROR_CODE,\n message:\n normalizeOptionalText(input.raw) ??\n `Gateway request failed with HTTP ${input.response.status}.`,\n requestId: headerRequestId,\n status: input.response.status,\n rawBody: input.raw,\n upstreamCode: null,\n });\n}\n\nexport function toStructuredGatewayFailure(\n error: unknown\n): StructuredGatewayFailure {\n if (error instanceof OpenMeldApiClientHttpError) {\n return {\n code: error.code,\n message: normalizeFailureMessage(error.message),\n requestId: error.requestId,\n status: error.status,\n upstreamCode: error.upstreamCode,\n };\n }\n\n if (error instanceof GatewayHttpError) {\n return {\n code: error.code,\n message: normalizeFailureMessage(error.message),\n requestId: error.requestId,\n status: error.status,\n upstreamCode: error.upstreamCode,\n };\n }\n\n const genericErrorCode = readGenericErrorCode(error);\n if (genericErrorCode) {\n return {\n code: genericErrorCode,\n message: normalizeFailureMessage(\n error instanceof Error ? error.message : String(error)\n ),\n requestId: null,\n status: null,\n upstreamCode: null,\n };\n }\n\n return {\n code: null,\n message: normalizeFailureMessage(\n error instanceof Error ? error.message : String(error)\n ),\n requestId: null,\n status: null,\n upstreamCode: null,\n };\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction normalizeFailureMessage(value: unknown): string {\n return normalizeOptionalText(value) ?? \"Unknown error.\";\n}\n\nfunction readGenericErrorCode(value: unknown): GatewayResponseErrorCode | null {\n if (!value || typeof value !== \"object\" || !(\"code\" in value)) {\n return null;\n }\n\n const normalized = normalizeOptionalText(\n (value as { code?: unknown }).code ?? null\n );\n return normalized as GatewayResponseErrorCode | null;\n}\n\nfunction readLooseGatewayErrorEnvelope(value: unknown): {\n code: string | null;\n message: string | null;\n requestId: string | null;\n upstreamCode: string | null;\n} | null {\n if (!value || typeof value !== \"object\") {\n return null;\n }\n\n const record = value as {\n error?: {\n code?: unknown;\n message?: unknown;\n requestId?: unknown;\n upstreamCode?: unknown;\n } | null;\n };\n const error = record.error;\n if (!error || typeof error !== \"object\") {\n return null;\n }\n\n const code = normalizeOptionalText(error.code);\n const message = normalizeOptionalText(error.message);\n const requestId = normalizeOptionalText(error.requestId);\n const upstreamCode = normalizeOptionalText(error.upstreamCode);\n if (!(code || message || requestId || upstreamCode)) {\n return null;\n }\n\n return {\n code,\n message,\n requestId,\n upstreamCode,\n };\n}\n","import type { SpaceMeta } from \"@openmeld/protocol\";\nimport { spaceMetaSchema } from \"@openmeld/schemas\";\n\ntype SpaceMetaParseOperation =\n | \"createSpaceMeta\"\n | \"fetchSpaceMeta\"\n | \"updateSpaceMeta\";\n\nexport function parseSpaceMetaPayload(input: {\n data: unknown;\n endpoint: string;\n operation: SpaceMetaParseOperation;\n}): SpaceMeta {\n try {\n const validation = spaceMetaSchema.safeParse(input.data);\n if (!validation.success) {\n const reason =\n validation.error.issues[0]?.message ??\n \"space meta payload does not match schema\";\n throw new Error(reason);\n }\n return validation.data;\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(\n `${input.operation} received invalid response payload from ${input.endpoint}: ${reason}; raw=${JSON.stringify(input.data)}`\n );\n }\n}\n\nexport function parseSpaceMetaResponse(input: {\n raw: string;\n endpoint: string;\n operation: Extract<\n SpaceMetaParseOperation,\n \"fetchSpaceMeta\" | \"updateSpaceMeta\"\n >;\n}): SpaceMeta {\n try {\n return parseSpaceMetaPayload({\n data: JSON.parse(input.raw) as unknown,\n endpoint: input.endpoint,\n operation: input.operation,\n });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(\n `${input.operation} received invalid response payload from ${input.endpoint}: ${reason}; raw=${input.raw}`\n );\n }\n}\n","import type { SpaceMeta } from \"@openmeld/protocol\";\nimport type { OpenMeldRequestContext } from \"@openmeld/schemas/types\";\nimport { buildOpenMeldRequestContextHeadersWithAuth } from \"../config/request-headers\";\nimport { toSpaceMetaUrl } from \"../protocol/urls\";\nimport { fetchSpaceRequestWithTimeout } from \"./fetch-with-timeout\";\nimport { readGatewayTextResponse } from \"./gateway-response\";\nimport { parseSpaceMetaResponse } from \"./space-meta-response\";\n\ntype SpaceMetaApiInput = {\n requestContext: OpenMeldRequestContext;\n baseUrl: string;\n space: string;\n password?: string;\n};\n\nexport async function fetchSpaceMeta(\n input: SpaceMetaApiInput\n): Promise<SpaceMeta> {\n const endpoint = toSpaceMetaUrl(input.baseUrl, input.space);\n const response = await fetchSpaceRequestWithTimeout({\n url: endpoint,\n operation: \"space.fetch_meta\",\n init: {\n method: \"GET\",\n headers: await buildOpenMeldRequestContextHeadersWithAuth({\n requestUrl: endpoint,\n requestContext: input.requestContext,\n spacePassword: input.password,\n }),\n },\n });\n const raw = await readGatewayTextResponse({ response });\n\n return parseSpaceMetaResponse({\n raw,\n endpoint,\n operation: \"fetchSpaceMeta\",\n });\n}\n\nexport async function updateSpaceMeta(\n input: SpaceMetaApiInput & {\n purpose?: string;\n guide?: string;\n }\n): Promise<SpaceMeta> {\n const endpoint = toSpaceMetaUrl(input.baseUrl, input.space);\n const headers = await buildOpenMeldRequestContextHeadersWithAuth({\n requestUrl: endpoint,\n requestContext: input.requestContext,\n spacePassword: input.password,\n });\n headers[\"content-type\"] = \"application/json\";\n\n const response = await fetchSpaceRequestWithTimeout({\n url: endpoint,\n operation: \"space.update_meta\",\n init: {\n method: \"PATCH\",\n headers,\n body: JSON.stringify({\n ...(input.purpose === undefined ? {} : { purpose: input.purpose }),\n ...(input.guide === undefined ? {} : { guide: input.guide }),\n }),\n },\n });\n const raw = await readGatewayTextResponse({ response });\n\n return parseSpaceMetaResponse({\n raw,\n endpoint,\n operation: \"updateSpaceMeta\",\n });\n}\n","import { createSpaceApi, type SpaceApi } from \"@openmeld/api-client\";\nimport { createCliApiClientFoundation } from \"./api-client-foundation\";\n\nexport type {\n SpaceApi,\n SpaceSignalsReadQuery,\n} from \"@openmeld/api-client\";\n\nexport function createCliSpaceApi(\n baseUrl: string,\n options: Parameters<typeof createCliApiClientFoundation>[1] = {}\n): SpaceApi {\n return createSpaceApi(createCliApiClientFoundation(baseUrl, options));\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA+BA,MAAa,yCACX;;AAGF,IAAa,iCAAb,cAAoD,MAAM;CACxD,UAAmB;CACnB;CACA,YACE,YACA,SACA;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,aAAa;CACpB;AACF;AAEA,MAAM,wCAAwC;AAC9C,MAAM,uCAAuC;AAC7C,MAAM,yBAAyB,MAAU,KAAK;AA0D9C,SAAgB,iCAAiC,OAoB/C;CACA,MAAM,YAAY,WAAW;CAC7B,MAAM,QAAQ,WAAW;CACzB,MAAM,aAAa,KACjB,sBAAsB,MAAM,aAAa,EAAE,KAAK,MAAM,IAAI,CAAC,GAC3D,0BACA,GAAG,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,GAAG,WAChC;CACA,UAAU,YAAY;EAAE,WAAW;EAAM,MAAM;CAAM,CAAC;CACtD,UAAU,YAAY,GAAK;CAE3B,MAAM,cAAc,KAAK,YAAY,cAAc;CACnD,MAAM,mBAAmB,KAAK,YAAY,aAAa;CACvD,MAAM,UAAsC;EAC1C,GAAI,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CACb,CAAC;AACH;AAEA,eAAsB,gBACpB,OAIoB;CACpB,MAAM,WAAW,eAAe,MAAM,SAAS,MAAM,KAAK;CAC1D,MAAM,UAAU,MAAM,2CAA2C;EAC/D,YAAY;EACZ,gBAAgB,MAAM;EACtB,eAAe,MAAM;CACvB,CAAC;CACD,QAAQ,kBAAkB;CAgB1B,OAAO,uBAAuB;EAC5B,KAAA,MAHgB,wBAAwB,EAAE,UAAA,MAZrB,6BAA6B;GAClD,KAAK;GACL,WAAW;GACX,MAAM;IACJ,QAAQ;IACR;IACA,MAAM,KAAK,UAAU;KACnB,GAAI,MAAM,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,MAAM,QAAQ;KAChE,GAAI,MAAM,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,MAAM,MAAM;IAC5D,CAAC;GACH;EACF,CAAC,EACoD,CAAC;EAIpD;EACA,WAAW;CACb,CAAC;AACH;;;ACjEA,SAAgB,kBACd,SACA,UAA8D,CAAC,GACrD;CACV,OAAO,eAAe,6BAA6B,SAAS,OAAO,CAAC;AACtE"}
|
|
@@ -3,26 +3,26 @@
|
|
|
3
3
|
import { _ as toSpaceWsUrl, a as toSpaceCreateUrl, d as toSpaceMembersUrl, f as toSpaceMetaUrl, m as toSpaceRemoveMembersUrl, o as toSpaceCursorUrl, p as toSpacePasswordUrl, s as toSpaceDeleteUrl, t as normalizeBaseUrl, u as toSpaceLeaveUrl } from "./urls-CY2uzH2-.js";
|
|
4
4
|
import { t as isLoopbackHostname } from "./loopback-hostname-DHQPKq8N.js";
|
|
5
5
|
import { ct as resolveOpenMeldEnvPreset, d as runWithHeldLock, i as isOpenMeldLockError, t as acquireLock, u as resolveOpenMeldOrphanedLockIssue } from "./lock-Bsl_ElWy.js";
|
|
6
|
-
import { An as resolveAccountSpaceIndexGatewayHost, At as createAccountSpaceIndexApi, Bi as toLegacySpaceImageGeometryWireValue, Br as removeSpaceMembersResponseSchema, Gn as parseServerErrorFrame$1, Hn as MAX_TEXT_LENGTH, Ht as createFetchTransport, Jt as createOrganizationApi, Kn as resolveCustomMentionAliasOverride, Mt as createAgentProfileBindingApi, Nn as toStructuredApiClientFailure, Rr as leaveSpaceResponseSchema, Un as parseEnvelope$1, Vi as toCompatibleSpaceAddressingRequestWireValue, Wn as parseIncoming$1, en as createProfileSpaceHistoryApi, gt as buildProfileSpaceHistoryUpsertPath, ht as buildProfileSpaceHistoryStatusPath, ii as resolveInitialSpaceAccessMode, jn as resolveProfileSpaceHistoryGatewayHost, n as OpenMeldApiClientInvalidResponseError, qt as createOpenMeldApiClient, t as OpenMeldApiClientHttpError, zr as postSpaceMembersResponseSchema } from "./dist-
|
|
6
|
+
import { An as resolveAccountSpaceIndexGatewayHost, At as createAccountSpaceIndexApi, Bi as toLegacySpaceImageGeometryWireValue, Br as removeSpaceMembersResponseSchema, Gn as parseServerErrorFrame$1, Hn as MAX_TEXT_LENGTH, Ht as createFetchTransport, Jt as createOrganizationApi, Kn as resolveCustomMentionAliasOverride, Mt as createAgentProfileBindingApi, Nn as toStructuredApiClientFailure, Rr as leaveSpaceResponseSchema, Un as parseEnvelope$1, Vi as toCompatibleSpaceAddressingRequestWireValue, Wn as parseIncoming$1, en as createProfileSpaceHistoryApi, gt as buildProfileSpaceHistoryUpsertPath, ht as buildProfileSpaceHistoryStatusPath, ii as resolveInitialSpaceAccessMode, jn as resolveProfileSpaceHistoryGatewayHost, n as OpenMeldApiClientInvalidResponseError, qt as createOpenMeldApiClient, t as OpenMeldApiClientHttpError, zr as postSpaceMembersResponseSchema } from "./dist-BewA9srP.js";
|
|
7
7
|
import { v as canonicalizeBuiltinAgentControllerRef, x as parseAgentControllerRef, y as normalizeBuiltinAgentControllerId } from "./controller-contract-DAOCaefz.js";
|
|
8
|
-
import { Dt as resolveRegistryOriginLaunchCommand, Et as listBuiltinAgentsRegistryEntries, G as updateAgentRegistrations, H as resolveAgentTargetState, I as listAgentTargetStates, O as syncDeviceRuntimeStateProjection, Q as resolveLocalRegistryAgentIdFromAgentControllerRef, S as syncProfileWorkspaceState, ar as createAuthorityOpenMeldServiceRuntimeId, br as resolveSelectableCandidates, cr as isAgentExecutionReadyOrConnecting, er as buildAgentControllerRef, j as resolveAgentProfilePrimaryAgentControllerReport, jr as resolveBuiltinAgentControllerBrand, kt as resolveRegistryRuntimeAdapterContractByAgentControllerRef, ur as parseAgentControllerRef$1 } from "./prepare-provider-runtime-
|
|
8
|
+
import { Dt as resolveRegistryOriginLaunchCommand, Et as listBuiltinAgentsRegistryEntries, G as updateAgentRegistrations, H as resolveAgentTargetState, I as listAgentTargetStates, O as syncDeviceRuntimeStateProjection, Q as resolveLocalRegistryAgentIdFromAgentControllerRef, S as syncProfileWorkspaceState, ar as createAuthorityOpenMeldServiceRuntimeId, br as resolveSelectableCandidates, cr as isAgentExecutionReadyOrConnecting, er as buildAgentControllerRef, j as resolveAgentProfilePrimaryAgentControllerReport, jr as resolveBuiltinAgentControllerBrand, kt as resolveRegistryRuntimeAdapterContractByAgentControllerRef, ur as parseAgentControllerRef$1 } from "./prepare-provider-runtime-CD5ZI-ct.js";
|
|
9
9
|
import { Ct as SPACE_MENTION_REJECT_NOTICE_PURPOSE, In as buildTargetWakeLifecycleId, Sr as resolveSingleSpaceMentionLabels, St as SPACE_MEMBER_REMOVE_NOTICE_PURPOSE, Yn as executionContextSelectionSchema, _t as CONVERSATION_CONTINUITY_WARNING_PURPOSE, br as normalizeSpacePasswordText, fr as parseOptionalClientMessageId, pn as spaceFileNameSchema, qt as SPACE_FILE_MAX_SIZE_BYTES, rn as resolveSpaceFileMimeType, ui as MAX_TEXT_LENGTH$1, xt as SPACE_MEMBER_JOIN_NOTICE_PURPOSE } from "./runtime-transport-0F5E6So6.js";
|
|
10
10
|
import { d as getAuthSessionState } from "./auth-session-CDhQANWx.js";
|
|
11
11
|
import { D as normalizeOptionalWorkingDirectory } from "./control-plane-BDS63N7Y.js";
|
|
12
|
-
import { D as createDelayedSpinner, G as ensureCommandAuthenticationOrCancel, N as renderHumanErrorCard, U as connectWebSocket, W as buildCommandAuthenticationPromptMessage, at as promptTextEntry, b as formatServiceRuntimeHeadline, it as buildUnifiedCardFrame, lt as getCurrentCommandCheckState, nt as renderInfoCard, x as resolveServiceParticipationReadiness, y as formatServiceParticipationReadinessLabel } from "./service-
|
|
12
|
+
import { D as createDelayedSpinner, G as ensureCommandAuthenticationOrCancel, N as renderHumanErrorCard, U as connectWebSocket, W as buildCommandAuthenticationPromptMessage, at as promptTextEntry, b as formatServiceRuntimeHeadline, it as buildUnifiedCardFrame, lt as getCurrentCommandCheckState, nt as renderInfoCard, x as resolveServiceParticipationReadiness, y as formatServiceParticipationReadinessLabel } from "./service-C72KhNft.js";
|
|
13
13
|
import { B as createOpenMeldHumanProfile, H as getOpenMeldProfileCapabilities, J as assertAdditionalHumanProfileCreationEnabled, U as listOpenMeldProfiles, et as buildHumanAuthenticationCard, it as resolveAuthenticationGuidanceFromError, rt as resolveAuthenticationGuidance, st as resolveCurrentOpenMeldAccountContext, z as createOpenMeldAgentProfile } from "./daemon-device-id-YnLMx1kN.js";
|
|
14
|
-
import { F as formatSpaceMemberCommandRecoveryCopy, H as resolveGatewayChainRetryGuidance, I as resolveReplyReadinessAvailabilityReasonCopy, L as resolveReplyReadinessGuidanceSummaryCopy, M as formatReplyReadinessSummary, O as resolveCurrentReplyReadinessSnapshot, P as REPLY_READINESS_COPY, R as resolveOpenClawDiagnosticsGuidance, U as resolveOpenClawLocalDiagnosticsValue, V as resolveGatewayChainRepairGuidance, W as resolveLocalServiceDemand, b as buildDaemonServiceRepairGuidance, z as classifyGatewayChainFailure } from "./daemon-service-update-coordinator-
|
|
15
|
-
import { At as SpaceComposerSubmissionError, Bt as buildSpaceProfileAddPlan, Ct as removeSpaceConfig, Dt as upsertSpaceConfig, Et as updateSpaceLastSeenTs, Ft as buildSignalMessageReadProjection, Gt as collectResolvedSpaceMentions, It as buildSignalReplyWorkflowProjection, Jt as createSpaceTargetCatalog, Lt as buildSpaceMemberAgentPresencePresentation, Ot as writeSpaceCacheDeletionNoticeState, Pt as buildSignalIndex, Rt as buildSpaceMentionProfileIndex, St as readSpaceRecentMentionProfileIds, Tt as toSpaceConfigListIntegrityError, Wt as closeMentionPickerState, Xt as extractMentionAuthoringPrefix, Yt as enterRelationPickerState, _t as isLocalSpaceStateCorruptResult, an as listSpaceMentionSuggestions, bt as readSpaceConfig, cn as prepareSpaceFileOnlySubmission, dn as returnToTargetPickerState, en as isRelationPickerState, fn as updateAuthoredMentionRanges, ht as LocalSpaceStateIntegrityError, in as listSpaceMentionRelationChoices, jt as buildDispatchResultMessageReadProjection, kt as writeSpaceRecentMentionProfileIds, ln as resolveNextRecentMentionProfileIdsForQueuedText, mt as projectSpaceProfileCache, on as openTargetPickerState, sn as prepareSpaceComposerSubmission, tn as isTargetPickerState, un as resolveSpaceMemberAgentOwnerWakeDiagnosticsView, vt as listSpaceConfigs, wt as toLocalSpaceStateIntegrityError, xt as readSpaceLastSeenTs, yt as readSpaceCacheDeletionNoticeState, zt as buildSpaceMessageReadRelationSummary } from "./daemon-frame-transport-
|
|
14
|
+
import { F as formatSpaceMemberCommandRecoveryCopy, H as resolveGatewayChainRetryGuidance, I as resolveReplyReadinessAvailabilityReasonCopy, L as resolveReplyReadinessGuidanceSummaryCopy, M as formatReplyReadinessSummary, O as resolveCurrentReplyReadinessSnapshot, P as REPLY_READINESS_COPY, R as resolveOpenClawDiagnosticsGuidance, U as resolveOpenClawLocalDiagnosticsValue, V as resolveGatewayChainRepairGuidance, W as resolveLocalServiceDemand, b as buildDaemonServiceRepairGuidance, z as classifyGatewayChainFailure } from "./daemon-service-update-coordinator-RJO997me.js";
|
|
15
|
+
import { At as SpaceComposerSubmissionError, Bt as buildSpaceProfileAddPlan, Ct as removeSpaceConfig, Dt as upsertSpaceConfig, Et as updateSpaceLastSeenTs, Ft as buildSignalMessageReadProjection, Gt as collectResolvedSpaceMentions, It as buildSignalReplyWorkflowProjection, Jt as createSpaceTargetCatalog, Lt as buildSpaceMemberAgentPresencePresentation, Ot as writeSpaceCacheDeletionNoticeState, Pt as buildSignalIndex, Rt as buildSpaceMentionProfileIndex, St as readSpaceRecentMentionProfileIds, Tt as toSpaceConfigListIntegrityError, Wt as closeMentionPickerState, Xt as extractMentionAuthoringPrefix, Yt as enterRelationPickerState, _t as isLocalSpaceStateCorruptResult, an as listSpaceMentionSuggestions, bt as readSpaceConfig, cn as prepareSpaceFileOnlySubmission, dn as returnToTargetPickerState, en as isRelationPickerState, fn as updateAuthoredMentionRanges, ht as LocalSpaceStateIntegrityError, in as listSpaceMentionRelationChoices, jt as buildDispatchResultMessageReadProjection, kt as writeSpaceRecentMentionProfileIds, ln as resolveNextRecentMentionProfileIdsForQueuedText, mt as projectSpaceProfileCache, on as openTargetPickerState, sn as prepareSpaceComposerSubmission, tn as isTargetPickerState, un as resolveSpaceMemberAgentOwnerWakeDiagnosticsView, vt as listSpaceConfigs, wt as toLocalSpaceStateIntegrityError, xt as readSpaceLastSeenTs, yt as readSpaceCacheDeletionNoticeState, zt as buildSpaceMessageReadRelationSummary } from "./daemon-frame-transport-D-4StENt.js";
|
|
16
16
|
import { a as resolveBaseUrl, d as createDefaultRuntimeAgentControllerSettings } from "./base-url-D7uE_xTo.js";
|
|
17
17
|
import { a as formatOpenMeldCliTextBlock, l as resolveUserFacingCliEntryCommand, n as formatOpenMeldCliCommand, o as formatProfileAwareOpenMeldCliCommand, r as formatOpenMeldCliCommands, t as formatInlineOpenMeldCliCommands } from "./cli-entry-command-CR_9QU1i.js";
|
|
18
18
|
import { t as sleep } from "./dist-BLuEEVHh.js";
|
|
19
19
|
import { a as requireOpenMeldProfile, n as resolveRuntimeContext, o as resolveOpenMeldProfileOrNull } from "./context-D9Ebb5wl.js";
|
|
20
20
|
import { a as outJsonLine, i as errLine, n as sanitizeTerminalDisplayText, o as outLine, r as formatMessage, t as createPresenter } from "./presenter-BcxiQyJg.js";
|
|
21
|
-
import { $ as ROOT_ENTRY_START_COMMAND, A as createSpaceLeaveCreatorGuideError, B as createSpaceSendInputEmptyGuideError, D as createSpaceContractSetGuideError, F as createSpaceRemoveMembersCreatorGuideError, G as createSpaceUnsupportedProfileKindGuideError, H as createSpaceSendInputRequiredGuideError, I as createSpaceRemoveMembersCurrentProfileGuideError, K as createSpaceUpdatesGuideError, L as createSpaceRemoveMembersGuideError, M as createSpaceMenuGuideError, N as createSpaceProfileRequiredGuideError, O as createSpaceCreateGuideError, P as createSpacePublicationSetGuideError, Q as ROOT_ENTRY_COMMANDS, R as createSpaceResultGuideError, T as createSpaceAddMembersGuideError, Tt as formatAgentOverviewPayload, U as createSpaceSubcommandTargetGuideError, V as createSpaceSendInputFileReadFailedGuideError, W as createSpaceTargetGuideError, b as createProfileCreateGuideError, dt as getCliVersionInfo, g as canUseInteractivePrompts, it as resolveSpaceAddMembersProgressPhase, j as createSpaceLeaveGuideError, k as createSpaceDeleteHumanApprovalGuideError, nt as SPACE_ADD_MEMBERS_AGENT_OVERVIEW_STAGES, rt as SPACE_ADD_MEMBERS_PROGRESS_HEARTBEAT_MS, tt as validateSpaceMemberSelectionInput, ut as formatCliVersionSummary, w as createSpaceAddMembersCurrentProfileGuideError, z as createSpaceSendInputConflictGuideError } from "./elapsed-time-
|
|
22
|
-
import { a as buildOpenMeldProfileIdentityRequestHeadersWithAuth, d as buildOpenMeldRequestContextFromProfile, f as buildOpenMeldRequestContextFromProfileIdentity, m as resolveAuthRequestCompatibility, n as fetchSpaceRequestWithTimeout, o as buildOpenMeldProfileRequestHeadersWithAuth, p as deriveAuthBaseUrlFromGatewayUrl, r as resolveSpaceRequestTimeoutMsForDiagnostics, s as buildOpenMeldRequestContextHeadersWithAuth, t as createCliApiClientFoundation } from "./api-client-foundation-
|
|
23
|
-
import { S as buildSpaceWebUrl, T as runDaemonServiceParticipationGate, _ as promptSearchSelect, b as resolveOffsetVisibleWindow, f as runAgentsRepair, g as promptSearchMultiselectWorkbench, h as promptSearchMultiselect, l as runAgentsEnable, m as formatTransportModeDisplay, v as clampNumber$2, x as computeRetryDelayMs, y as resolveAnchoredVisibleWindow } from "./agents-
|
|
24
|
-
import { l as resolveLocalAgentControllerReportDecision, n as submitProfileRuntimeAgentControllerReport, o as collectLocalAgentControllerInventory, r as submitRuntimeAgentControllerReport } from "./runtime-agent-controller-reporting-submission-
|
|
25
|
-
import { a as parseSpaceMetaResponse, d as assertDispatchOwnedRuntimePublicWriteAllowed, i as parseSpaceMetaPayload, l as toStructuredGatewayFailure, n as fetchSpaceMeta, o as GatewayHttpError, s as readGatewayJsonResponse, t as createCliSpaceApi } from "./cli-space-api-
|
|
21
|
+
import { $ as ROOT_ENTRY_START_COMMAND, A as createSpaceLeaveCreatorGuideError, B as createSpaceSendInputEmptyGuideError, D as createSpaceContractSetGuideError, F as createSpaceRemoveMembersCreatorGuideError, G as createSpaceUnsupportedProfileKindGuideError, H as createSpaceSendInputRequiredGuideError, I as createSpaceRemoveMembersCurrentProfileGuideError, K as createSpaceUpdatesGuideError, L as createSpaceRemoveMembersGuideError, M as createSpaceMenuGuideError, N as createSpaceProfileRequiredGuideError, O as createSpaceCreateGuideError, P as createSpacePublicationSetGuideError, Q as ROOT_ENTRY_COMMANDS, R as createSpaceResultGuideError, T as createSpaceAddMembersGuideError, Tt as formatAgentOverviewPayload, U as createSpaceSubcommandTargetGuideError, V as createSpaceSendInputFileReadFailedGuideError, W as createSpaceTargetGuideError, b as createProfileCreateGuideError, dt as getCliVersionInfo, g as canUseInteractivePrompts, it as resolveSpaceAddMembersProgressPhase, j as createSpaceLeaveGuideError, k as createSpaceDeleteHumanApprovalGuideError, nt as SPACE_ADD_MEMBERS_AGENT_OVERVIEW_STAGES, rt as SPACE_ADD_MEMBERS_PROGRESS_HEARTBEAT_MS, tt as validateSpaceMemberSelectionInput, ut as formatCliVersionSummary, w as createSpaceAddMembersCurrentProfileGuideError, z as createSpaceSendInputConflictGuideError } from "./elapsed-time-Cw6b9rYy.js";
|
|
22
|
+
import { a as buildOpenMeldProfileIdentityRequestHeadersWithAuth, d as buildOpenMeldRequestContextFromProfile, f as buildOpenMeldRequestContextFromProfileIdentity, m as resolveAuthRequestCompatibility, n as fetchSpaceRequestWithTimeout, o as buildOpenMeldProfileRequestHeadersWithAuth, p as deriveAuthBaseUrlFromGatewayUrl, r as resolveSpaceRequestTimeoutMsForDiagnostics, s as buildOpenMeldRequestContextHeadersWithAuth, t as createCliApiClientFoundation } from "./api-client-foundation-D-Cb6EVg.js";
|
|
23
|
+
import { S as buildSpaceWebUrl, T as runDaemonServiceParticipationGate, _ as promptSearchSelect, b as resolveOffsetVisibleWindow, f as runAgentsRepair, g as promptSearchMultiselectWorkbench, h as promptSearchMultiselect, l as runAgentsEnable, m as formatTransportModeDisplay, v as clampNumber$2, x as computeRetryDelayMs, y as resolveAnchoredVisibleWindow } from "./agents-2TzCubpV.js";
|
|
24
|
+
import { l as resolveLocalAgentControllerReportDecision, n as submitProfileRuntimeAgentControllerReport, o as collectLocalAgentControllerInventory, r as submitRuntimeAgentControllerReport } from "./runtime-agent-controller-reporting-submission-DGm8O4q_.js";
|
|
25
|
+
import { a as parseSpaceMetaResponse, d as assertDispatchOwnedRuntimePublicWriteAllowed, i as parseSpaceMetaPayload, l as toStructuredGatewayFailure, n as fetchSpaceMeta, o as GatewayHttpError, s as readGatewayJsonResponse, t as createCliSpaceApi } from "./cli-space-api-B2l1xMPn.js";
|
|
26
26
|
import { basename } from "node:path";
|
|
27
27
|
import { access, readFile } from "node:fs/promises";
|
|
28
28
|
import * as z$1 from "zod/v4";
|
|
@@ -24483,4 +24483,4 @@ function isHumanInteractiveSpaceRuntime(runtime) {
|
|
|
24483
24483
|
//#endregion
|
|
24484
24484
|
export { resolveCreateProfileKind as $, parseEnvelope as A, resolveHumanControllerDisplayName as B, toSpaceMetaUpsertInput as C, formatHumanReadTargetList as D, buildHumanReplyContextSummary as E, resolveOpenMeldProfileForSpaceCommand as F, printOpenMeldBanner as G, resolveAgentProfileSetup as H, emitSpaceAgentOverview as I, renderOpenMeldLogo as J, renderOpenMeldBrandBlockLines as K, emitSpaceCliAgentOverview as L, assertFullSignalIdArgument as M, assertValidSpaceIdTarget as N, resolveLinkAccessLabel as O, prepareAuthenticatedSpaceCommandContext as P, createProfileByKind as Q, prepareLocalAgentReadiness as R, loadSpaceSignalIndexOrNull as S, buildFormalSignalReadPayload as T, colorizeAgentLabel as U, persistAgentTransportSelection as V, colorizeDisplayProfileLabel as W, resolveSpaceSendText as X, renderOpenMeldTagline as Y, resolveSpaceTaskSelection as Z, runSpaceWriteWithPasswordRetry as _, runSpaceDelete as a, buildIdentityOnlyMembersSnapshotForReadProjection as b, runSpaceLeave as c, runSpaceRemoveMembers as d, resolveCreateProfileName as et, runSpaceSend as f, runSpaceReadWithPasswordRetry as g, uploadPreparedSpaceFiles as h, runSpaceCreate as i, isSpaceCommandOutputHandledError as j, resolveOrganizationVisibilityLabel as k, runSpaceList as l, prepareRequestedSpaceSendFiles as m, promptAndConfirmSpacePassword as n, assessActionParticipationCandidate as nt, runSpaceHistory as o, runSpaceWatch as p, renderOpenMeldHeader as q, runSpaceAddMembers as r, runSpaceJoin as s, buildCreateSpacePasswordPromptConfig as t, ensureAgentProfileRuntimeBinding as tt, runSpacePassword as u, buildHumanReadSignalsTranscriptItems as v, buildFormalDispatchResultReadPayload as w, loadSpaceIdentityDirectoryOrNull as x, emitHumanReadSignalsTextProjection as y, buildReplyReadinessGuidance as z };
|
|
24485
24485
|
|
|
24486
|
-
//# sourceMappingURL=command-
|
|
24486
|
+
//# sourceMappingURL=command-MlrjQYq5.js.map
|