@experiture/xyra-cli 0.6.1 → 0.6.4
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/README.md +24 -1
- package/dist/auth/oauthClient.js +89 -30
- package/dist/auth/oauthClient.js.map +1 -1
- package/dist/auth/session.js +11 -7
- package/dist/auth/session.js.map +1 -1
- package/dist/auth/tokenStore.js.map +1 -1
- package/dist/chat/runtimeChatClient.js +22503 -1287
- package/dist/chat/runtimeChatClient.js.map +4 -4
- package/dist/commands/chat.js +159 -37
- package/dist/commands/chat.js.map +1 -1
- package/dist/commands/login.js +7 -7
- package/dist/commands/login.js.map +1 -1
- package/dist/commands/mcpContext.js +29 -3
- package/dist/commands/mcpContext.js.map +1 -1
- package/dist/commands/session.js +32 -24
- package/dist/commands/session.js.map +1 -1
- package/dist/commands/tools.js +72 -7
- package/dist/commands/tools.js.map +1 -1
- package/dist/commands/workflowProposal.js +19 -0
- package/dist/commands/workflowProposal.js.map +1 -0
- package/dist/config/configStore.js +130 -104
- package/dist/config/configStore.js.map +3 -3
- package/dist/index.js +26 -10
- package/dist/index.js.map +1 -1
- package/dist/mcp/confirmation.js +17 -3
- package/dist/mcp/confirmation.js.map +1 -1
- package/dist/mcp/mcpClient.js +83 -32
- package/dist/mcp/mcpClient.js.map +4 -4
- package/dist/output/formatters.js +4 -0
- package/dist/output/formatters.js.map +1 -1
- package/package.json +3 -3
package/dist/mcp/mcpClient.js
CHANGED
|
@@ -35,10 +35,18 @@ var require_xyra_administration = __commonJS({
|
|
|
35
35
|
"../../libs/xyra-types/dist/xyra-administration.js"(exports2) {
|
|
36
36
|
"use strict";
|
|
37
37
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
38
|
+
exports2.runtimeAdministrationTarget = runtimeAdministrationTarget;
|
|
38
39
|
exports2.parseXyraAdministrationTargetV1 = parseXyraAdministrationTargetV12;
|
|
39
40
|
exports2.xyraAdministrationTargetKeyV1 = xyraAdministrationTargetKeyV1;
|
|
40
41
|
exports2.parseXyraAdministrationResolvedTargetV1 = parseXyraAdministrationResolvedTargetV1;
|
|
41
42
|
exports2.parseXyraAdministrationDecisionV1 = parseXyraAdministrationDecisionV1;
|
|
43
|
+
function runtimeAdministrationTarget(identity) {
|
|
44
|
+
return identity.licenseSourceProductId !== identity.licensedProductId && identity.tenantId === identity.licenseOwnerTenantId ? {
|
|
45
|
+
targetKind: "configuration-owner",
|
|
46
|
+
configurationTenantId: identity.licenseOwnerTenantId,
|
|
47
|
+
managedProductId: identity.licenseSourceProductId
|
|
48
|
+
} : { targetKind: "customer-resource", targetTenantId: identity.tenantId, activeProductId: identity.productId };
|
|
49
|
+
}
|
|
42
50
|
var identifier = (value) => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,49}$/.test(value);
|
|
43
51
|
var guid = (value) => typeof value === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value) && value !== "00000000-0000-0000-0000-000000000000";
|
|
44
52
|
var record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
@@ -76,7 +84,7 @@ var require_xyra_administration = __commonJS({
|
|
|
76
84
|
const base = ["targetKind", "managedProductId", "relationshipKind", "activeProductId", "actualTenantId", "licensedProductId", "commercialState"];
|
|
77
85
|
const embedded = ["licenseSourceProductId", "licenseOwnerTenantId", "bindingId", "entitlementId", "sourceEntitlementId"];
|
|
78
86
|
const isNative = value.relationshipKind === "native-product-tenant";
|
|
79
|
-
if (!isNative && value.relationshipKind !== "embedded-product-entitlement" || !exact(value, isNative ? base : [...base, ...embedded]) || value.licensedProductId !== "xyra-ai" || !base.filter((key) => !["targetKind", "relationshipKind"].includes(key)).every((key) => identifier(value[key])) || (isNative ? value.activeProductId !== "xyra-ai" : !embedded.every((key) => identifier(value[key]))) || value.actualTenantId !== (target.targetKind === "customer-resource" ? target.targetTenantId : target.configurationTenantId) || target.targetKind === "customer-resource" && value.activeProductId !== target.activeProductId || target.targetKind === "configuration-owner" && value.activeProductId !== target.managedProductId || !isNative && (value.
|
|
87
|
+
if (!isNative && value.relationshipKind !== "embedded-product-entitlement" || !exact(value, isNative ? base : [...base, ...embedded]) || value.licensedProductId !== "xyra-ai" || !base.filter((key) => !["targetKind", "relationshipKind"].includes(key)).every((key) => identifier(value[key])) || (isNative ? value.activeProductId !== "xyra-ai" : !embedded.every((key) => identifier(value[key]))) || value.actualTenantId !== (target.targetKind === "customer-resource" ? target.targetTenantId : target.configurationTenantId) || target.targetKind === "customer-resource" && value.activeProductId !== target.activeProductId || target.targetKind === "configuration-owner" && value.activeProductId !== target.managedProductId || !isNative && (value.activeProductId !== value.licenseSourceProductId && value.activeProductId !== value.licensedProductId || !["bindingId", "entitlementId", "sourceEntitlementId"].every((key) => guid(value[key])) || target.targetKind === "configuration-owner" && (value.licenseOwnerTenantId !== target.configurationTenantId || value.licenseSourceProductId !== target.managedProductId)))
|
|
80
88
|
return null;
|
|
81
89
|
return { ...value };
|
|
82
90
|
}
|
|
@@ -92,17 +100,23 @@ var require_xyra_administration = __commonJS({
|
|
|
92
100
|
"targetTenantId",
|
|
93
101
|
"grantId",
|
|
94
102
|
"target",
|
|
95
|
-
"resolvedTarget"
|
|
96
|
-
|
|
103
|
+
"resolvedTarget",
|
|
104
|
+
...Object.prototype.hasOwnProperty.call(value, "configurationAccess") ? ["configurationAccess"] : []
|
|
105
|
+
]) || value.configurationAccess !== void 0 && !["read", "manage", "manage_selection"].includes(String(value.configurationAccess)) || value.operationId !== request.operationId || value.purpose !== purpose || value.accessPurpose !== "administration" || value.productId !== "xyra-ai" || typeof value.allowed !== "boolean" || typeof value.code !== "string" || !/^[A-Z0-9_.]{1,160}$/.test(value.code) || !(value.operatorTenantId === null || identifier(value.operatorTenantId)) || !(value.grantId === null || guid(value.grantId)))
|
|
97
106
|
return null;
|
|
98
107
|
const target = parseXyraAdministrationTargetV12(value.target);
|
|
99
108
|
if (!target || xyraAdministrationTargetKeyV1(target) !== xyraAdministrationTargetKeyV1(request.target) || value.targetTenantId !== (target.targetKind === "global-resource" ? null : target.targetKind === "configuration-owner" ? target.configurationTenantId : target.targetTenantId))
|
|
100
109
|
return null;
|
|
101
110
|
const resolvedTarget = parseXyraAdministrationResolvedTargetV1(value.resolvedTarget, target);
|
|
102
111
|
if (value.allowed) {
|
|
103
|
-
if (!resolvedTarget
|
|
112
|
+
if (!resolvedTarget)
|
|
113
|
+
return null;
|
|
114
|
+
if (value.code === "AUTHORIZATION.ALLOWED.SAME_TENANT") {
|
|
115
|
+
if (target.targetKind !== "customer-resource" || value.operatorTenantId !== target.targetTenantId || value.grantId !== null)
|
|
116
|
+
return null;
|
|
117
|
+
} else if (value.code === "AUTHORIZATION.ALLOWED.SUPER_USER" ? value.operatorTenantId !== null || value.grantId !== null : !["AUTHORIZATION.ALLOWED", "AUTHORIZATION.ALLOWED.LICENSEE"].includes(value.code) || value.operatorTenantId === null || value.grantId === null)
|
|
104
118
|
return null;
|
|
105
|
-
if (value.code === "AUTHORIZATION.ALLOWED.LICENSEE" && (target.targetKind === "global-resource" || resolvedTarget.relationshipKind !== "embedded-product-entitlement" || resolvedTarget.licenseOwnerTenantId !== value.operatorTenantId
|
|
119
|
+
if (value.code === "AUTHORIZATION.ALLOWED.LICENSEE" && (target.targetKind === "global-resource" || resolvedTarget.relationshipKind !== "embedded-product-entitlement" || resolvedTarget.licenseOwnerTenantId !== value.operatorTenantId))
|
|
106
120
|
return null;
|
|
107
121
|
} else if (value.code.startsWith("AUTHORIZATION.ALLOWED") || value.resolvedTarget !== null)
|
|
108
122
|
return null;
|
|
@@ -115,24 +129,14 @@ var require_xyra_administration = __commonJS({
|
|
|
115
129
|
var mcpClient_exports = {};
|
|
116
130
|
__export(mcpClient_exports, {
|
|
117
131
|
McpClient: () => McpClient,
|
|
118
|
-
McpRawResponseCapture: () => McpRawResponseCapture
|
|
132
|
+
McpRawResponseCapture: () => McpRawResponseCapture,
|
|
133
|
+
validateToolConversationId: () => validateToolConversationId,
|
|
134
|
+
workflowResumeControlFor: () => workflowResumeControlFor
|
|
119
135
|
});
|
|
120
136
|
module.exports = __toCommonJS(mcpClient_exports);
|
|
121
|
-
var import_types2 = require("@modelcontextprotocol/sdk/types.js");
|
|
122
|
-
|
|
123
|
-
// src/mcp/mcpError.ts
|
|
124
137
|
var import_types = require("@modelcontextprotocol/sdk/types.js");
|
|
125
|
-
var
|
|
126
|
-
|
|
127
|
-
constructor(rpc) {
|
|
128
|
-
super(rpc.message);
|
|
129
|
-
this.name = "McpRpcError";
|
|
130
|
-
this.rpc = rpc;
|
|
131
|
-
}
|
|
132
|
-
static from(error) {
|
|
133
|
-
return error instanceof import_types.McpError ? new _McpRpcError({ code: error.code, message: error.message, data: error.data }) : null;
|
|
134
|
-
}
|
|
135
|
-
};
|
|
138
|
+
var import_CliError = require("../errors/CliError");
|
|
139
|
+
var import_mcpError = require("./mcpError");
|
|
136
140
|
|
|
137
141
|
// src/diagnostics/latency.ts
|
|
138
142
|
var activeDiagnostics;
|
|
@@ -158,6 +162,21 @@ var McpRawResponseCapture = class {
|
|
|
158
162
|
}
|
|
159
163
|
}
|
|
160
164
|
};
|
|
165
|
+
function workflowResumeControlFor(result, toolKey, executionId) {
|
|
166
|
+
const envelope = result.structuredContent;
|
|
167
|
+
const metadata = result._meta;
|
|
168
|
+
const value = envelope?.continuation ?? metadata?.["com.experiture.xyra/workflowContinuation"];
|
|
169
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
170
|
+
const reference = value;
|
|
171
|
+
if (reference.executionId !== executionId || reference.toolKey !== toolKey || !Number.isSafeInteger(reference.revision) || Number(reference.revision) < 0) return void 0;
|
|
172
|
+
return { workflowResume: { executionId, expectedRevision: Number(reference.revision) } };
|
|
173
|
+
}
|
|
174
|
+
function validateToolConversationId(value) {
|
|
175
|
+
if (value !== void 0 && (typeof value !== "string" || value !== value.trim() || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value))) {
|
|
176
|
+
throw new import_CliError.CliError(import_CliError.CliErrorCodes.InvalidArguments, "--conversation must be a conversation UUID.");
|
|
177
|
+
}
|
|
178
|
+
return value;
|
|
179
|
+
}
|
|
161
180
|
var McpClient = class {
|
|
162
181
|
constructor(sdk, transport, rawCapture, administrationTarget) {
|
|
163
182
|
this.sdk = sdk;
|
|
@@ -166,7 +185,7 @@ var McpClient = class {
|
|
|
166
185
|
this.administrationTarget = administrationTarget;
|
|
167
186
|
if (administrationTarget) {
|
|
168
187
|
const selected = (0, import_xyra_administration.parseXyraAdministrationTargetV1)(administrationTarget);
|
|
169
|
-
if (!selected) throw new McpRpcError({ code: -32602, message: "Select one closed administration target.", data: { xyraCode: "XYRA.MCP.REQUEST_INVALID" } });
|
|
188
|
+
if (!selected) throw new import_mcpError.McpRpcError({ code: -32602, message: "Select one closed administration target.", data: { xyraCode: "XYRA.MCP.REQUEST_INVALID" } });
|
|
170
189
|
this.administrationTarget = selected;
|
|
171
190
|
}
|
|
172
191
|
}
|
|
@@ -180,28 +199,28 @@ var McpClient = class {
|
|
|
180
199
|
}
|
|
181
200
|
async request(method, params = {}, options) {
|
|
182
201
|
if (this.administrationTarget) {
|
|
183
|
-
if (method === "xyra/chat" || ["xyra/confirmations/approve", "xyra/confirmations/reject", "xyra/confirmations/cancel"].includes(method))
|
|
184
|
-
throw new McpRpcError({ code: -32602, message: "Administrative delegated sessions cannot run chat or decide approvals.", data: { xyraCode: "XYRA.AUTH.INSUFFICIENT_PERMISSIONS" } });
|
|
202
|
+
if (method === "xyra/chat" || ["xyra/confirmations/approve", "xyra/confirmations/reject", "xyra/confirmations/cancel", "xyra/confirmations/continue"].includes(method))
|
|
203
|
+
throw new import_mcpError.McpRpcError({ code: -32602, message: "Administrative delegated sessions cannot run chat or decide approvals.", data: { xyraCode: "XYRA.AUTH.INSUFFICIENT_PERMISSIONS" } });
|
|
185
204
|
if (method === "tools/list" || method === "tools/call") params = { ...params, target: this.administrationTarget };
|
|
186
205
|
}
|
|
187
206
|
this.rawCapture?.begin(options?.captureRaw);
|
|
188
207
|
try {
|
|
189
208
|
return await measureLatencyPhase(
|
|
190
209
|
"mcp.method",
|
|
191
|
-
() => this.sdk.request({ method, params },
|
|
210
|
+
() => this.sdk.request({ method, params }, import_types.ResultSchema),
|
|
192
211
|
{ method }
|
|
193
212
|
);
|
|
194
213
|
} catch (error) {
|
|
195
|
-
throw McpRpcError.from(error) ?? error;
|
|
214
|
+
throw import_mcpError.McpRpcError.from(error) ?? error;
|
|
196
215
|
} finally {
|
|
197
216
|
this.rawCapture?.end();
|
|
198
217
|
}
|
|
199
218
|
}
|
|
200
|
-
assertConfirmationExtension() {
|
|
219
|
+
assertConfirmationExtension(method) {
|
|
201
220
|
const experimental = this.sdk.getServerCapabilities()?.experimental;
|
|
202
221
|
const extension = experimental?.["com.experiture.xyra.confirmations"];
|
|
203
|
-
if (extension?.version !== 1) {
|
|
204
|
-
throw new McpRpcError({
|
|
222
|
+
if (extension?.version !== 1 || method && (!Array.isArray(extension.methods) || !extension.methods.includes(method))) {
|
|
223
|
+
throw new import_mcpError.McpRpcError({
|
|
205
224
|
code: -32602,
|
|
206
225
|
message: "The server did not negotiate the Xyra confirmation extension.",
|
|
207
226
|
data: { xyraCode: "XYRA.MCP.EXTENSION_NOT_NEGOTIATED" }
|
|
@@ -212,7 +231,7 @@ var McpClient = class {
|
|
|
212
231
|
const experimental = this.sdk.getServerCapabilities()?.experimental;
|
|
213
232
|
const extension = experimental?.["com.experiture.xyra.chat"];
|
|
214
233
|
if (extension?.version !== 1) {
|
|
215
|
-
throw new McpRpcError({
|
|
234
|
+
throw new import_mcpError.McpRpcError({
|
|
216
235
|
code: -32602,
|
|
217
236
|
message: "The server did not negotiate the Xyra chat extension.",
|
|
218
237
|
data: { xyraCode: "XYRA.MCP.EXTENSION_NOT_NEGOTIATED" }
|
|
@@ -225,7 +244,7 @@ var McpClient = class {
|
|
|
225
244
|
let cursor;
|
|
226
245
|
do {
|
|
227
246
|
const params = {};
|
|
228
|
-
if (this.administrationTarget && (filters?.domainId || filters?.taskKey)) throw new McpRpcError({
|
|
247
|
+
if (this.administrationTarget && (filters?.domainId || filters?.taskKey)) throw new import_mcpError.McpRpcError({
|
|
229
248
|
code: -32602,
|
|
230
249
|
message: "Administrative discovery uses a closed target and optional exact tool key; runtime domain/task filters are not admission.",
|
|
231
250
|
data: { xyraCode: "XYRA.MCP.REQUEST_INVALID" }
|
|
@@ -248,10 +267,15 @@ var McpClient = class {
|
|
|
248
267
|
return all.find((tool) => tool.name === toolKey);
|
|
249
268
|
}
|
|
250
269
|
callTool(name, args, options, control) {
|
|
270
|
+
const conversationId = validateToolConversationId(control?.conversationId);
|
|
251
271
|
return this.request("tools/call", {
|
|
272
|
+
...conversationId ? { conversationId } : {},
|
|
252
273
|
name,
|
|
253
274
|
arguments: args,
|
|
254
|
-
...control?.confirmationRequestId ? { _meta: {
|
|
275
|
+
...control?.confirmationRequestId || control?.workflowResume ? { _meta: {
|
|
276
|
+
...control.confirmationRequestId ? { "com.experiture.xyra/confirmationRequestId": control.confirmationRequestId } : {},
|
|
277
|
+
...control.workflowResume ? { "com.experiture.xyra/workflowResume": control.workflowResume } : {}
|
|
278
|
+
} } : {}
|
|
255
279
|
}, options);
|
|
256
280
|
}
|
|
257
281
|
listConfirmations(params = {}) {
|
|
@@ -274,6 +298,31 @@ var McpClient = class {
|
|
|
274
298
|
this.assertConfirmationExtension();
|
|
275
299
|
return this.request("xyra/confirmations/cancel", { id });
|
|
276
300
|
}
|
|
301
|
+
async continueGovernanceApproval(id, expected, options) {
|
|
302
|
+
this.assertConfirmationExtension("xyra/confirmations/continue");
|
|
303
|
+
const result = await this.request("xyra/confirmations/continue", { id }, options);
|
|
304
|
+
if (result?.schemaVersion !== 1 || !["pending", "completed", "failed", "canceled"].includes(result.status) || result.confirmation?.id !== id || result.continuation?.kind !== "governance_change_set" || typeof result.continuation.changeSetId !== "string" || !result.continuation.changeSetId || typeof result.continuation.changeSetHash !== "string" || !result.continuation.changeSetHash || expected && (result.continuation.changeSetId !== expected.changeSetId || result.continuation.changeSetHash !== expected.changeSetHash) || result.changeSet?.id !== result.continuation.changeSetId || result.status === "completed" && result.changeSet.status !== "applied") {
|
|
305
|
+
throw new import_mcpError.McpRpcError({
|
|
306
|
+
code: -32603,
|
|
307
|
+
message: "The governance continuation did not match its original approval and change set.",
|
|
308
|
+
data: { xyraCode: "XYRA.MCP.RESULT_SCHEMA_MISMATCH" }
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
return result;
|
|
312
|
+
}
|
|
313
|
+
resumeChat(params) {
|
|
314
|
+
this.assertChatExtension();
|
|
315
|
+
return this.request("xyra/chat", { ...params, resumeRetainedWork: true });
|
|
316
|
+
}
|
|
317
|
+
getWorkflowProposal(params) {
|
|
318
|
+
this.assertChatExtension();
|
|
319
|
+
const { conversationId, clientRequestId, ...readProposal } = params;
|
|
320
|
+
return this.request("xyra/chat", { conversationId, clientRequestId, readProposal });
|
|
321
|
+
}
|
|
322
|
+
stopChat(params) {
|
|
323
|
+
this.assertChatExtension();
|
|
324
|
+
return this.request("xyra/chat", { ...params, stopRetainedWork: true });
|
|
325
|
+
}
|
|
277
326
|
chat(params) {
|
|
278
327
|
this.assertChatExtension();
|
|
279
328
|
return this.request("xyra/chat", params);
|
|
@@ -282,6 +331,8 @@ var McpClient = class {
|
|
|
282
331
|
// Annotate the CommonJS export names for ESM import in node:
|
|
283
332
|
0 && (module.exports = {
|
|
284
333
|
McpClient,
|
|
285
|
-
McpRawResponseCapture
|
|
334
|
+
McpRawResponseCapture,
|
|
335
|
+
validateToolConversationId,
|
|
336
|
+
workflowResumeControlFor
|
|
286
337
|
});
|
|
287
338
|
//# sourceMappingURL=mcpClient.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../../../libs/xyra-types/src/xyra-administration.ts", "../../src/mcp/mcpClient.ts", "../../src/
|
|
4
|
-
"sourcesContent": ["/** A requested maintenance target. It is never a runtime identity or an authorization decision. */\nexport type XyraAdministrationTargetV1 =\n | Readonly<{ targetKind: 'global-resource'; managedProductId: 'xyra-ai' }>\n | Readonly<{ targetKind: 'configuration-owner'; configurationTenantId: string; managedProductId: string }>\n | Readonly<{ targetKind: 'customer-resource'; targetTenantId: string; activeProductId: string }>;\n\nexport type XyraAccessPurposeV1 = 'runtime' | 'administration';\nexport type XyraAuthorityDecisionPhaseV1 = 'discovery' | 'execution';\n\nexport type XyraAdministrationRequestV1 = Readonly<{\n operationId: string;\n target: XyraAdministrationTargetV1;\n}>;\n\n/** Auth-resolved relationship facts, without a permission snapshot or runtime licence grant. */\nexport type XyraAdministrationResolvedTargetV1 =\n | Readonly<{ targetKind: 'global-resource'; managedProductId: 'xyra-ai'; relationshipKind: 'global-resource' }>\n | Readonly<{ targetKind: 'configuration-owner' | 'customer-resource'; managedProductId: string;\n relationshipKind: 'native-product-tenant'; activeProductId: 'xyra-ai'; actualTenantId: string;\n licensedProductId: 'xyra-ai'; commercialState: string }>\n | Readonly<{ targetKind: 'configuration-owner' | 'customer-resource'; managedProductId: string;\n relationshipKind: 'embedded-product-entitlement'; activeProductId: string; actualTenantId: string;\n licenseSourceProductId: string; licensedProductId: 'xyra-ai'; licenseOwnerTenantId: string;\n bindingId: string; entitlementId: string; sourceEntitlementId: string; commercialState: string }>;\n\nexport type XyraAdministrationDecisionV1 = Readonly<{\n operationId: string;\n purpose: XyraAuthorityDecisionPhaseV1;\n accessPurpose: 'administration';\n allowed: boolean;\n code: string;\n productId: 'xyra-ai';\n operatorTenantId: string | null;\n targetTenantId: string | null;\n grantId: string | null;\n target: XyraAdministrationTargetV1;\n resolvedTarget: XyraAdministrationResolvedTargetV1 | null;\n}>;\n\n/** Protected execution/approval scope, not a permission grant and never a public argument. */\nexport type XyraAdministrationExecutionScopeV1 = Readonly<{\n accessPurpose: 'administration';\n resourceAudience: string;\n administrationTransport: 'native-http' | 'delegated-oauth';\n actorOperatorTenantId: string | null;\n targetHash: string;\n target: XyraAdministrationTargetV1;\n resolvedTarget: XyraAdministrationResolvedTargetV1;\n}>;\n\nconst identifier = (value: unknown): value is string => typeof value === 'string'\n && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,49}$/.test(value);\nconst guid = (value: unknown): value is string => typeof value === 'string'\n && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value)\n && value !== '00000000-0000-0000-0000-000000000000';\nconst record = (value: unknown): value is Record<string, unknown> => value !== null\n && typeof value === 'object' && !Array.isArray(value);\nconst exact = (value: Record<string, unknown>, keys: readonly string[]): boolean =>\n Object.keys(value).length === keys.length && keys.every(key => Object.prototype.hasOwnProperty.call(value, key));\n\n/** Strictly parse the closed object shape; raw duplicate JSON keys belong to the transport parser. */\nexport function parseXyraAdministrationTargetV1(value: unknown): XyraAdministrationTargetV1 | null {\n if (!record(value)) return null;\n if (value.targetKind === 'global-resource' && exact(value, ['targetKind', 'managedProductId'])\n && value.managedProductId === 'xyra-ai') {\n return { targetKind: 'global-resource', managedProductId: 'xyra-ai' };\n }\n if (value.targetKind === 'configuration-owner'\n && exact(value, ['targetKind', 'configurationTenantId', 'managedProductId'])\n && identifier(value.configurationTenantId) && identifier(value.managedProductId)) {\n return { targetKind: 'configuration-owner', configurationTenantId: value.configurationTenantId,\n managedProductId: value.managedProductId };\n }\n if (value.targetKind === 'customer-resource'\n && exact(value, ['targetKind', 'targetTenantId', 'activeProductId'])\n && identifier(value.targetTenantId) && identifier(value.activeProductId)) {\n return { targetKind: 'customer-resource', targetTenantId: value.targetTenantId, activeProductId: value.activeProductId };\n }\n return null;\n}\n\n/** Stable exact tuple for cache/request binding, excluding display text and mutable capabilities. */\nexport function xyraAdministrationTargetKeyV1(target: XyraAdministrationTargetV1): string {\n return JSON.stringify(target.targetKind === 'global-resource'\n ? [target.targetKind, target.managedProductId]\n : target.targetKind === 'configuration-owner'\n ? [target.targetKind, target.configurationTenantId, target.managedProductId]\n : [target.targetKind, target.targetTenantId, target.activeProductId]);\n}\n\n/** Validate independent Auth facts against the exact request, never infer a missing relationship. */\nexport function parseXyraAdministrationResolvedTargetV1(\n value: unknown, target: XyraAdministrationTargetV1,\n): XyraAdministrationResolvedTargetV1 | null {\n if (!record(value) || value.targetKind !== target.targetKind) return null;\n const managedProductId = target.targetKind === 'customer-resource' ? 'xyra-ai' : target.managedProductId;\n if (value.managedProductId !== managedProductId) return null;\n if (target.targetKind === 'global-resource') {\n return exact(value, ['targetKind', 'managedProductId', 'relationshipKind']) && value.relationshipKind === 'global-resource'\n ? { targetKind: 'global-resource', managedProductId: 'xyra-ai', relationshipKind: 'global-resource' } : null;\n }\n const base = ['targetKind', 'managedProductId', 'relationshipKind', 'activeProductId', 'actualTenantId', 'licensedProductId', 'commercialState'];\n const embedded = ['licenseSourceProductId', 'licenseOwnerTenantId', 'bindingId', 'entitlementId', 'sourceEntitlementId'];\n const isNative = value.relationshipKind === 'native-product-tenant';\n if ((!isNative && value.relationshipKind !== 'embedded-product-entitlement')\n || !exact(value, isNative ? base : [...base, ...embedded]) || value.licensedProductId !== 'xyra-ai'\n || !base.filter(key => !['targetKind', 'relationshipKind'].includes(key)).every(key => identifier(value[key]))\n || (isNative ? value.activeProductId !== 'xyra-ai' : !embedded.every(key => identifier(value[key])))\n || value.actualTenantId !== (target.targetKind === 'customer-resource' ? target.targetTenantId : target.configurationTenantId)\n || (target.targetKind === 'customer-resource' && value.activeProductId !== target.activeProductId)\n || (target.targetKind === 'configuration-owner' && value.activeProductId !== target.managedProductId)\n || (!isNative && (value.licenseSourceProductId !== value.activeProductId\n || !['bindingId', 'entitlementId', 'sourceEntitlementId'].every(key => guid(value[key]))\n || (target.targetKind === 'configuration-owner' && value.licenseOwnerTenantId !== target.configurationTenantId)))) return null;\n return { ...value } as XyraAdministrationResolvedTargetV1;\n}\n\n/** Parse a decision only for the operation, phase and target that were actually requested. */\nexport function parseXyraAdministrationDecisionV1(value: unknown,\n request: XyraAdministrationRequestV1, purpose: XyraAuthorityDecisionPhaseV1,\n): XyraAdministrationDecisionV1 | null {\n if (!record(value) || !exact(value, ['operationId', 'purpose', 'accessPurpose', 'allowed', 'code', 'productId',\n 'operatorTenantId', 'targetTenantId', 'grantId', 'target', 'resolvedTarget'])\n || value.operationId !== request.operationId || value.purpose !== purpose || value.accessPurpose !== 'administration'\n || value.productId !== 'xyra-ai' || typeof value.allowed !== 'boolean' || typeof value.code !== 'string'\n || !/^[A-Z0-9_.]{1,160}$/.test(value.code)\n || !(value.operatorTenantId === null || identifier(value.operatorTenantId))\n || !(value.grantId === null || guid(value.grantId))) return null;\n const target = parseXyraAdministrationTargetV1(value.target);\n if (!target || xyraAdministrationTargetKeyV1(target) !== xyraAdministrationTargetKeyV1(request.target)\n || value.targetTenantId !== (target.targetKind === 'global-resource' ? null\n : target.targetKind === 'configuration-owner' ? target.configurationTenantId : target.targetTenantId)) return null;\n const resolvedTarget = parseXyraAdministrationResolvedTargetV1(value.resolvedTarget, target);\n if (value.allowed) {\n if (!resolvedTarget || (value.code === 'AUTHORIZATION.ALLOWED.SUPER_USER'\n ? value.operatorTenantId !== null || value.grantId !== null\n : !['AUTHORIZATION.ALLOWED', 'AUTHORIZATION.ALLOWED.LICENSEE'].includes(value.code) || value.operatorTenantId === null || value.grantId === null)) return null;\n if (value.code === 'AUTHORIZATION.ALLOWED.LICENSEE'\n && (target.targetKind === 'global-resource' || resolvedTarget.relationshipKind !== 'embedded-product-entitlement'\n || resolvedTarget.licenseOwnerTenantId !== value.operatorTenantId || resolvedTarget.activeProductId === 'xyra-ai')) return null;\n } else if (value.code.startsWith('AUTHORIZATION.ALLOWED') || value.resolvedTarget !== null) return null;\n return { ...value, target, resolvedTarget } as XyraAdministrationDecisionV1;\n}\n", "import { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport type { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport { ResultSchema } from '@modelcontextprotocol/sdk/types.js';\nimport type {\n XyraRuntimeActionDescriptor,\n XyraPendingHumanApprovalV1,\n XyraRuntimeResponse,\n XyraRuntimeStreamOutcome,\n XyraHumanApprovalViewV1,\n} from '@experiture/xyra-runtime-client';\nimport { McpRpcError } from './mcpError';\nimport { measureLatencyPhase } from '../diagnostics/latency';\nimport {parseXyraAdministrationTargetV1,type XyraAdministrationTargetV1}from'@xyra/types/xyra-administration';\n\nexport interface RpcCallOptions {\n /** Exact JSON-RPC envelope captured from a JSON Streamable HTTP response. */\n captureRaw?: (raw: unknown) => void;\n}\n\nexport class McpRawResponseCapture {\n private callback?: (raw: unknown) => void;\n\n begin(callback?: (raw: unknown) => void): void {\n this.callback = callback;\n }\n\n end(): void {\n this.callback = undefined;\n }\n\n async observe(response: Response): Promise<void> {\n if (!this.callback || !response.headers.get('content-type')?.includes('application/json')) return;\n try {\n this.callback(await response.clone().json());\n } catch {\n // The SDK remains the protocol authority; raw capture is diagnostic only.\n }\n }\n}\n\nexport interface McpTool {\n name: string;\n title?: string;\n description?: string;\n inputSchema?: unknown;\n outputSchema?: unknown;\n annotations?: Record<string, unknown>;\n _meta?: Record<string, unknown>;\n}\n\ninterface ToolsListResult {\n tools: McpTool[];\n nextCursor?: string;\n}\n\nexport interface ToolCallResult {\n content?: unknown;\n structuredContent?: unknown;\n isError?: boolean;\n [key: string]: unknown;\n}\n\nexport interface ConfirmationControl {\n confirmationRequestId?: string;\n}\n\nexport interface ConfirmationListResult {\n confirmations: Record<string, unknown>[];\n count: number;\n}\n\nexport interface McpChatRequest {\n conversationId?: string;\n createConversation?: boolean;\n title?: string;\n message: string;\n locale?: 'en' | 'fr' | 'zh-Hans';\n clientRequestId?: string;\n}\n\nexport interface McpChatResult {\n schemaVersion: 1;\n conversationId: string;\n clientRequestId: string;\n requestId: string;\n executionId: string;\n streamId: string;\n traceId?: string;\n userMessageId: string;\n assistantMessageId?: string;\n outcome: XyraRuntimeStreamOutcome;\n message?: string;\n response?: XyraRuntimeResponse;\n error?: unknown;\n actions?: XyraRuntimeActionDescriptor[];\n pendingHumanApproval?: XyraPendingHumanApprovalV1;\n confirmation?: XyraHumanApprovalViewV1;\n eventCount: number;\n chunkCount: number;\n createdConversation?: {\n id: string;\n title: string;\n titleSource: string;\n createdAt: string;\n };\n}\n\nexport class McpClient {\n constructor(\n private readonly sdk: Client,\n private readonly transport: StreamableHTTPClientTransport,\n private readonly rawCapture?: McpRawResponseCapture,\n private readonly administrationTarget?:XyraAdministrationTargetV1,\n ) {\n if(administrationTarget){\n const selected=parseXyraAdministrationTargetV1(administrationTarget);\n if(!selected)throw new McpRpcError({code:-32602,message:'Select one closed administration target.',data:{xyraCode:'XYRA.MCP.REQUEST_INVALID'}});\n this.administrationTarget=selected;\n }\n }\n\n initialize(): unknown {\n return {\n protocolVersion: this.transport.protocolVersion,\n capabilities: this.sdk.getServerCapabilities() ?? {},\n serverInfo: this.sdk.getServerVersion() ?? {},\n instructions: this.sdk.getInstructions(),\n };\n }\n\n private async request<T>(method: string, params: Record<string, unknown> = {}, options?: RpcCallOptions): Promise<T> {\n if(this.administrationTarget){\n if(method==='xyra/chat'||['xyra/confirmations/approve','xyra/confirmations/reject','xyra/confirmations/cancel'].includes(method))\n throw new McpRpcError({code:-32602,message:'Administrative delegated sessions cannot run chat or decide approvals.',data:{xyraCode:'XYRA.AUTH.INSUFFICIENT_PERMISSIONS'}});\n if(method==='tools/list'||method==='tools/call')params={...params,target:this.administrationTarget};\n }\n this.rawCapture?.begin(options?.captureRaw);\n try {\n return await measureLatencyPhase(\n 'mcp.method',\n () => this.sdk.request({ method, params } as never, ResultSchema) as Promise<T>,\n { method },\n );\n } catch (error) {\n throw McpRpcError.from(error) ?? error;\n } finally {\n this.rawCapture?.end();\n }\n }\n\n private assertConfirmationExtension(): void {\n const experimental = this.sdk.getServerCapabilities()?.experimental;\n const extension = experimental?.['com.experiture.xyra.confirmations'] as Record<string, unknown> | undefined;\n if (extension?.version !== 1) {\n throw new McpRpcError({\n code: -32602,\n message: 'The server did not negotiate the Xyra confirmation extension.',\n data: { xyraCode: 'XYRA.MCP.EXTENSION_NOT_NEGOTIATED' },\n });\n }\n }\n\n private assertChatExtension(): void {\n const experimental = this.sdk.getServerCapabilities()?.experimental;\n const extension = experimental?.['com.experiture.xyra.chat'] as Record<string, unknown> | undefined;\n if (extension?.version !== 1) {\n throw new McpRpcError({\n code: -32602,\n message: 'The server did not negotiate the Xyra chat extension.',\n data: { xyraCode: 'XYRA.MCP.EXTENSION_NOT_NEGOTIATED' },\n });\n }\n }\n\n /** Page through every visible tool unless a hard limit is supplied. */\n async listTools(filters?: { domainId?: string; taskKey?: string; toolKey?: string; limit?: number }): Promise<McpTool[]> {\n const tools: McpTool[] = [];\n let cursor: string | undefined;\n do {\n const params: Record<string, unknown> = {};\n if(this.administrationTarget&&(filters?.domainId||filters?.taskKey))throw new McpRpcError({code:-32602,\n message:'Administrative discovery uses a closed target and optional exact tool key; runtime domain/task filters are not admission.',data:{xyraCode:'XYRA.MCP.REQUEST_INVALID'}});\n if (filters?.domainId) params.domainId = filters.domainId;\n if (filters?.taskKey) params.taskKey = filters.taskKey;\n if (filters?.toolKey) params.toolKey = filters.toolKey;\n if (cursor) params.cursor = cursor;\n const result = await this.request<ToolsListResult>('tools/list', params);\n tools.push(...(result.tools ?? []));\n cursor = result.nextCursor;\n if (filters?.limit && tools.length >= filters.limit) return tools.slice(0, filters.limit);\n } while (cursor);\n return tools;\n }\n\n async describeTool(toolKey: string): Promise<McpTool | undefined> {\n const byKey = await this.listTools({ toolKey });\n if (byKey.length > 0) return byKey.find((tool) => tool.name === toolKey) ?? byKey[0];\n const all = await this.listTools();\n return all.find((tool) => tool.name === toolKey);\n }\n\n callTool(name: string, args: Record<string, unknown>, options?: RpcCallOptions, control?: ConfirmationControl): Promise<ToolCallResult> {\n return this.request<ToolCallResult>('tools/call', {\n name,\n arguments: args,\n ...(control?.confirmationRequestId\n ? { _meta: { 'com.experiture.xyra/confirmationRequestId': control.confirmationRequestId } }\n : {}),\n }, options);\n }\n\n listConfirmations(params: { status?: string[]; toolKey?: string; limit?: number; includeAll?: boolean } = {}): Promise<ConfirmationListResult> {\n this.assertConfirmationExtension();\n return this.request<ConfirmationListResult>('xyra/confirmations/list', params);\n }\n\n getConfirmation(id: string): Promise<Record<string, unknown>> {\n this.assertConfirmationExtension();\n return this.request('xyra/confirmations/get', { id });\n }\n\n approveConfirmation(id: string): Promise<Record<string, unknown>> {\n this.assertConfirmationExtension();\n return this.request('xyra/confirmations/approve', { id });\n }\n\n rejectConfirmation(id: string, reason?: string): Promise<Record<string, unknown>> {\n this.assertConfirmationExtension();\n return this.request('xyra/confirmations/reject', { id, ...(reason ? { reason } : {}) });\n }\n\n cancelConfirmation(id: string): Promise<Record<string, unknown>> {\n this.assertConfirmationExtension();\n return this.request('xyra/confirmations/cancel', { id });\n }\n\n chat(params: McpChatRequest): Promise<McpChatResult> {\n this.assertChatExtension();\n return this.request<McpChatResult>('xyra/chat', params as unknown as Record<string, unknown>);\n }\n}\n", "import { McpError } from '@modelcontextprotocol/sdk/types.js';\n\nexport interface JsonRpcError {\n code: number;\n message: string;\n data?: unknown;\n}\n\n/** Wraps a canonical MCP error so the formatter preserves code and data. */\nexport class McpRpcError extends Error {\n readonly rpc: JsonRpcError;\n\n constructor(rpc: JsonRpcError) {\n super(rpc.message);\n this.name = 'McpRpcError';\n this.rpc = rpc;\n }\n\n static from(error: unknown): McpRpcError | null {\n return error instanceof McpError\n ? new McpRpcError({ code: error.code, message: error.message, data: error.data })\n : null;\n }\n}\n", "import crypto from 'node:crypto';\nimport { context, trace, TraceFlags, type Context } from '@opentelemetry/api';\nimport { W3CTraceContextPropagator } from '@opentelemetry/core';\nimport type { OutputWriter } from '../output/console';\n\nexport interface LatencyPhaseRecord {\n name: string;\n durationMs: number;\n metadata?: Record<string, string | number | boolean>;\n}\n\nexport interface LatencyLinkage {\n traceId?: string;\n correlationId?: string;\n serverTiming?: string;\n}\n\nexport interface LatencyReport {\n schemaVersion: 1;\n generatedAt: string;\n totalDurationMs: number;\n phases: LatencyPhaseRecord[];\n linkage: LatencyLinkage;\n}\n\ntype LatencyMode = 'human' | 'json';\n\nlet configuredMode: LatencyMode | undefined;\nlet activeDiagnostics: LatencyDiagnostics | undefined;\n\nfunction elapsedMs(startedAt: number): number {\n return Math.round((performance.now() - startedAt) * 100) / 100;\n}\n\nfunction validTraceId(value: string | null): value is string {\n return Boolean(value && /^[0-9a-f]{32}$/i.test(value) && !/^0{32}$/.test(value));\n}\n\nexport class LatencyDiagnostics {\n private readonly startedAt = performance.now();\n private readonly records: LatencyPhaseRecord[] = [];\n private readonly linkage: LatencyLinkage = {};\n private readonly traceContext: Context;\n\n constructor(readonly mode: LatencyMode) {\n const traceId = crypto.randomBytes(16).toString('hex');\n const spanId = crypto.randomBytes(8).toString('hex');\n this.linkage.traceId = traceId;\n this.traceContext = trace.setSpanContext(context.active(), {\n traceId,\n spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n });\n }\n\n async measure<T>(\n name: string,\n fn: () => Promise<T> | T,\n metadata?: Record<string, string | number | boolean>,\n ): Promise<T> {\n const startedAt = performance.now();\n try {\n return await fn();\n } finally {\n this.records.push({ name, durationMs: elapsedMs(startedAt), ...(metadata ? { metadata } : {}) });\n }\n }\n\n record(name: string, durationMs: number, metadata?: Record<string, string | number | boolean>): void {\n this.records.push({ name, durationMs: Math.round(durationMs * 100) / 100, ...(metadata ? { metadata } : {}) });\n }\n\n injectTraceHeaders(headers: Headers): void {\n new W3CTraceContextPropagator().inject(this.traceContext, headers, {\n set(carrier, key, value) {\n carrier.set(key, value);\n },\n });\n }\n\n observeResponseHeaders(headers: Headers): void {\n const serverTraceId = headers.get('x-trace-id');\n if (validTraceId(serverTraceId)) this.linkage.traceId = serverTraceId.toLowerCase();\n const correlationId = headers.get('x-correlation-id');\n if (correlationId) this.linkage.correlationId = correlationId;\n const serverTiming = headers.get('server-timing');\n if (serverTiming) this.linkage.serverTiming = serverTiming;\n }\n\n report(): LatencyReport {\n return {\n schemaVersion: 1,\n generatedAt: new Date().toISOString(),\n totalDurationMs: elapsedMs(this.startedAt),\n phases: [...this.records],\n linkage: { ...this.linkage },\n };\n }\n}\n\nexport function configureLatencyDiagnostics(options: { timings?: boolean; timingsJson?: boolean }): void {\n configuredMode = options.timingsJson ? 'json' : options.timings ? 'human' : undefined;\n}\n\nexport function beginLatencyDiagnostics(): LatencyDiagnostics | undefined {\n activeDiagnostics = configuredMode ? new LatencyDiagnostics(configuredMode) : undefined;\n return activeDiagnostics;\n}\n\nexport function getLatencyDiagnostics(): LatencyDiagnostics | undefined {\n return activeDiagnostics;\n}\n\nexport function endLatencyDiagnostics(): void {\n activeDiagnostics = undefined;\n}\n\nexport async function measureLatencyPhase<T>(\n name: string,\n fn: () => Promise<T> | T,\n metadata?: Record<string, string | number | boolean>,\n): Promise<T> {\n return activeDiagnostics\n ? activeDiagnostics.measure(name, fn, metadata)\n : fn();\n}\n\nexport function createTimedOutputWriter(writer: OutputWriter): OutputWriter {\n return {\n out(message) {\n const startedAt = performance.now();\n try {\n writer.out(message);\n } finally {\n activeDiagnostics?.record('output.render', elapsedMs(startedAt), { stream: 'stdout' });\n }\n },\n err(message) {\n const startedAt = performance.now();\n try {\n writer.err(message);\n } finally {\n activeDiagnostics?.record('output.render', elapsedMs(startedAt), { stream: 'stderr' });\n }\n },\n };\n}\n\nexport function emitLatencyDiagnostics(diagnostics: LatencyDiagnostics, writer: OutputWriter): void {\n const report = diagnostics.report();\n if (diagnostics.mode === 'json') {\n writer.err(JSON.stringify(report));\n return;\n }\n const rows = report.phases.map((phase) => ` ${phase.name}: ${phase.durationMs.toFixed(2)} ms`);\n writer.err([\n `Latency diagnostics: ${report.totalDurationMs.toFixed(2)} ms total`,\n ...rows,\n ...(report.linkage.serverTiming ? [` server-timing: ${report.linkage.serverTiming}`] : []),\n ...(report.linkage.traceId ? [` trace-id: ${report.linkage.traceId}`] : []),\n ...(report.linkage.correlationId ? [` correlation-id: ${report.linkage.correlationId}`] : []),\n ].join('\\n'));\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
6
|
-
"names": ["exports", "parseXyraAdministrationTargetV1"
|
|
3
|
+
"sources": ["../../../../libs/xyra-types/src/xyra-administration.ts", "../../src/mcp/mcpClient.ts", "../../src/diagnostics/latency.ts"],
|
|
4
|
+
"sourcesContent": ["import type { XyraRuntimeIdentityV2 } from './context';\n\n/** A requested maintenance target. It is never a runtime identity or an authorization decision. */\nexport type XyraAdministrationTargetV1 =\n | Readonly<{ targetKind: 'global-resource'; managedProductId: 'xyra-ai' }>\n | Readonly<{ targetKind: 'configuration-owner'; configurationTenantId: string; managedProductId: string }>\n | Readonly<{ targetKind: 'customer-resource'; targetTenantId: string; activeProductId: string }>;\n\n/** Selects a candidate from verified runtime facts. Auth must still admit the exact action. */\nexport function runtimeAdministrationTarget(identity: XyraRuntimeIdentityV2): XyraAdministrationTargetV1 {\n return identity.licenseSourceProductId !== identity.licensedProductId\n && identity.tenantId === identity.licenseOwnerTenantId\n ? { targetKind: 'configuration-owner', configurationTenantId: identity.licenseOwnerTenantId,\n managedProductId: identity.licenseSourceProductId }\n : { targetKind: 'customer-resource', targetTenantId: identity.tenantId, activeProductId: identity.productId };\n}\n\nexport type XyraAccessPurposeV1 = 'runtime' | 'administration';\nexport type XyraAuthorityDecisionPhaseV1 = 'discovery' | 'execution';\nexport type XyraConfigurationAccess = 'read' | 'manage' | 'manage_selection';\n\nexport type XyraAdministrationRequestV1 = Readonly<{\n operationId: string;\n target: XyraAdministrationTargetV1;\n}>;\n\n/** Auth-resolved relationship facts, without a permission snapshot or runtime licence grant. */\nexport type XyraAdministrationResolvedTargetV1 =\n | Readonly<{ targetKind: 'global-resource'; managedProductId: 'xyra-ai'; relationshipKind: 'global-resource' }>\n | Readonly<{ targetKind: 'configuration-owner' | 'customer-resource'; managedProductId: string;\n relationshipKind: 'native-product-tenant'; activeProductId: 'xyra-ai'; actualTenantId: string;\n licensedProductId: 'xyra-ai'; commercialState: string }>\n | Readonly<{ targetKind: 'configuration-owner' | 'customer-resource'; managedProductId: string;\n relationshipKind: 'embedded-product-entitlement'; activeProductId: string; actualTenantId: string;\n licenseSourceProductId: string; licensedProductId: 'xyra-ai'; licenseOwnerTenantId: string;\n bindingId: string; entitlementId: string; sourceEntitlementId: string; commercialState: string }>;\n\nexport type XyraAdministrationDecisionV1 = Readonly<{\n operationId: string;\n purpose: XyraAuthorityDecisionPhaseV1;\n accessPurpose: 'administration';\n allowed: boolean;\n code: string;\n productId: 'xyra-ai';\n operatorTenantId: string | null;\n targetTenantId: string | null;\n grantId: string | null;\n target: XyraAdministrationTargetV1;\n resolvedTarget: XyraAdministrationResolvedTargetV1 | null;\n /** Optional Auth-owned projection requested during a rolling service release. */\n configurationAccess?: XyraConfigurationAccess;\n}>;\n\n/** Protected execution/approval scope, not a permission grant and never a public argument. */\nexport type XyraAdministrationExecutionScopeV1 = Readonly<{\n accessPurpose: 'administration';\n resourceAudience: string;\n administrationTransport: 'native-http' | 'delegated-oauth';\n actorOperatorTenantId: string | null;\n targetHash: string;\n target: XyraAdministrationTargetV1;\n resolvedTarget: XyraAdministrationResolvedTargetV1;\n}>;\n\nconst identifier = (value: unknown): value is string => typeof value === 'string'\n && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,49}$/.test(value);\nconst guid = (value: unknown): value is string => typeof value === 'string'\n && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value)\n && value !== '00000000-0000-0000-0000-000000000000';\nconst record = (value: unknown): value is Record<string, unknown> => value !== null\n && typeof value === 'object' && !Array.isArray(value);\nconst exact = (value: Record<string, unknown>, keys: readonly string[]): boolean =>\n Object.keys(value).length === keys.length && keys.every(key => Object.prototype.hasOwnProperty.call(value, key));\n\n/** Strictly parse the closed object shape; raw duplicate JSON keys belong to the transport parser. */\nexport function parseXyraAdministrationTargetV1(value: unknown): XyraAdministrationTargetV1 | null {\n if (!record(value)) return null;\n if (value.targetKind === 'global-resource' && exact(value, ['targetKind', 'managedProductId'])\n && value.managedProductId === 'xyra-ai') {\n return { targetKind: 'global-resource', managedProductId: 'xyra-ai' };\n }\n if (value.targetKind === 'configuration-owner'\n && exact(value, ['targetKind', 'configurationTenantId', 'managedProductId'])\n && identifier(value.configurationTenantId) && identifier(value.managedProductId)) {\n return { targetKind: 'configuration-owner', configurationTenantId: value.configurationTenantId,\n managedProductId: value.managedProductId };\n }\n if (value.targetKind === 'customer-resource'\n && exact(value, ['targetKind', 'targetTenantId', 'activeProductId'])\n && identifier(value.targetTenantId) && identifier(value.activeProductId)) {\n return { targetKind: 'customer-resource', targetTenantId: value.targetTenantId, activeProductId: value.activeProductId };\n }\n return null;\n}\n\n/** Stable exact tuple for cache/request binding, excluding display text and mutable capabilities. */\nexport function xyraAdministrationTargetKeyV1(target: XyraAdministrationTargetV1): string {\n return JSON.stringify(target.targetKind === 'global-resource'\n ? [target.targetKind, target.managedProductId]\n : target.targetKind === 'configuration-owner'\n ? [target.targetKind, target.configurationTenantId, target.managedProductId]\n : [target.targetKind, target.targetTenantId, target.activeProductId]);\n}\n\n/** Validate independent Auth facts against the exact request, never infer a missing relationship. */\nexport function parseXyraAdministrationResolvedTargetV1(\n value: unknown, target: XyraAdministrationTargetV1,\n): XyraAdministrationResolvedTargetV1 | null {\n if (!record(value) || value.targetKind !== target.targetKind) return null;\n const managedProductId = target.targetKind === 'customer-resource' ? 'xyra-ai' : target.managedProductId;\n if (value.managedProductId !== managedProductId) return null;\n if (target.targetKind === 'global-resource') {\n return exact(value, ['targetKind', 'managedProductId', 'relationshipKind']) && value.relationshipKind === 'global-resource'\n ? { targetKind: 'global-resource', managedProductId: 'xyra-ai', relationshipKind: 'global-resource' } : null;\n }\n const base = ['targetKind', 'managedProductId', 'relationshipKind', 'activeProductId', 'actualTenantId', 'licensedProductId', 'commercialState'];\n const embedded = ['licenseSourceProductId', 'licenseOwnerTenantId', 'bindingId', 'entitlementId', 'sourceEntitlementId'];\n const isNative = value.relationshipKind === 'native-product-tenant';\n if ((!isNative && value.relationshipKind !== 'embedded-product-entitlement')\n || !exact(value, isNative ? base : [...base, ...embedded]) || value.licensedProductId !== 'xyra-ai'\n || !base.filter(key => !['targetKind', 'relationshipKind'].includes(key)).every(key => identifier(value[key]))\n || (isNative ? value.activeProductId !== 'xyra-ai' : !embedded.every(key => identifier(value[key])))\n || value.actualTenantId !== (target.targetKind === 'customer-resource' ? target.targetTenantId : target.configurationTenantId)\n || (target.targetKind === 'customer-resource' && value.activeProductId !== target.activeProductId)\n || (target.targetKind === 'configuration-owner' && value.activeProductId !== target.managedProductId)\n || (!isNative && (value.activeProductId !== value.licenseSourceProductId && value.activeProductId !== value.licensedProductId\n || !['bindingId', 'entitlementId', 'sourceEntitlementId'].every(key => guid(value[key]))\n || (target.targetKind === 'configuration-owner' && (value.licenseOwnerTenantId !== target.configurationTenantId\n || value.licenseSourceProductId !== target.managedProductId))))) return null;\n return { ...value } as XyraAdministrationResolvedTargetV1;\n}\n\n/** Parse a decision only for the operation, phase and target that were actually requested. */\nexport function parseXyraAdministrationDecisionV1(value: unknown,\n request: XyraAdministrationRequestV1, purpose: XyraAuthorityDecisionPhaseV1,\n): XyraAdministrationDecisionV1 | null {\n if (!record(value) || !exact(value, ['operationId', 'purpose', 'accessPurpose', 'allowed', 'code', 'productId',\n 'operatorTenantId', 'targetTenantId', 'grantId', 'target', 'resolvedTarget',\n ...(Object.prototype.hasOwnProperty.call(value, 'configurationAccess') ? ['configurationAccess'] : [])])\n || (value.configurationAccess !== undefined && !['read', 'manage', 'manage_selection'].includes(String(value.configurationAccess)))\n || value.operationId !== request.operationId || value.purpose !== purpose || value.accessPurpose !== 'administration'\n || value.productId !== 'xyra-ai' || typeof value.allowed !== 'boolean' || typeof value.code !== 'string'\n || !/^[A-Z0-9_.]{1,160}$/.test(value.code)\n || !(value.operatorTenantId === null || identifier(value.operatorTenantId))\n || !(value.grantId === null || guid(value.grantId))) return null;\n const target = parseXyraAdministrationTargetV1(value.target);\n if (!target || xyraAdministrationTargetKeyV1(target) !== xyraAdministrationTargetKeyV1(request.target)\n || value.targetTenantId !== (target.targetKind === 'global-resource' ? null\n : target.targetKind === 'configuration-owner' ? target.configurationTenantId : target.targetTenantId)) return null;\n const resolvedTarget = parseXyraAdministrationResolvedTargetV1(value.resolvedTarget, target);\n if (value.allowed) {\n if (!resolvedTarget) return null;\n if (value.code === 'AUTHORIZATION.ALLOWED.SAME_TENANT') {\n if (target.targetKind !== 'customer-resource' || value.operatorTenantId !== target.targetTenantId\n || value.grantId !== null) return null;\n } else if (value.code === 'AUTHORIZATION.ALLOWED.SUPER_USER'\n ? value.operatorTenantId !== null || value.grantId !== null\n : !['AUTHORIZATION.ALLOWED', 'AUTHORIZATION.ALLOWED.LICENSEE'].includes(value.code) || value.operatorTenantId === null || value.grantId === null) return null;\n if (value.code === 'AUTHORIZATION.ALLOWED.LICENSEE'\n && (target.targetKind === 'global-resource' || resolvedTarget.relationshipKind !== 'embedded-product-entitlement'\n || resolvedTarget.licenseOwnerTenantId !== value.operatorTenantId)) return null;\n } else if (value.code.startsWith('AUTHORIZATION.ALLOWED') || value.resolvedTarget !== null) return null;\n return { ...value, target, resolvedTarget } as XyraAdministrationDecisionV1;\n}\n", "import { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport type { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport { ResultSchema } from '@modelcontextprotocol/sdk/types.js';\nimport type {\n XyraRuntimeActionDescriptor,\n XyraPendingHumanApprovalV1,\n XyraRuntimeResponse,\n XyraRuntimeStreamOutcome,\n XyraRuntimeTurnStatusV1,\n XyraHumanApprovalViewV1,\n} from '@experiture/xyra-runtime-client';\nimport { CliError, CliErrorCodes } from '../errors/CliError';\nimport { McpRpcError } from './mcpError';\nimport { measureLatencyPhase } from '../diagnostics/latency';\nimport {parseXyraAdministrationTargetV1,type XyraAdministrationTargetV1}from'@xyra/types/xyra-administration';\nimport type { XyraGovernanceApprovalContinuationV1 } from '@xyra/types';\n\nexport interface RpcCallOptions {\n /** Exact JSON-RPC envelope captured from a JSON Streamable HTTP response. */\n captureRaw?: (raw: unknown) => void;\n}\n\nexport class McpRawResponseCapture {\n private callback?: (raw: unknown) => void;\n\n begin(callback?: (raw: unknown) => void): void {\n this.callback = callback;\n }\n\n end(): void {\n this.callback = undefined;\n }\n\n async observe(response: Response): Promise<void> {\n if (!this.callback || !response.headers.get('content-type')?.includes('application/json')) return;\n try {\n this.callback(await response.clone().json());\n } catch {\n // The SDK remains the protocol authority; raw capture is diagnostic only.\n }\n }\n}\n\nexport interface McpTool {\n name: string;\n title?: string;\n description?: string;\n inputSchema?: unknown;\n outputSchema?: unknown;\n annotations?: Record<string, unknown>;\n _meta?: Record<string, unknown>;\n}\n\ninterface ToolsListResult {\n tools: McpTool[];\n nextCursor?: string;\n}\n\nexport interface ToolCallResult {\n content?: unknown;\n structuredContent?: unknown;\n isError?: boolean;\n [key: string]: unknown;\n}\n\nexport interface ConfirmationControl {\n conversationId?: string;\n confirmationRequestId?: string;\n workflowResume?: {executionId:string;expectedRevision:number;continueCorrection?:true;guidance?:string};\n}\n\n/** Resume only the checkpoint revision published by the existing execution owner. */\nexport function workflowResumeControlFor(result: ToolCallResult, toolKey: string, executionId: string): { workflowResume: NonNullable<ConfirmationControl['workflowResume']> } | undefined {\n const envelope = result.structuredContent as { continuation?: unknown } | undefined;\n const metadata = result._meta as Record<string, unknown> | undefined;\n const value = envelope?.continuation ?? metadata?.['com.experiture.xyra/workflowContinuation'];\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;\n const reference = value as Record<string, unknown>;\n if (reference.executionId !== executionId || reference.toolKey !== toolKey\n || !Number.isSafeInteger(reference.revision) || Number(reference.revision) < 0) return undefined;\n return { workflowResume: { executionId, expectedRevision: Number(reference.revision) } };\n}\n\nexport function validateToolConversationId(value: string | undefined): string | undefined {\n if (value !== undefined && (typeof value !== 'string' || value !== value.trim() || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value))) {\n throw new CliError(CliErrorCodes.InvalidArguments, '--conversation must be a conversation UUID.');\n }\n return value;\n}\n\nexport interface ConfirmationListResult {\n confirmations: Record<string, unknown>[];\n count: number;\n}\n\nexport interface McpChatRequest {\n conversationId?: string;\n createConversation?: boolean;\n title?: string;\n message: string;\n locale?: 'en' | 'fr' | 'zh-Hans';\n clientRequestId?: string;\n}\n\nexport interface McpChatRecoveryResult {\n schemaVersion:1;mode:'observe';conversationId:string;clientRequestId:string;runtimeTurnId?:string;\n status:XyraRuntimeTurnStatusV1;outcome:XyraRuntimeStreamOutcome|'waiting';assistantMessageId?:string;message?:string;\n recovery:{state:'completed'|'waiting'|'denied'|'unavailable';code?:string};eventCount:0;chunkCount:0;\n}\n\nexport interface McpChatResult {\n schemaVersion: 1;\n conversationId: string;\n clientRequestId: string;\n requestId: string;\n executionId: string;\n streamId: string;\n traceId?: string;\n userMessageId: string;\n assistantMessageId?: string;\n outcome: XyraRuntimeStreamOutcome;\n message?: string;\n response?: XyraRuntimeResponse;\n error?: unknown;\n actions?: XyraRuntimeActionDescriptor[];\n pendingHumanApproval?: XyraPendingHumanApprovalV1;\n confirmation?: XyraHumanApprovalViewV1;\n eventCount: number;\n chunkCount: number;\n createdConversation?: {\n id: string;\n title: string;\n titleSource: string;\n createdAt: string;\n };\n}\n\nexport class McpClient {\n constructor(\n private readonly sdk: Client,\n private readonly transport: StreamableHTTPClientTransport,\n private readonly rawCapture?: McpRawResponseCapture,\n private readonly administrationTarget?:XyraAdministrationTargetV1,\n ) {\n if(administrationTarget){\n const selected=parseXyraAdministrationTargetV1(administrationTarget);\n if(!selected)throw new McpRpcError({code:-32602,message:'Select one closed administration target.',data:{xyraCode:'XYRA.MCP.REQUEST_INVALID'}});\n this.administrationTarget=selected;\n }\n }\n\n initialize(): unknown {\n return {\n protocolVersion: this.transport.protocolVersion,\n capabilities: this.sdk.getServerCapabilities() ?? {},\n serverInfo: this.sdk.getServerVersion() ?? {},\n instructions: this.sdk.getInstructions(),\n };\n }\n\n private async request<T>(method: string, params: Record<string, unknown> = {}, options?: RpcCallOptions): Promise<T> {\n if(this.administrationTarget){\n if(method==='xyra/chat'||['xyra/confirmations/approve','xyra/confirmations/reject','xyra/confirmations/cancel','xyra/confirmations/continue'].includes(method))\n throw new McpRpcError({code:-32602,message:'Administrative delegated sessions cannot run chat or decide approvals.',data:{xyraCode:'XYRA.AUTH.INSUFFICIENT_PERMISSIONS'}});\n if(method==='tools/list'||method==='tools/call')params={...params,target:this.administrationTarget};\n }\n this.rawCapture?.begin(options?.captureRaw);\n try {\n return await measureLatencyPhase(\n 'mcp.method',\n () => this.sdk.request({ method, params } as never, ResultSchema) as Promise<T>,\n { method },\n );\n } catch (error) {\n throw McpRpcError.from(error) ?? error;\n } finally {\n this.rawCapture?.end();\n }\n }\n\n private assertConfirmationExtension(method?: string): void {\n const experimental = this.sdk.getServerCapabilities()?.experimental;\n const extension = experimental?.['com.experiture.xyra.confirmations'] as Record<string, unknown> | undefined;\n if (extension?.version !== 1 || (method && (!Array.isArray(extension.methods) || !extension.methods.includes(method)))) {\n throw new McpRpcError({\n code: -32602,\n message: 'The server did not negotiate the Xyra confirmation extension.',\n data: { xyraCode: 'XYRA.MCP.EXTENSION_NOT_NEGOTIATED' },\n });\n }\n }\n\n private assertChatExtension(): void {\n const experimental = this.sdk.getServerCapabilities()?.experimental;\n const extension = experimental?.['com.experiture.xyra.chat'] as Record<string, unknown> | undefined;\n if (extension?.version !== 1) {\n throw new McpRpcError({\n code: -32602,\n message: 'The server did not negotiate the Xyra chat extension.',\n data: { xyraCode: 'XYRA.MCP.EXTENSION_NOT_NEGOTIATED' },\n });\n }\n }\n\n /** Page through every visible tool unless a hard limit is supplied. */\n async listTools(filters?: { domainId?: string; taskKey?: string; toolKey?: string; limit?: number }): Promise<McpTool[]> {\n const tools: McpTool[] = [];\n let cursor: string | undefined;\n do {\n const params: Record<string, unknown> = {};\n if(this.administrationTarget&&(filters?.domainId||filters?.taskKey))throw new McpRpcError({code:-32602,\n message:'Administrative discovery uses a closed target and optional exact tool key; runtime domain/task filters are not admission.',data:{xyraCode:'XYRA.MCP.REQUEST_INVALID'}});\n if (filters?.domainId) params.domainId = filters.domainId;\n if (filters?.taskKey) params.taskKey = filters.taskKey;\n if (filters?.toolKey) params.toolKey = filters.toolKey;\n if (cursor) params.cursor = cursor;\n const result = await this.request<ToolsListResult>('tools/list', params);\n tools.push(...(result.tools ?? []));\n cursor = result.nextCursor;\n if (filters?.limit && tools.length >= filters.limit) return tools.slice(0, filters.limit);\n } while (cursor);\n return tools;\n }\n\n async describeTool(toolKey: string): Promise<McpTool | undefined> {\n const byKey = await this.listTools({ toolKey });\n if (byKey.length > 0) return byKey.find((tool) => tool.name === toolKey) ?? byKey[0];\n const all = await this.listTools();\n return all.find((tool) => tool.name === toolKey);\n }\n\n callTool(name: string, args: Record<string, unknown>, options?: RpcCallOptions, control?: ConfirmationControl): Promise<ToolCallResult> {\n const conversationId = validateToolConversationId(control?.conversationId);\n return this.request<ToolCallResult>('tools/call', {\n ...(conversationId ? { conversationId } : {}),\n name,\n arguments: args,\n ...(control?.confirmationRequestId || control?.workflowResume ? { _meta: {\n ...(control.confirmationRequestId ? {'com.experiture.xyra/confirmationRequestId':control.confirmationRequestId}:{}),\n ...(control.workflowResume ? {'com.experiture.xyra/workflowResume':control.workflowResume}:{})} } : {}),\n }, options);\n }\n\n listConfirmations(params: { status?: string[]; toolKey?: string; limit?: number; includeAll?: boolean } = {}): Promise<ConfirmationListResult> {\n this.assertConfirmationExtension();\n return this.request<ConfirmationListResult>('xyra/confirmations/list', params);\n }\n\n getConfirmation(id: string): Promise<Record<string, unknown>> {\n this.assertConfirmationExtension();\n return this.request('xyra/confirmations/get', { id });\n }\n\n approveConfirmation(id: string): Promise<Record<string, unknown>> {\n this.assertConfirmationExtension();\n return this.request('xyra/confirmations/approve', { id });\n }\n\n rejectConfirmation(id: string, reason?: string): Promise<Record<string, unknown>> {\n this.assertConfirmationExtension();\n return this.request('xyra/confirmations/reject', { id, ...(reason ? { reason } : {}) });\n }\n\n cancelConfirmation(id: string): Promise<Record<string, unknown>> {\n this.assertConfirmationExtension();\n return this.request('xyra/confirmations/cancel', { id });\n }\n\n async continueGovernanceApproval(id: string, expected?: XyraGovernanceApprovalContinuationV1['continuation'], options?: RpcCallOptions): Promise<XyraGovernanceApprovalContinuationV1> {\n this.assertConfirmationExtension('xyra/confirmations/continue');\n const result = await this.request<XyraGovernanceApprovalContinuationV1>('xyra/confirmations/continue', { id }, options);\n if (result?.schemaVersion !== 1 || !['pending', 'completed', 'failed', 'canceled'].includes(result.status)\n || result.confirmation?.id !== id || result.continuation?.kind !== 'governance_change_set'\n || typeof result.continuation.changeSetId !== 'string' || !result.continuation.changeSetId\n || typeof result.continuation.changeSetHash !== 'string' || !result.continuation.changeSetHash\n || (expected && (result.continuation.changeSetId !== expected.changeSetId || result.continuation.changeSetHash !== expected.changeSetHash))\n || result.changeSet?.id !== result.continuation.changeSetId || (result.status === 'completed' && result.changeSet.status !== 'applied')) {\n throw new McpRpcError({ code: -32603, message: 'The governance continuation did not match its original approval and change set.',\n data: { xyraCode: 'XYRA.MCP.RESULT_SCHEMA_MISMATCH' } });\n }\n return result;\n }\n\n resumeChat(params:{conversationId:string;clientRequestId:string;control?:{resumeExecutionId:string;expectedRevision:number;guidance?:string}}):Promise<McpChatRecoveryResult> {\n this.assertChatExtension();\n return this.request<McpChatRecoveryResult>('xyra/chat',{...params,resumeRetainedWork:true});\n }\n\n getWorkflowProposal(params:{conversationId:string;clientRequestId:string;executionId:string;revision:number;stepKey:string}):Promise<import('@experiture/xyra-runtime-client').XyraWorkflowInputProposalV1> {\n this.assertChatExtension();const {conversationId,clientRequestId,...readProposal}=params;return this.request('xyra/chat',{conversationId,clientRequestId,readProposal});\n }\n\n stopChat(params:{conversationId:string;clientRequestId:string}):Promise<unknown> {\n this.assertChatExtension();return this.request('xyra/chat',{...params,stopRetainedWork:true});\n }\n\n chat(params: McpChatRequest): Promise<McpChatResult> {\n this.assertChatExtension();\n return this.request<McpChatResult>('xyra/chat', params as unknown as Record<string, unknown>);\n }\n}\n", "import crypto from 'node:crypto';\nimport { context, trace, TraceFlags, type Context } from '@opentelemetry/api';\nimport { W3CTraceContextPropagator } from '@opentelemetry/core';\nimport type { OutputWriter } from '../output/console';\n\nexport interface LatencyPhaseRecord {\n name: string;\n durationMs: number;\n metadata?: Record<string, string | number | boolean>;\n}\n\nexport interface LatencyLinkage {\n traceId?: string;\n correlationId?: string;\n serverTiming?: string;\n}\n\nexport interface LatencyReport {\n schemaVersion: 1;\n generatedAt: string;\n totalDurationMs: number;\n phases: LatencyPhaseRecord[];\n linkage: LatencyLinkage;\n}\n\ntype LatencyMode = 'human' | 'json';\n\nlet configuredMode: LatencyMode | undefined;\nlet activeDiagnostics: LatencyDiagnostics | undefined;\n\nfunction elapsedMs(startedAt: number): number {\n return Math.round((performance.now() - startedAt) * 100) / 100;\n}\n\nfunction validTraceId(value: string | null): value is string {\n return Boolean(value && /^[0-9a-f]{32}$/i.test(value) && !/^0{32}$/.test(value));\n}\n\nexport class LatencyDiagnostics {\n private readonly startedAt = performance.now();\n private readonly records: LatencyPhaseRecord[] = [];\n private readonly linkage: LatencyLinkage = {};\n private readonly traceContext: Context;\n\n constructor(readonly mode: LatencyMode) {\n const traceId = crypto.randomBytes(16).toString('hex');\n const spanId = crypto.randomBytes(8).toString('hex');\n this.linkage.traceId = traceId;\n this.traceContext = trace.setSpanContext(context.active(), {\n traceId,\n spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n });\n }\n\n async measure<T>(\n name: string,\n fn: () => Promise<T> | T,\n metadata?: Record<string, string | number | boolean>,\n ): Promise<T> {\n const startedAt = performance.now();\n try {\n return await fn();\n } finally {\n this.records.push({ name, durationMs: elapsedMs(startedAt), ...(metadata ? { metadata } : {}) });\n }\n }\n\n record(name: string, durationMs: number, metadata?: Record<string, string | number | boolean>): void {\n this.records.push({ name, durationMs: Math.round(durationMs * 100) / 100, ...(metadata ? { metadata } : {}) });\n }\n\n injectTraceHeaders(headers: Headers): void {\n new W3CTraceContextPropagator().inject(this.traceContext, headers, {\n set(carrier, key, value) {\n carrier.set(key, value);\n },\n });\n }\n\n observeResponseHeaders(headers: Headers): void {\n const serverTraceId = headers.get('x-trace-id');\n if (validTraceId(serverTraceId)) this.linkage.traceId = serverTraceId.toLowerCase();\n const correlationId = headers.get('x-correlation-id');\n if (correlationId) this.linkage.correlationId = correlationId;\n const serverTiming = headers.get('server-timing');\n if (serverTiming) this.linkage.serverTiming = serverTiming;\n }\n\n report(): LatencyReport {\n return {\n schemaVersion: 1,\n generatedAt: new Date().toISOString(),\n totalDurationMs: elapsedMs(this.startedAt),\n phases: [...this.records],\n linkage: { ...this.linkage },\n };\n }\n}\n\nexport function configureLatencyDiagnostics(options: { timings?: boolean; timingsJson?: boolean }): void {\n configuredMode = options.timingsJson ? 'json' : options.timings ? 'human' : undefined;\n}\n\nexport function beginLatencyDiagnostics(): LatencyDiagnostics | undefined {\n activeDiagnostics = configuredMode ? new LatencyDiagnostics(configuredMode) : undefined;\n return activeDiagnostics;\n}\n\nexport function getLatencyDiagnostics(): LatencyDiagnostics | undefined {\n return activeDiagnostics;\n}\n\nexport function endLatencyDiagnostics(): void {\n activeDiagnostics = undefined;\n}\n\nexport async function measureLatencyPhase<T>(\n name: string,\n fn: () => Promise<T> | T,\n metadata?: Record<string, string | number | boolean>,\n): Promise<T> {\n return activeDiagnostics\n ? activeDiagnostics.measure(name, fn, metadata)\n : fn();\n}\n\nexport function createTimedOutputWriter(writer: OutputWriter): OutputWriter {\n return {\n out(message) {\n const startedAt = performance.now();\n try {\n writer.out(message);\n } finally {\n activeDiagnostics?.record('output.render', elapsedMs(startedAt), { stream: 'stdout' });\n }\n },\n err(message) {\n const startedAt = performance.now();\n try {\n writer.err(message);\n } finally {\n activeDiagnostics?.record('output.render', elapsedMs(startedAt), { stream: 'stderr' });\n }\n },\n };\n}\n\nexport function emitLatencyDiagnostics(diagnostics: LatencyDiagnostics, writer: OutputWriter): void {\n const report = diagnostics.report();\n if (diagnostics.mode === 'json') {\n writer.err(JSON.stringify(report));\n return;\n }\n const rows = report.phases.map((phase) => ` ${phase.name}: ${phase.durationMs.toFixed(2)} ms`);\n writer.err([\n `Latency diagnostics: ${report.totalDurationMs.toFixed(2)} ms total`,\n ...rows,\n ...(report.linkage.serverTiming ? [` server-timing: ${report.linkage.serverTiming}`] : []),\n ...(report.linkage.traceId ? [` trace-id: ${report.linkage.traceId}`] : []),\n ...(report.linkage.correlationId ? [` correlation-id: ${report.linkage.correlationId}`] : []),\n ].join('\\n'));\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,IAAAA,SAAA,8BAAA;AAkEA,IAAAA,SAAA,kCAAAC;AAqBA,IAAAD,SAAA,gCAAA;AASA,IAAAA,SAAA,0CAAA;AA4BA,IAAAA,SAAA,oCAAA;AA5HA,aAAgB,4BAA4B,UAA+B;AACzE,aAAO,SAAS,2BAA2B,SAAS,qBAC/C,SAAS,aAAa,SAAS,uBAChC;QAAE,YAAY;QAAuB,uBAAuB,SAAS;QACnE,kBAAkB,SAAS;MAAsB,IACnD,EAAE,YAAY,qBAAqB,gBAAgB,SAAS,UAAU,iBAAiB,SAAS,UAAS;IAC/G;AAiDA,QAAM,aAAa,CAAC,UAAoC,OAAO,UAAU,YACpE,qCAAqC,KAAK,KAAK;AACpD,QAAM,OAAO,CAAC,UAAoC,OAAO,UAAU,YAC9D,kEAAkE,KAAK,KAAK,KAC5E,UAAU;AACf,QAAM,SAAS,CAAC,UAAqD,UAAU,QAC1E,O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zB,WAAO,KAAK,QAA+B,aAAY,EAAC,GAAG,QAAO,oBAAmB,KAAI,CAAC;AAAA,EAC5F;AAAA,EAEA,oBAAoB,QAAwL;AAC1M,SAAK,oBAAoB;AAAE,UAAM,EAAC,gBAAe,iBAAgB,GAAG,aAAY,IAAE;AAAO,WAAO,KAAK,QAAQ,aAAY,EAAC,gBAAe,iBAAgB,aAAY,CAAC;AAAA,EACxK;AAAA,EAEA,SAAS,QAAwE;AAC/E,SAAK,oBAAoB;AAAE,WAAO,KAAK,QAAQ,aAAY,EAAC,GAAG,QAAO,kBAAiB,KAAI,CAAC;AAAA,EAC9F;AAAA,EAEA,KAAK,QAAgD;AACnD,SAAK,oBAAoB;AACzB,WAAO,KAAK,QAAuB,aAAa,MAA4C;AAAA,EAC9F;AACF;",
|
|
6
|
+
"names": ["exports", "parseXyraAdministrationTargetV1"]
|
|
7
7
|
}
|
|
@@ -58,6 +58,10 @@ function hasPresentationEnvelope(result) {
|
|
|
58
58
|
}
|
|
59
59
|
/** Human view of a tools/call result: presenter Markdown first, then legacy structured output. */
|
|
60
60
|
function formatToolResult(result) {
|
|
61
|
+
const envelope = result.structuredContent;
|
|
62
|
+
if (envelope?.status === 'requirements_unmet') {
|
|
63
|
+
return ['The requested operation was not started.', ...(envelope.requirements?.unmet ?? []).map(item => item.explanation).filter(Boolean), toJson(envelope)].join('\n');
|
|
64
|
+
}
|
|
61
65
|
const text = textContent(result);
|
|
62
66
|
if (text && hasPresentationEnvelope(result)) {
|
|
63
67
|
return text;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"formatters.js","sourceRoot":"","sources":["../../src/output/formatters.ts"],"names":[],"mappings":";;AAIA,wBAEC;AAED,wCAOC;AAED,4CAaC;AA4BD,
|
|
1
|
+
{"version":3,"file":"formatters.js","sourceRoot":"","sources":["../../src/output/formatters.ts"],"names":[],"mappings":";;AAIA,wBAEC;AAED,wCAOC;AAED,4CAaC;AA4BD,4CAgBC;AA1ED,uCAA0C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K,CAAC;IACf,CAAC;IACD,MAAM,aAAa,GAAI,UAAsC,CAAC,aAAa,CAAC;IAC5E,OAAO,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,IAAI,aAAa,CAAC,MAAM,GAAG,CAAC,CAAC;AAClE,CAAC;AAED,kGAAkG;AAClG,SAAgB,gBAAgB,CAAC,MAAsB;IACrD,MAAM,QAAQ,GAAG,MAAM,CAAC,iBAAiI,CAAC;IAC1J,IAAI,QAAQ,EAAE,MAAM,KAAK,oBAAoB,EAAE,CAAC;QAC9C,OAAO,CAAC,0CAA0C,EAAE,GAAG,CAAC,QAAQ,CAAC,YAAY,EAAE,KAAK,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC1K,CAAC;IACD,MAAM,IAAI,GAAG,WAAW,CAAC,MAAM,CAAC,CAAC;IACjC,IAAI,IAAI,IAAI,uBAAuB,CAAC,MAAM,CAAC,EAAE,CAAC;QAC5C,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,MAAM,CAAC,iBAAiB,KAAK,SAAS,EAAE,CAAC;QAC3C,OAAO,MAAM,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC;IAC1C,CAAC;IACD,IAAI,IAAI,EAAE,CAAC;QACT,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC;AACxB,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@experiture/xyra-cli",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.4",
|
|
4
4
|
"description": "Xyra CLI - headless application runner over the Xyra MCP server and Auth delegated OAuth flow.",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"private": false,
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
"registry": "https://registry.npmjs.org/"
|
|
34
34
|
},
|
|
35
35
|
"scripts": {
|
|
36
|
-
"build": "npm run clean && tsc && esbuild src/chat/runtimeChatClient.ts src/config/configStore.ts src/mcp/mcpClient.ts --bundle --platform=node --format=cjs --target=node20 --sourcemap --outdir=dist --outbase=src --external:@modelcontextprotocol/* && node -e \"require('node:fs').chmodSync('dist/index.js', 0o755)\"",
|
|
36
|
+
"build": "npm run clean && tsc && esbuild src/chat/runtimeChatClient.ts src/config/configStore.ts src/mcp/mcpClient.ts --bundle --platform=node --format=cjs --target=node20 --sourcemap --outdir=dist --outbase=src --external:@modelcontextprotocol/* --external:../errors/CliError --external:./mcpError && node -e \"require('node:fs').chmodSync('dist/index.js', 0o755)\"",
|
|
37
37
|
"benchmark:latency": "node scripts/benchmark-latency.mjs",
|
|
38
38
|
"certify:router-acknowledgement": "node scripts/router-acknowledgement-certification.mjs",
|
|
39
39
|
"clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
},
|
|
53
53
|
"devDependencies": {
|
|
54
54
|
"@experiture/xyra-provider-client": "^0.1.13",
|
|
55
|
-
"@experiture/xyra-runtime-client": "0.1.
|
|
55
|
+
"@experiture/xyra-runtime-client": "0.1.93",
|
|
56
56
|
"@jest/globals": "^29.7.0",
|
|
57
57
|
"@types/jest": "^29.5.0",
|
|
58
58
|
"@types/node": "^20.11.0",
|