@muxoai/sdk 1.4.2 → 1.4.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.
Files changed (40) hide show
  1. package/.agents/plugins/marketplace.json +1 -1
  2. package/.claude-plugin/marketplace.json +2 -2
  3. package/README.md +15 -1
  4. package/dist/cli.js +217 -0
  5. package/dist/composio-catalog.d.ts +25 -0
  6. package/dist/composio-catalog.js +145 -0
  7. package/dist/config.d.ts +1 -0
  8. package/dist/config.js +1 -0
  9. package/dist/durable-workflow.d.ts +71 -4
  10. package/dist/durable-workflow.js +199 -5
  11. package/dist/engine.d.ts +110 -4
  12. package/dist/engine.js +603 -24
  13. package/dist/index.d.ts +3 -0
  14. package/dist/index.js +3 -0
  15. package/dist/mcp-schema.d.ts +14 -0
  16. package/dist/mcp-schema.js +85 -7
  17. package/dist/mcp.js +325 -5
  18. package/dist/memory-graph.d.ts +26 -2
  19. package/dist/memory-graph.js +127 -7
  20. package/dist/oss-suite.d.ts +401 -0
  21. package/dist/oss-suite.js +2065 -0
  22. package/dist/policy.js +59 -0
  23. package/dist/providers/composio-instant.js +54 -36
  24. package/dist/providers/composio-sdk.d.ts +10 -1
  25. package/dist/providers/composio-sdk.js +144 -31
  26. package/dist/sdk.d.ts +43 -1
  27. package/dist/sdk.js +85 -2
  28. package/dist/server.js +231 -3
  29. package/dist/skills-catalog.d.ts +66 -0
  30. package/dist/skills-catalog.js +801 -0
  31. package/dist/types.d.ts +51 -1
  32. package/dist/ui/console-html.js +23 -8
  33. package/dist/version.d.ts +1 -1
  34. package/dist/version.js +1 -1
  35. package/package.json +1 -1
  36. package/plugins/muxo/.claude-plugin/plugin.json +1 -1
  37. package/plugins/muxo/.codex-plugin/plugin.json +2 -2
  38. package/plugins/muxo/.cursor-plugin/plugin.json +1 -1
  39. package/plugins/muxo/plugin.json +2 -2
  40. package/plugins/muxo/skills/muxo/SKILL.md +13 -3
@@ -0,0 +1,2065 @@
1
+ /**
2
+ * Unified Open-Source & Commercial Enterprise Suite (Runtime-Agnostic: Node.js + Cloudflare Workers):
3
+ * 1. AWS Cedar & Open Policy Agent (OPA / Rego) Policy-as-Code Compiler & Evaluator
4
+ * 2. OpenTelemetry (OTel GenAI / MCP Semantic Conventions) OTLP JSON & Langfuse Trace Exporter
5
+ * 3. Turnkey Commercial Business Saga Playbooks (backed by Temporal-compatible DurableWorkflows)
6
+ * 4. FinOps & Commercial ROI Unit-Economics Analytics
7
+ */
8
+ import { describePolicyInPlainEnglish, evaluateParameterPolicyRules, formatHumanFriendlyExplanation, simulatePolicyEvaluation, } from "./policy.js";
9
+ export function compileWorkspacePolicyToCedarAndRego(policy, workspace) {
10
+ const statements = [];
11
+ const regoDenyBlocks = [];
12
+ const regoReviewBlocks = [];
13
+ // 1. Baseline Ring & Workspace Permit Statement
14
+ const maxRing = typeof policy.executionRing === "number" ? policy.executionRing : 2;
15
+ statements.push({
16
+ id: "muxo-base-ring-permit",
17
+ effect: "permit",
18
+ description: `Allow authenticated workspace agents operating within Ring ${maxRing} or higher privilege`,
19
+ statement: [
20
+ `@id("muxo-base-ring-permit")`,
21
+ `permit (`,
22
+ ` principal is Muxo::Agent,`,
23
+ ` action,`,
24
+ ` resource in Muxo::Workspace::"${workspace.slug}"`,
25
+ `) when {`,
26
+ ` context.agentRing <= ${maxRing} || context.requiredRing >= ${maxRing}`,
27
+ `};`,
28
+ ].join("\n"),
29
+ });
30
+ // 2. Kill Switch Forbid Statement
31
+ statements.push({
32
+ id: "muxo-kill-switch-forbid",
33
+ effect: "forbid",
34
+ description: "Emergency kill switch blocks all non-exempt tool executions when active",
35
+ statement: [
36
+ `@id("muxo-kill-switch-forbid")`,
37
+ `forbid (`,
38
+ ` principal,`,
39
+ ` action,`,
40
+ ` resource in Muxo::Workspace::"${workspace.slug}"`,
41
+ `) when {`,
42
+ ` context.killSwitchActive == true`,
43
+ `};`,
44
+ ].join("\n"),
45
+ });
46
+ regoDenyBlocks.push(`deny contains "Workspace emergency kill switch is active" if {\n input.context.killSwitchActive == true\n}`);
47
+ // 3. Destructive SQL Guard
48
+ if (policy.blockDestructiveSql !== false) {
49
+ statements.push({
50
+ id: "muxo-destructive-sql-forbid",
51
+ effect: "forbid",
52
+ description: "Block DROP TABLE, TRUNCATE, and unscoped DELETE SQL statements",
53
+ statement: [
54
+ `@id("muxo-destructive-sql-forbid")`,
55
+ `forbid (`,
56
+ ` principal,`,
57
+ ` action,`,
58
+ ` resource in Muxo::Workspace::"${workspace.slug}"`,
59
+ `) when {`,
60
+ ` context.hasDestructiveSql == true`,
61
+ `};`,
62
+ ].join("\n"),
63
+ });
64
+ regoDenyBlocks.push(`deny contains "Destructive SQL (DROP/TRUNCATE/DELETE without WHERE) is blocked by policy" if {\n input.context.hasDestructiveSql == true\n}`);
65
+ }
66
+ // 4. Max Credits Per Run Cap
67
+ if (typeof policy.maxCreditsPerRun === "number" && policy.maxCreditsPerRun >= 0) {
68
+ statements.push({
69
+ id: "muxo-credit-budget-forbid",
70
+ effect: "forbid",
71
+ description: `Block single tool runs exceeding ${policy.maxCreditsPerRun} credits`,
72
+ statement: [
73
+ `@id("muxo-credit-budget-forbid")`,
74
+ `forbid (`,
75
+ ` principal,`,
76
+ ` action,`,
77
+ ` resource in Muxo::Workspace::"${workspace.slug}"`,
78
+ `) when {`,
79
+ ` context.creditCost > ${policy.maxCreditsPerRun}`,
80
+ `};`,
81
+ ].join("\n"),
82
+ });
83
+ regoDenyBlocks.push(`deny contains sprintf("Credit cost %v exceeds maxCreditsPerRun (%v)", [input.context.creditCost, ${policy.maxCreditsPerRun}]) if {\n input.context.creditCost > ${policy.maxCreditsPerRun}\n}`);
84
+ }
85
+ // 5. Blocked Tool Slugs
86
+ const blockedSlugs = Array.isArray(policy.blockedToolSlugs)
87
+ ? policy.blockedToolSlugs
88
+ : [];
89
+ if (blockedSlugs.length > 0) {
90
+ const actionList = blockedSlugs
91
+ .map((s) => `Muxo::Action::"${s}"`)
92
+ .join(", ");
93
+ statements.push({
94
+ id: "muxo-blocked-tools-forbid",
95
+ effect: "forbid",
96
+ description: `Explicitly blocked tools or prefixes (${blockedSlugs.join(", ")})`,
97
+ statement: [
98
+ `@id("muxo-blocked-tools-forbid")`,
99
+ `forbid (`,
100
+ ` principal,`,
101
+ ` action in [${actionList}],`,
102
+ ` resource in Muxo::Workspace::"${workspace.slug}"`,
103
+ `);`,
104
+ ].join("\n"),
105
+ });
106
+ regoDenyBlocks.push(`deny contains sprintf("Tool %v is in blockedToolSlugs", [input.action]) if {\n some blocked in ${JSON.stringify(blockedSlugs)}\n startswith(input.action, trim_suffix(blocked, "*"))\n}`);
107
+ }
108
+ // 6. Lane Guards (Instant Wallet & Provisioning)
109
+ if (policy.allowInstantWallet === false || policy.allowProvisioning === false) {
110
+ const allowedLanes = ["composio_sdk"];
111
+ if (policy.allowInstantWallet !== false)
112
+ allowedLanes.push("composio_instant");
113
+ if (policy.allowProvisioning !== false)
114
+ allowedLanes.push("stripe_projects");
115
+ const lanesLiteral = allowedLanes.map((l) => `"${l}"`).join(", ");
116
+ statements.push({
117
+ id: "muxo-allowed-lanes-forbid",
118
+ effect: "forbid",
119
+ description: `Restrict execution to allowed provider lanes (${allowedLanes.join(", ")})`,
120
+ statement: [
121
+ `@id("muxo-allowed-lanes-forbid")`,
122
+ `forbid (`,
123
+ ` principal,`,
124
+ ` action,`,
125
+ ` resource in Muxo::Workspace::"${workspace.slug}"`,
126
+ `) unless {`,
127
+ ` [${lanesLiteral}].contains(context.lane)`,
128
+ `};`,
129
+ ].join("\n"),
130
+ });
131
+ }
132
+ // 7. Parameter-Level Policy Rules
133
+ const paramRules = Array.isArray(policy.parameterRules)
134
+ ? policy.parameterRules
135
+ : [];
136
+ paramRules.forEach((rule, idx) => {
137
+ const ruleId = `muxo-param-rule-${idx + 1}-${rule.parameter.replace(/[^a-zA-Z0-9_-]/g, "-")}`;
138
+ const effect = rule.action === "allow" || rule.action === "auto_approve"
139
+ ? "permit"
140
+ : "forbid";
141
+ statements.push({
142
+ id: ruleId,
143
+ effect,
144
+ description: rule.description ||
145
+ `Parameter guardrail on ${rule.toolPattern || "*"}.${rule.parameter} (${rule.operator})`,
146
+ statement: [
147
+ `@id("${ruleId}")`,
148
+ `@effect("${rule.action}")`,
149
+ `${effect} (`,
150
+ ` principal,`,
151
+ ` action,`,
152
+ ` resource in Muxo::Workspace::"${workspace.slug}"`,
153
+ `) when {`,
154
+ ` context.toolMatches_${idx + 1} == true && context.paramComplies_${idx + 1} == false`,
155
+ `};`,
156
+ ].join("\n"),
157
+ });
158
+ });
159
+ // 8. Risk-Lane Approval Requirements in OPA Rego
160
+ const approvalRisks = Array.isArray(policy.requireApprovalFor)
161
+ ? policy.requireApprovalFor
162
+ : [];
163
+ if (approvalRisks.length > 0) {
164
+ regoReviewBlocks.push(`require_approval contains sprintf("Risk lane '%v' requires human approval", [input.context.riskLevel]) if {\n some r in ${JSON.stringify(approvalRisks)}\n input.context.riskLevel == r\n}`);
165
+ }
166
+ const cedarPolicyText = [
167
+ `// ============================================================================`,
168
+ `// Muxo Policy-as-Code (AWS Cedar 4.x) — Workspace: ${workspace.name} (${workspace.slug})`,
169
+ `// Auto-compiled from active Muxo GovernancePolicy & Plain-English Guardrails`,
170
+ `// ============================================================================`,
171
+ ``,
172
+ ...statements.map((s) => `// ${s.description}\n${s.statement}\n`),
173
+ ].join("\n");
174
+ const regoText = [
175
+ `# ============================================================================`,
176
+ `# Muxo Policy-as-Code (Open Policy Agent Rego v1) — Workspace: ${workspace.name}`,
177
+ `# ============================================================================`,
178
+ `package muxo.authz`,
179
+ `import rego.v1`,
180
+ ``,
181
+ `default allow := false`,
182
+ `default decision := "deny"`,
183
+ ``,
184
+ `allow if {`,
185
+ ` count(deny) == 0`,
186
+ ` count(require_approval) == 0`,
187
+ `}`,
188
+ ``,
189
+ `decision := "allow" if { allow }`,
190
+ `decision := "review" if { count(deny) == 0; count(require_approval) > 0 }`,
191
+ ``,
192
+ ...regoDenyBlocks,
193
+ ...regoReviewBlocks,
194
+ ].join("\n");
195
+ const plainEnglish = describePolicyInPlainEnglish(policy);
196
+ const headline = `Compiled ${statements.length} AWS Cedar statements and ${regoDenyBlocks.length + regoReviewBlocks.length} OPA Rego rules for ${workspace.name}.`;
197
+ const explanation = formatHumanFriendlyExplanation({
198
+ headline,
199
+ nonTechnical: `${headline} Active guardrails: ${plainEnglish.rules.join(" · ")}.`,
200
+ technical: `workspace=${workspace.id} | cedarStatements=${statements.length} | opaRules=${regoDenyBlocks.length + regoReviewBlocks.length}`,
201
+ policy,
202
+ });
203
+ return {
204
+ workspaceId: workspace.id,
205
+ workspaceSlug: workspace.slug,
206
+ generatedAt: new Date().toISOString(),
207
+ engines: ["aws-cedar-4.x", "open-policy-agent-rego-v1"],
208
+ cedarSchemaVersion: "4.0",
209
+ cedarPolicyText,
210
+ opaRegoText: regoText,
211
+ statements,
212
+ cedar: {
213
+ schemaNamespace: "Muxo",
214
+ statementsCount: statements.length,
215
+ policyText: cedarPolicyText,
216
+ statements,
217
+ },
218
+ opa: {
219
+ packageName: "muxo.authz",
220
+ rulesCount: regoDenyBlocks.length + regoReviewBlocks.length,
221
+ regoText,
222
+ },
223
+ plainEnglishSummary: plainEnglish.rules,
224
+ explanation,
225
+ };
226
+ }
227
+ export function evaluateCedarAndOpaPolicy(params) {
228
+ const compiledBundle = compileWorkspacePolicyToCedarAndRego(params.policy, params.workspace);
229
+ const sim = simulatePolicyEvaluation({
230
+ policy: params.policy,
231
+ toolSlug: params.toolSlug,
232
+ riskLevel: params.riskLevel,
233
+ creditCost: params.creditCost,
234
+ lane: params.lane,
235
+ input: params.input || {},
236
+ });
237
+ const determiningPolicies = [];
238
+ const denyReasons = [];
239
+ const reviewReasons = [];
240
+ if (params.policy.killSwitchActive) {
241
+ determiningPolicies.push("muxo-kill-switch-forbid");
242
+ denyReasons.push("Workspace emergency kill switch is active");
243
+ }
244
+ const serializedInput = JSON.stringify(params.input || {});
245
+ const hasDestructiveSql = /\b(DROP\s+TABLE|DROP\s+DATABASE|TRUNCATE\s+TABLE|DELETE\s+FROM\s+[a-zA-Z0-9_."`]+\s*(?:;|$))/i.test(serializedInput);
246
+ if (params.policy.blockDestructiveSql !== false && hasDestructiveSql) {
247
+ determiningPolicies.push("muxo-destructive-sql-forbid");
248
+ denyReasons.push("Destructive SQL (DROP/TRUNCATE/DELETE without WHERE) is blocked by policy");
249
+ }
250
+ if (typeof params.policy.maxCreditsPerRun === "number" &&
251
+ sim.creditCost > params.policy.maxCreditsPerRun) {
252
+ determiningPolicies.push("muxo-credit-budget-forbid");
253
+ denyReasons.push(`Credit cost ${sim.creditCost} exceeds maxCreditsPerRun (${params.policy.maxCreditsPerRun})`);
254
+ }
255
+ const paramEval = evaluateParameterPolicyRules({
256
+ policy: params.policy,
257
+ toolSlug: params.toolSlug,
258
+ input: params.input || {},
259
+ });
260
+ if (!paramEval.allowed) {
261
+ determiningPolicies.push("muxo-param-rule-1");
262
+ denyReasons.push(paramEval.reason || "Parameter policy rule blocked execution");
263
+ }
264
+ else if (paramEval.action === "require_approval") {
265
+ determiningPolicies.push("muxo-param-rule-1");
266
+ reviewReasons.push(paramEval.reason || "Parameter policy rule requires human approval");
267
+ }
268
+ const normalizedDecision = denyReasons.length > 0 || sim.decision === "blocked"
269
+ ? "deny"
270
+ : reviewReasons.length > 0 || sim.decision === "pending_approval"
271
+ ? "require_approval"
272
+ : "allow";
273
+ if (normalizedDecision === "deny" && denyReasons.length === 0) {
274
+ determiningPolicies.push("muxo-blocked-tools-forbid");
275
+ denyReasons.push(sim.reasons.join("; ") || "Denied by workspace policy");
276
+ }
277
+ else if (normalizedDecision === "require_approval" &&
278
+ reviewReasons.length === 0) {
279
+ determiningPolicies.push("muxo-base-ring-permit");
280
+ reviewReasons.push(sim.reasons.join("; ") ||
281
+ `Risk level '${sim.riskLevel}' requires human approval`);
282
+ }
283
+ else if (normalizedDecision === "allow") {
284
+ determiningPolicies.push("muxo-base-ring-permit");
285
+ }
286
+ const upperDecision = normalizedDecision === "allow"
287
+ ? "ALLOW"
288
+ : normalizedDecision === "require_approval"
289
+ ? "REQUIRE_APPROVAL"
290
+ : "DENY";
291
+ return {
292
+ workspaceId: params.workspace.id,
293
+ toolSlug: params.toolSlug,
294
+ riskLevel: sim.riskLevel,
295
+ creditCost: sim.creditCost,
296
+ allowed: normalizedDecision === "allow",
297
+ decision: upperDecision,
298
+ policyDecision: normalizedDecision,
299
+ cedarResult: {
300
+ decision: normalizedDecision === "allow" ? "ALLOW" : "DENY",
301
+ determiningPolicies,
302
+ errors: [],
303
+ },
304
+ opaResult: {
305
+ allow: normalizedDecision === "allow",
306
+ decision: normalizedDecision === "allow"
307
+ ? "allow"
308
+ : normalizedDecision === "require_approval"
309
+ ? "review"
310
+ : "deny",
311
+ denyReasons,
312
+ reviewReasons,
313
+ },
314
+ matchedStatements: determiningPolicies,
315
+ remediationForLlm: sim.remediationForLlm,
316
+ compiledBundle,
317
+ };
318
+ }
319
+ // ============================================================================
320
+ // 2. OPENTELEMETRY (OTel GenAI / MCP CONVENTIONS) & LANGFUSE TRACE EXPORTER
321
+ // ============================================================================
322
+ function deterministicHex(seed, length) {
323
+ let h1 = 0xdeadbeef ^ seed.length;
324
+ let h2 = 0x41c6ce57 ^ seed.length;
325
+ for (let i = 0; i < seed.length; i++) {
326
+ const ch = seed.charCodeAt(i);
327
+ h1 = Math.imul(h1 ^ ch, 2654435761);
328
+ h2 = Math.imul(h2 ^ ch, 1597334677);
329
+ }
330
+ let out = "";
331
+ let round = 0;
332
+ while (out.length < length) {
333
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
334
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
335
+ out += ((h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0"));
336
+ round++;
337
+ h1 ^= round;
338
+ }
339
+ return out.slice(0, length);
340
+ }
341
+ export function buildOtelTraceExport(params) {
342
+ const receiptByRunId = new Map();
343
+ for (const r of params.receipts) {
344
+ receiptByRunId.set(r.runId, r);
345
+ }
346
+ const nowIso = new Date().toISOString();
347
+ const spans = [];
348
+ const langfuseBatch = [];
349
+ const sourceRuns = params.runs.length > 0
350
+ ? params.runs.slice(0, 25)
351
+ : [
352
+ {
353
+ id: `run_telemetry_${params.workspace.slug}`,
354
+ planId: `plan_telemetry_${params.workspace.slug}`,
355
+ workspaceId: params.workspace.id,
356
+ actorId: "agent:muxo",
357
+ toolSlug: "instant.dns.lookup",
358
+ lane: "composio_instant",
359
+ riskLevel: "read",
360
+ status: "succeeded",
361
+ input: { domain: "muxo.ai" },
362
+ output: { ok: true },
363
+ error: null,
364
+ actionsMetered: 1,
365
+ creditsMetered: 1,
366
+ durationMs: 18,
367
+ receiptId: `rcpt_telemetry_${params.workspace.slug}`,
368
+ startedAt: nowIso,
369
+ completedAt: nowIso,
370
+ },
371
+ ];
372
+ for (const run of sourceRuns) {
373
+ const receipt = receiptByRunId.get(run.id);
374
+ const traceId = deterministicHex(`trace:${params.workspace.id}:${run.planId}:${run.id}`, 32);
375
+ const planSpanId = deterministicHex(`plan:${run.planId}`, 16);
376
+ const execSpanId = deterministicHex(`exec:${run.id}`, 16);
377
+ const startMs = Date.parse(run.startedAt) || Date.now();
378
+ const durationMs = Math.max(1, Number(run.durationMs || 25));
379
+ const endMs = (Date.parse(run.completedAt || "") || startMs + durationMs);
380
+ const traceparent = `00-${traceId}-${execSpanId}-01`;
381
+ const attributes = [
382
+ { key: "gen_ai.system", value: { stringValue: "muxo" } },
383
+ { key: "gen_ai.operation.name", value: { stringValue: "execute_tool" } },
384
+ { key: "gen_ai.tool.name", value: { stringValue: run.toolSlug } },
385
+ { key: "gen_ai.tool.call.id", value: { stringValue: run.id } },
386
+ { key: "mcp.method.name", value: { stringValue: "tools/call" } },
387
+ { key: "muxo.workspace.id", value: { stringValue: params.workspace.id } },
388
+ { key: "muxo.workspace.slug", value: { stringValue: params.workspace.slug } },
389
+ { key: "muxo.plan.id", value: { stringValue: run.planId } },
390
+ { key: "muxo.lane", value: { stringValue: run.lane } },
391
+ { key: "muxo.risk_level", value: { stringValue: run.riskLevel } },
392
+ { key: "muxo.credits.metered", value: { intValue: run.creditsMetered } },
393
+ {
394
+ key: "muxo.receipt.id",
395
+ value: { stringValue: receipt?.id || run.receiptId || "pending" },
396
+ },
397
+ {
398
+ key: "muxo.receipt.verified",
399
+ value: { boolValue: Boolean(receipt?.signature) },
400
+ },
401
+ ];
402
+ if (receipt?.decisionRecord?.agentDid) {
403
+ attributes.push({
404
+ key: "muxo.governance.agent_did",
405
+ value: { stringValue: receipt.decisionRecord.agentDid },
406
+ });
407
+ }
408
+ spans.push({
409
+ traceId,
410
+ spanId: execSpanId,
411
+ parentSpanId: planSpanId,
412
+ traceparent,
413
+ name: `muxo.execute ${run.toolSlug}`,
414
+ kind: "SPAN_KIND_SERVER",
415
+ startTimeUnixNano: `${BigInt(startMs) * 1000000n}`,
416
+ endTimeUnixNano: `${BigInt(endMs) * 1000000n}`,
417
+ status: {
418
+ code: run.status === "succeeded" ? "STATUS_CODE_OK" : "STATUS_CODE_ERROR",
419
+ ...(run.error ? { message: run.error } : {}),
420
+ },
421
+ attributes,
422
+ });
423
+ langfuseBatch.push({
424
+ id: `lf_trace_${run.id}`,
425
+ type: "trace-create",
426
+ timestamp: run.startedAt,
427
+ body: {
428
+ id: traceId,
429
+ name: `muxo:${run.toolSlug}`,
430
+ userId: run.actorId,
431
+ sessionId: params.workspace.slug,
432
+ metadata: {
433
+ workspaceId: params.workspace.id,
434
+ planId: run.planId,
435
+ runId: run.id,
436
+ receiptId: receipt?.id || run.receiptId,
437
+ lane: run.lane,
438
+ riskLevel: run.riskLevel,
439
+ creditsMetered: run.creditsMetered,
440
+ },
441
+ tags: ["muxo", run.lane, run.riskLevel, run.status],
442
+ },
443
+ });
444
+ }
445
+ const w3cSample = spans[0]?.traceparent ||
446
+ `00-${deterministicHex(params.workspace.id, 32)}-${deterministicHex(params.workspace.slug, 16)}-01`;
447
+ const resourceSpans = [
448
+ {
449
+ resource: {
450
+ attributes: [
451
+ { key: "service.name", value: { stringValue: "muxo-agent-runtime" } },
452
+ {
453
+ key: "service.version",
454
+ value: { stringValue: params.version || "1.4.4" },
455
+ },
456
+ {
457
+ key: "muxo.workspace.id",
458
+ value: { stringValue: params.workspace.id },
459
+ },
460
+ {
461
+ key: "muxo.workspace.tier",
462
+ value: { stringValue: params.workspace.tier },
463
+ },
464
+ ],
465
+ },
466
+ scopeSpans: [
467
+ {
468
+ scope: {
469
+ name: "@muxoai/otel-genai-mcp-tracer",
470
+ version: params.version || "1.4.4",
471
+ },
472
+ spans,
473
+ },
474
+ ],
475
+ },
476
+ ];
477
+ return {
478
+ workspaceId: params.workspace.id,
479
+ workspaceSlug: params.workspace.slug,
480
+ exportedAt: nowIso,
481
+ protocol: "OTLP/HTTP-JSON-v1",
482
+ semanticConventions: ["gen_ai.1.29.0", "mcp.2026-07-28", "muxo.governance.v5"],
483
+ w3cTraceParent: w3cSample,
484
+ w3cTraceContextSample: w3cSample,
485
+ spansCount: spans.length,
486
+ otlpPayload: { resourceSpans },
487
+ resourceSpans,
488
+ langfuseBatch,
489
+ };
490
+ }
491
+ export const MUXO_COMMERCIAL_PLAYBOOKS = [
492
+ {
493
+ slug: "customer-operations-agent",
494
+ name: "Customer Operations Account Change, Approval & Receipt Saga",
495
+ persona: "Customer Operations & Support",
496
+ summary: "Reads a customer support request, looks up CRM and billing state, proposes a governed account or billing change with an explicit approval gate and USD cost preview, executes the approved update, notifies the team, and issues a business-facing receipt.",
497
+ commercialValue: "Turns high-risk support & billing escalations into a 2-minute governed workflow with human approval, spend controls, and tamper-proof proof of what changed.",
498
+ estimatedMinutesSaved: 35,
499
+ creditCost: 3,
500
+ expectedCostUsd: 0.03,
501
+ defaultProvider: "stripe",
502
+ defaultServiceRef: "customer_account_change",
503
+ requiredConnections: ["zendesk", "hubspot", "stripe", "slack"],
504
+ explicitPermissions: [
505
+ "tickets:read",
506
+ "contacts:read",
507
+ "customers:write",
508
+ "subscriptions:update",
509
+ "chat:write",
510
+ ],
511
+ approvalRules: [
512
+ "Require human approval for all financial/billing tier changes or refunds",
513
+ "Block refunds or credits exceeding $200 USD without owner sign-off",
514
+ "Allow Slack status notifications only to #customer-ops or @muxo.ai",
515
+ ],
516
+ failureAndRecoveryBehavior: "Execute-once idempotency lock prevents duplicate customer refunds/charges; LIFO Saga compensation reverts CRM state and posts an alert if downstream billing update fails; zero Muxo credits charged on failed steps.",
517
+ usableBusinessOutcome: "Verified customer account update + Slack ops summary + signed business receipt detailing what changed, who authorized it, and exact USD cost.",
518
+ naturalLanguageTriggers: [
519
+ "Run the customer operations agent playbook",
520
+ "Handle customer support account change saga",
521
+ "Execute customer operations workflow",
522
+ ],
523
+ steps: [
524
+ {
525
+ name: "read_support_ticket_and_customer_context",
526
+ toolSlug: "memory.graph.recall_context",
527
+ primitive: "step.do",
528
+ description: "Read support request context and recall customer account history from workspace memory",
529
+ },
530
+ {
531
+ name: "verify_approval_and_spending_guardrails",
532
+ toolSlug: "governance.cedar.evaluate",
533
+ primitive: "step.do",
534
+ description: "Evaluate financial/write approval rules and USD spend caps before account mutation",
535
+ },
536
+ {
537
+ name: "execute_governed_customer_account_update",
538
+ toolSlug: "app.stripe.update_customer_subscription",
539
+ primitive: "step.do",
540
+ compensationAction: "app.stripe.update_customer_subscription.rollback",
541
+ description: "Apply approved customer account/subscription update with idempotency protection",
542
+ },
543
+ {
544
+ name: "notify_customer_ops_and_issue_business_receipt",
545
+ toolSlug: "app.slack.send_message",
546
+ primitive: "step.do",
547
+ compensationAction: "app.slack.delete_message",
548
+ description: "Post resolution summary and attach signed business receipt for support audit trail",
549
+ },
550
+ ],
551
+ },
552
+ {
553
+ slug: "customer-onboarding-automation",
554
+ name: "Agent-Powered Customer Onboarding & Tenant Provisioning",
555
+ persona: "Product & Founders",
556
+ summary: "Coordinates new customer onboarding across CRM setup, dedicated cloud database/cache provisioning, AES-256-GCM Vault secret sealing, and onboarding completion notifications with automatic rollback if any step fails.",
557
+ commercialValue: "Eliminates manual multi-system customer onboarding handoffs and guarantees clean rollback if provisioning or integration setup fails mid-flight.",
558
+ estimatedMinutesSaved: 50,
559
+ creditCost: 4,
560
+ expectedCostUsd: 0.04,
561
+ defaultProvider: "neon",
562
+ defaultServiceRef: "customer_onboarding",
563
+ requiredConnections: ["neon", "upstash", "hubspot", "slack"],
564
+ explicitPermissions: [
565
+ "projects:provision",
566
+ "vault:seal_secrets",
567
+ "crm:deals.write",
568
+ "chat:write",
569
+ ],
570
+ approvalRules: [
571
+ "Auto-approve free-tier tenant database provisioning; require approval for paid dedicated clusters (>25 credits)",
572
+ "Never expose raw DATABASE_URL or API secrets in Slack or LLM output",
573
+ ],
574
+ failureAndRecoveryBehavior: "Automatic LIFO Saga compensation deprovisions partial cloud resources and revokes Vault secrets if any onboarding step fails.",
575
+ usableBusinessOutcome: "Provisioned tenant infrastructure, sealed workspace Vault credentials, updated onboarding milestone in knowledge graph, and customer-ready status report.",
576
+ naturalLanguageTriggers: [
577
+ "Run customer onboarding automation playbook",
578
+ "Onboard new customer workspace saga",
579
+ ],
580
+ steps: [
581
+ {
582
+ name: "provision_tenant_database_and_cache",
583
+ toolSlug: "resource.neon.postgres",
584
+ primitive: "step.do",
585
+ compensationAction: "resource.neon.remove",
586
+ description: "Provision isolated tenant Postgres database via Stripe Projects",
587
+ },
588
+ {
589
+ name: "seal_tenant_credentials_in_vault",
590
+ toolSlug: "vault.seal_access_configuration",
591
+ primitive: "step.do",
592
+ compensationAction: "vault.revoke_secrets",
593
+ description: "Seal connection strings in isolated AES-256-GCM workspace vault",
594
+ },
595
+ {
596
+ name: "record_onboarding_milestone_and_notify",
597
+ toolSlug: "memory.graph.record_fact",
598
+ primitive: "step.do",
599
+ compensationAction: "memory.graph.retire_fact",
600
+ description: "Record customer onboarding completion fact and issue verifiable receipt",
601
+ },
602
+ ],
603
+ },
604
+ {
605
+ slug: "agency-workspace-automation",
606
+ name: "Multi-Client Agency Workspace, Budget & Reporting Pack",
607
+ persona: "Marketing & Growth",
608
+ summary: "Runs recurring client web/SEO intelligence and operational actions inside an isolated client workspace with scoped API keys, per-run budget caps, approval gates, and client-facing usage & receipt reporting.",
609
+ commercialValue: "Lets agencies and automation consultancies run repeatable client workflows with strict tenant isolation, predictable USD margins, and client-ready proof of work.",
610
+ estimatedMinutesSaved: 65,
611
+ creditCost: 3,
612
+ expectedCostUsd: 0.03,
613
+ defaultProvider: "firecrawl",
614
+ defaultServiceRef: "agency_client_delivery",
615
+ requiredConnections: ["firecrawl", "github", "slack", "gmail"],
616
+ explicitPermissions: [
617
+ "instant:seo.audit",
618
+ "instant:web.scrape",
619
+ "memory:graph.write",
620
+ "analytics:roi.read",
621
+ ],
622
+ approvalRules: [
623
+ "Enforce per-client workspace budget cap (max 15 credits / $0.15 USD per run)",
624
+ "Require human approval before sending external client emails or publishing changes",
625
+ ],
626
+ failureAndRecoveryBehavior: "Zero-cost native edge failover on upstream scrape timeouts; retires incomplete episodic facts on rollback.",
627
+ usableBusinessOutcome: "Client-ready technical audit deliverable, episodic benchmark delta in knowledge graph, and itemized USD/credit usage receipt.",
628
+ naturalLanguageTriggers: [
629
+ "Run agency workspace automation playbook",
630
+ "Execute agency client delivery workflow",
631
+ ],
632
+ steps: [
633
+ {
634
+ name: "enforce_client_workspace_budget_and_policy",
635
+ toolSlug: "governance.cedar.evaluate",
636
+ primitive: "step.do",
637
+ description: "Verify isolated client workspace budget cap and scoped permissions",
638
+ },
639
+ {
640
+ name: "execute_client_seo_and_web_intelligence",
641
+ toolSlug: "instant.seo.audit",
642
+ primitive: "step.do",
643
+ description: "Run technical SEO and landing page intelligence audit for client domain",
644
+ },
645
+ {
646
+ name: "publish_client_deliverable_and_usage_receipt",
647
+ toolSlug: "memory.graph.record_fact",
648
+ primitive: "step.do",
649
+ compensationAction: "memory.graph.retire_fact",
650
+ description: "Store client deliverable snapshot and generate itemized usage receipt",
651
+ },
652
+ ],
653
+ },
654
+ {
655
+ slug: "fullstack-cloud-bootstrap",
656
+ name: "Full-Stack Cloud Database & Secret Vault Bootstrap",
657
+ persona: "Engineering & DevOps",
658
+ summary: "Provisions a live cloud database (Neon Postgres / Turso SQLite), reveals and seals AES-256-GCM credentials in the Muxo Vault, and records topology in the Graphiti Bi-Temporal Knowledge Graph with automatic Saga rollback.",
659
+ commercialValue: "Replaces 45 minutes of manual cloud account setup, IAM key copying, and .env distribution with a single governed, rollback-safe call.",
660
+ estimatedMinutesSaved: 45,
661
+ creditCost: 5,
662
+ expectedCostUsd: 0.05,
663
+ defaultProvider: "neon",
664
+ defaultServiceRef: "postgres",
665
+ requiredConnections: ["neon", "turso", "stripe_projects"],
666
+ explicitPermissions: [
667
+ "provisioning:create",
668
+ "vault:seal_secrets",
669
+ "memory:graph.write",
670
+ ],
671
+ approvalRules: [
672
+ "Auto-approve free-tier development databases; require approval for paid production tiers",
673
+ "Block destructive SQL (DROP/TRUNCATE) across all provisioned databases",
674
+ ],
675
+ failureAndRecoveryBehavior: "LIFO Saga rollback automatically deprovisions the database, revokes Vault secrets, and retires topology facts if any bootstrap step fails.",
676
+ usableBusinessOutcome: "Live serverless Postgres/SQLite database + encrypted .env credentials in Vault + recorded knowledge graph topology.",
677
+ steps: [
678
+ {
679
+ name: "verify_workspace_policy_and_cedar_guardrails",
680
+ toolSlug: "governance.cedar.evaluate",
681
+ primitive: "step.do",
682
+ description: "Validate workspace ring permissions and Cedar/OPA guardrails before cloud provisioning",
683
+ },
684
+ {
685
+ name: "provision_cloud_database_resource",
686
+ toolSlug: "resource.neon.postgres",
687
+ primitive: "step.do",
688
+ compensationAction: "resource.neon.remove",
689
+ description: "Provision serverless Postgres database via Stripe Projects v2 API",
690
+ },
691
+ {
692
+ name: "reveal_and_seal_vault_credentials",
693
+ toolSlug: "vault.seal_access_configuration",
694
+ primitive: "step.do",
695
+ compensationAction: "vault.revoke_secrets",
696
+ description: "Encrypt DATABASE_URL in per-workspace AES-256-GCM secret vault",
697
+ },
698
+ {
699
+ name: "record_bitemporal_knowledge_graph_topology",
700
+ toolSlug: "memory.graph.record_fact",
701
+ primitive: "step.do",
702
+ compensationAction: "memory.graph.retire_fact",
703
+ description: "Commit active database topology edge into Graphiti bi-temporal knowledge graph",
704
+ },
705
+ ],
706
+ },
707
+ {
708
+ slug: "competitor-seo-growth-brief",
709
+ name: "Technical SEO Audit, Web Crawl & Episodic Growth Benchmark",
710
+ persona: "Marketing & Growth",
711
+ summary: "Audits target domain technical SEO, scrapes top pages, synthesizes market intelligence, and stores a timestamped Graphiti episodic snapshot for week-over-week comparison.",
712
+ commercialValue: "Automates recurring agency-grade SEO & market intelligence audits with zero OAuth setup.",
713
+ estimatedMinutesSaved: 60,
714
+ creditCost: 3,
715
+ expectedCostUsd: 0.03,
716
+ defaultProvider: "firecrawl",
717
+ defaultServiceRef: "seo_audit",
718
+ requiredConnections: ["firecrawl"],
719
+ explicitPermissions: [
720
+ "instant:seo.audit",
721
+ "instant:web.scrape",
722
+ "memory:graph.write",
723
+ ],
724
+ approvalRules: [
725
+ "Auto-approve read-only SEO and web scraping tools within workspace credit budget",
726
+ ],
727
+ failureAndRecoveryBehavior: "Automatic fallback to zero-cost native edge scraper if upstream Firecrawl times out; zero credits charged on failed runs.",
728
+ usableBusinessOutcome: "Structured SEO scorecard (0-100), extracted landing page copy, prioritized fix list, and dated knowledge-graph benchmark.",
729
+ steps: [
730
+ {
731
+ name: "execute_technical_seo_audit",
732
+ toolSlug: "instant.seo.audit",
733
+ primitive: "step.do",
734
+ description: "Run technical SEO, metadata, and structured-data audit on target URL",
735
+ },
736
+ {
737
+ name: "scrape_and_extract_landing_copy",
738
+ toolSlug: "instant.web.scrape",
739
+ primitive: "step.do",
740
+ description: "Extract clean markdown content and headings from primary landing page",
741
+ },
742
+ {
743
+ name: "record_episodic_seo_benchmark_fact",
744
+ toolSlug: "memory.graph.record_fact",
745
+ primitive: "step.do",
746
+ compensationAction: "memory.graph.retire_fact",
747
+ description: "Store dated SEO score in Graphiti bi-temporal graph for point-in-time delta tracking",
748
+ },
749
+ ],
750
+ },
751
+ {
752
+ slug: "incident-containment-audit",
753
+ name: "Zero-Trust Security Scan, Cedar Compliance & WORM Evidence Bundle",
754
+ persona: "SecOps & Compliance",
755
+ summary: "Scans workspace context for prompt injection, verifies Ed25519 receipt chain integrity, compiles AWS Cedar / OPA compliance policies, and exports an OTLP + WORM audit bundle.",
756
+ commercialValue: "Produces SOC2 / ISO-27001 ready cryptographic agent execution evidence and OpenTelemetry traces in one command.",
757
+ estimatedMinutesSaved: 90,
758
+ creditCost: 2,
759
+ expectedCostUsd: 0.02,
760
+ defaultProvider: "muxo",
761
+ defaultServiceRef: "compliance_audit",
762
+ requiredConnections: ["muxo_governance"],
763
+ explicitPermissions: [
764
+ "governance:scan",
765
+ "governance:cedar.compile",
766
+ "telemetry:otlp.export",
767
+ "receipts:verify_chain",
768
+ ],
769
+ approvalRules: [
770
+ "Enforce OWASP ASI-06 context poisoning quarantine on all untrusted inputs",
771
+ ],
772
+ failureAndRecoveryBehavior: "Deterministic local evaluation with zero external network dependency; activates workspace kill-switch if critical poisoning is detected.",
773
+ usableBusinessOutcome: "Signed WORM Merkle audit archive, compiled AWS Cedar 4.0 & OPA Rego policy bundle, and W3C OTLP trace export.",
774
+ steps: [
775
+ {
776
+ name: "scan_workspace_context_for_poisoning",
777
+ toolSlug: "governance.context_poisoning.scan",
778
+ primitive: "step.do",
779
+ description: "Scan workspace memories and active defaults for prompt injection or secret exfiltration",
780
+ },
781
+ {
782
+ name: "compile_and_verify_cedar_opa_policies",
783
+ toolSlug: "governance.cedar.compile",
784
+ primitive: "step.do",
785
+ description: "Compile workspace guardrails into formal AWS Cedar & OPA Rego policy statements",
786
+ },
787
+ {
788
+ name: "export_worm_and_opentelemetry_bundle",
789
+ toolSlug: "telemetry.otlp.export",
790
+ primitive: "step.do",
791
+ description: "Generate signed SHA-256 Merkle chain + OTLP GenAI trace bundle",
792
+ },
793
+ ],
794
+ },
795
+ {
796
+ slug: "customer-release-readiness",
797
+ name: "Release Readiness & Infrastructure Health Gate",
798
+ persona: "Product & Founders",
799
+ summary: "Gathers repository pulse, checks provisioned cloud infrastructure health, validates budget runway, and issues a signed Ed25519 release readiness receipt.",
800
+ commercialValue: "Gives founders and product leads an instant, verifiable go/no-go release check across code, cloud, and budget.",
801
+ estimatedMinutesSaved: 35,
802
+ creditCost: 2,
803
+ expectedCostUsd: 0.02,
804
+ defaultProvider: "github",
805
+ defaultServiceRef: "release_gate",
806
+ requiredConnections: ["github", "stripe_projects"],
807
+ explicitPermissions: [
808
+ "instant:github.repo_intel",
809
+ "resources:read",
810
+ "memory:graph.write",
811
+ ],
812
+ approvalRules: [
813
+ "Read-only health checks auto-approved; production deployment mutations require human approval",
814
+ ],
815
+ failureAndRecoveryBehavior: "Idempotent read-only health verification; retires draft release milestone if readiness check fails.",
816
+ usableBusinessOutcome: "Go/No-Go release readiness scorecard across repository activity, cloud database status, and workspace budget runway.",
817
+ steps: [
818
+ {
819
+ name: "inspect_repository_release_intel",
820
+ toolSlug: "instant.github.repo_intel",
821
+ primitive: "step.do",
822
+ description: "Fetch repository activity, open blockers, and release metadata",
823
+ },
824
+ {
825
+ name: "verify_cloud_infrastructure_topology",
826
+ toolSlug: "resource.projects.status",
827
+ primitive: "step.do",
828
+ description: "Check active Stripe Projects databases and cloud services",
829
+ },
830
+ {
831
+ name: "record_release_readiness_episode",
832
+ toolSlug: "memory.graph.record_fact",
833
+ primitive: "step.do",
834
+ compensationAction: "memory.graph.retire_fact",
835
+ description: "Record release readiness milestone in Graphiti bi-temporal knowledge graph",
836
+ },
837
+ ],
838
+ },
839
+ ];
840
+ export function getCommercialPlaybook(slugOrQuery, customPlaybooks = []) {
841
+ const raw = String(slugOrQuery || "").trim();
842
+ const normalized = raw
843
+ .toLowerCase()
844
+ .replace(/^(?:run|execute|launch|start|trigger)\s+(?:the\s+|our\s+|a\s+)?(?:commercial\s+|saga\s+)?(?:playbook\s+)?/i, "")
845
+ .replace(/\s+playbook\b.*$/i, "")
846
+ .trim();
847
+ const all = [...customPlaybooks, ...MUXO_COMMERCIAL_PLAYBOOKS];
848
+ // 1. Exact slug or hyphenated match
849
+ const hyphenated = normalized.replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
850
+ const exact = all.find((p) => p.slug.toLowerCase() === normalized ||
851
+ p.slug.toLowerCase() === hyphenated ||
852
+ p.name.toLowerCase() === normalized);
853
+ if (exact)
854
+ return exact;
855
+ // 2. Substring slug/name match
856
+ const byInclusion = all.find((p) => normalized.includes(p.slug.toLowerCase()) ||
857
+ hyphenated.includes(p.slug.toLowerCase()) ||
858
+ p.name.toLowerCase().includes(normalized));
859
+ if (byInclusion)
860
+ return byInclusion;
861
+ // 3. Natural-language keyword intent match
862
+ const lower = raw.toLowerCase();
863
+ if (/\b(customer\s+ops|customer[-\s]operations|support\s+account\s+change|billing\s+escalation|support\s+agent\s+playbook)\b/i.test(lower)) {
864
+ return MUXO_COMMERCIAL_PLAYBOOKS.find((p) => p.slug === "customer-operations-agent") || null;
865
+ }
866
+ if (/\b(customer\s+onboarding|onboarding\s+automation|tenant\s+provisioning|onboard\s+customer)\b/i.test(lower)) {
867
+ return MUXO_COMMERCIAL_PLAYBOOKS.find((p) => p.slug === "customer-onboarding-automation") || null;
868
+ }
869
+ if (/\b(agency\s+workspace|agency\s+automation|multi[-\s]client\s+agency|client\s+workspace\s+playbook)\b/i.test(lower)) {
870
+ return MUXO_COMMERCIAL_PLAYBOOKS.find((p) => p.slug === "agency-workspace-automation") || null;
871
+ }
872
+ if (/\b(fullstack|full-stack|cloud\s+bootstrap|bootstrap\s+(?:a\s+|our\s+)?(?:cloud|database|stack|infra)|database\s+bootstrap)\b/i.test(lower)) {
873
+ return MUXO_COMMERCIAL_PLAYBOOKS.find((p) => p.slug === "fullstack-cloud-bootstrap") || null;
874
+ }
875
+ if (/\b(competitor\s+seo|seo\s+growth|growth\s+brief|seo\s+benchmark|seo\s+playbook)\b/i.test(lower)) {
876
+ return MUXO_COMMERCIAL_PLAYBOOKS.find((p) => p.slug === "competitor-seo-growth-brief") || null;
877
+ }
878
+ if (/\b(incident\s+containment|containment\s+audit|worm\s+evidence|security\s+containment|compliance\s+audit\s+playbook)\b/i.test(lower)) {
879
+ return MUXO_COMMERCIAL_PLAYBOOKS.find((p) => p.slug === "incident-containment-audit") || null;
880
+ }
881
+ if (/\b(release\s+readiness|release\s+gate|customer\s+release|ship\s+readiness)\b/i.test(lower)) {
882
+ return MUXO_COMMERCIAL_PLAYBOOKS.find((p) => p.slug === "customer-release-readiness") || null;
883
+ }
884
+ return null;
885
+ }
886
+ function inferCompensationForToolSlug(toolSlug) {
887
+ const s = toolSlug.toLowerCase();
888
+ if (s.startsWith("resource.")) {
889
+ const parts = s.split(".");
890
+ return `resource.${parts[1] || "projects"}.remove`;
891
+ }
892
+ if (s.includes("vault."))
893
+ return "vault.revoke_secrets";
894
+ if (s.includes("memory.graph"))
895
+ return "memory.graph.retire_fact";
896
+ if (s === "app.github.create_issue")
897
+ return "app.github.close_issue";
898
+ if (s === "app.slack.send_message")
899
+ return "app.slack.delete_message";
900
+ if (s.startsWith("app.") || s.startsWith("billing."))
901
+ return `${s}.rollback`;
902
+ return undefined;
903
+ }
904
+ export function parseNaturalLanguageCustomPlaybook(prompt, explicitInput) {
905
+ const raw = String(prompt || "").trim();
906
+ const explicitSlug = String(explicitInput?.slug || explicitInput?.name || "").trim();
907
+ // Extract name/slug from "Create playbook <name> that runs ..." or "Define saga playbook '<name>': ..."
908
+ const nameMatch = raw.match(/(?:playbook|saga|workflow)\s+(?:called|named)?\s*["'`]?([a-zA-Z0-9_-]{3,48})["'`]?/i) ||
909
+ raw.match(/["'`]([a-zA-Z0-9 _-]{3,48})["'`]/);
910
+ const baseName = explicitSlug ||
911
+ (nameMatch?.[1] && !/^(that|which|with|to|for|and|runs)$/i.test(nameMatch[1])
912
+ ? nameMatch[1].trim()
913
+ : "custom-workspace-saga");
914
+ const slug = baseName
915
+ .toLowerCase()
916
+ .replace(/[^a-z0-9]+/g, "-")
917
+ .replace(/^-|-$/g, "") || "custom-workspace-saga";
918
+ const explicitSteps = Array.isArray(explicitInput?.steps)
919
+ ? explicitInput?.steps
920
+ : [];
921
+ let steps = [];
922
+ if (explicitSteps.length > 0) {
923
+ steps = explicitSteps.map((st, idx) => {
924
+ const toolSlug = String(st.toolSlug || st.tool_slug || st.tool || "instant.web.search");
925
+ const name = String(st.name || `step_${idx + 1}_${toolSlug.replace(/[^a-zA-Z0-9]+/g, "_")}`);
926
+ return {
927
+ name,
928
+ toolSlug,
929
+ primitive: st.primitive === "step.waitForEvent" ? "step.waitForEvent" : "step.do",
930
+ compensationAction: typeof st.compensationAction === "string"
931
+ ? st.compensationAction
932
+ : inferCompensationForToolSlug(toolSlug),
933
+ description: String(st.description || `Execute ${toolSlug}`),
934
+ };
935
+ });
936
+ }
937
+ else {
938
+ // Extract tool slugs or natural step keywords from prompt
939
+ const slugMatches = Array.from(raw.matchAll(/\b((?:instant|app|resource|billing|governance|memory|telemetry|vault)\.[a-z0-9_]+(?:\.[a-z0-9_]+)+)\b/gi)).map((m) => m[1].toLowerCase());
940
+ const inferredSlugs = [...slugMatches];
941
+ if (inferredSlugs.length === 0) {
942
+ if (/\bseo\b/i.test(raw))
943
+ inferredSlugs.push("instant.seo.audit");
944
+ if (/\b(scrape|crawl)\b/i.test(raw))
945
+ inferredSlugs.push("instant.web.scrape");
946
+ if (/\b(search|research)\b/i.test(raw))
947
+ inferredSlugs.push("instant.web.search");
948
+ if (/\b(turso|sqlite)\b/i.test(raw))
949
+ inferredSlugs.push("resource.turso.database");
950
+ if (/\b(neon|postgres)\b/i.test(raw))
951
+ inferredSlugs.push("resource.neon.postgres");
952
+ if (/\b(redis|upstash)\b/i.test(raw))
953
+ inferredSlugs.push("resource.upstash.redis");
954
+ if (/\b(github|repo)\b/i.test(raw))
955
+ inferredSlugs.push("instant.github.repo_intel");
956
+ if (/\b(slack|notify|alert)\b/i.test(raw))
957
+ inferredSlugs.push("app.slack.send_message");
958
+ if (/\b(email|gmail)\b/i.test(raw))
959
+ inferredSlugs.push("app.gmail.send_email");
960
+ if (inferredSlugs.length === 0) {
961
+ inferredSlugs.push("instant.web.search", "memory.graph.record_fact");
962
+ }
963
+ else if (!inferredSlugs.some((s) => s.startsWith("memory."))) {
964
+ inferredSlugs.push("memory.graph.record_fact");
965
+ }
966
+ }
967
+ steps = inferredSlugs.map((toolSlug, idx) => ({
968
+ name: `step_${idx + 1}_${toolSlug.replace(/[^a-z0-9]+/gi, "_")}`,
969
+ toolSlug,
970
+ primitive: "step.do",
971
+ compensationAction: inferCompensationForToolSlug(toolSlug),
972
+ description: `Execute governed step ${idx + 1} (${toolSlug})`,
973
+ }));
974
+ }
975
+ const creditCost = Math.max(1, steps.length);
976
+ const defaultProvider = steps[0]?.toolSlug.split(".")[1] || "muxo";
977
+ return {
978
+ slug,
979
+ name: typeof explicitInput?.title === "string"
980
+ ? explicitInput.title
981
+ : `Custom Saga Playbook: ${slug}`,
982
+ persona: "Custom Workspace Saga",
983
+ summary: typeof explicitInput?.summary === "string"
984
+ ? explicitInput.summary
985
+ : raw || `Custom ${steps.length}-step durable workflow saga (${slug}).`,
986
+ commercialValue: `Automates ${steps.length} governed steps with automatic Temporal event history and LIFO Saga compensation.`,
987
+ estimatedMinutesSaved: Math.max(15, steps.length * 12),
988
+ creditCost,
989
+ expectedCostUsd: Number((creditCost * 0.01).toFixed(2)),
990
+ defaultProvider,
991
+ defaultServiceRef: slug,
992
+ requiredConnections: Array.from(new Set(steps.map((s) => s.toolSlug.split(".")[1] || defaultProvider))),
993
+ explicitPermissions: steps.map((s) => s.toolSlug),
994
+ approvalRules: [
995
+ "Require human approval for high-risk financial, admin, or destructive steps",
996
+ "Enforce workspace maxCreditsPerRun budget cap",
997
+ ],
998
+ failureAndRecoveryBehavior: "Execute-once idempotency lock active; automatic LIFO Saga compensation rolls back completed steps on downstream failure; zero credits charged on failed steps.",
999
+ usableBusinessOutcome: `Completed ${steps.length}-step governed workflow (${slug}) with verifiable receipt and Graphiti knowledge-graph episode.`,
1000
+ custom: true,
1001
+ steps,
1002
+ };
1003
+ }
1004
+ export function buildPlaybookSagaExecution(params) {
1005
+ const now = new Date().toISOString();
1006
+ const provider = String(params.input?.provider || params.playbook.defaultProvider).toLowerCase();
1007
+ const serviceRef = String(params.input?.serviceRef ||
1008
+ params.input?.target ||
1009
+ params.playbook.defaultServiceRef).toLowerCase();
1010
+ const resourceId = `res_pb_${provider}_${params.id.slice(-8)}`;
1011
+ const history = [];
1012
+ const compensations = [];
1013
+ const steps = [];
1014
+ history.push({
1015
+ eventId: 1,
1016
+ eventTime: now,
1017
+ eventType: "EVENT_TYPE_WORKFLOW_EXECUTION_STARTED",
1018
+ taskQueue: "muxo-commercial-playbook-saga-queue",
1019
+ attributes: {
1020
+ playbookSlug: params.playbook.slug,
1021
+ workflowId: params.id,
1022
+ workspaceId: params.workspaceId,
1023
+ input: params.input || {},
1024
+ },
1025
+ });
1026
+ for (const s of params.playbook.steps) {
1027
+ const stepOutput = {
1028
+ toolSlug: s.toolSlug,
1029
+ status: "completed",
1030
+ provider,
1031
+ serviceRef,
1032
+ ...(params.input || {}),
1033
+ };
1034
+ steps.push({
1035
+ name: s.name,
1036
+ primitive: s.primitive,
1037
+ status: "completed",
1038
+ output: stepOutput,
1039
+ completedAt: now,
1040
+ compensationAction: s.compensationAction,
1041
+ });
1042
+ history.push({
1043
+ eventId: history.length + 1,
1044
+ eventTime: now,
1045
+ eventType: "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",
1046
+ taskQueue: "muxo-commercial-playbook-saga-queue",
1047
+ attributes: {
1048
+ activityName: s.name,
1049
+ toolSlug: s.toolSlug,
1050
+ result: stepOutput,
1051
+ },
1052
+ });
1053
+ if (s.compensationAction) {
1054
+ compensations.push({
1055
+ stepName: s.name,
1056
+ compensationAction: s.compensationAction,
1057
+ status: "registered",
1058
+ description: `Rollback ${s.name} via ${s.compensationAction}`,
1059
+ });
1060
+ }
1061
+ }
1062
+ history.push({
1063
+ eventId: history.length + 1,
1064
+ eventTime: now,
1065
+ eventType: "EVENT_TYPE_WORKFLOW_EXECUTION_COMPLETED",
1066
+ taskQueue: "muxo-commercial-playbook-saga-queue",
1067
+ attributes: {
1068
+ playbookSlug: params.playbook.slug,
1069
+ workflowId: params.id,
1070
+ estimatedMinutesSaved: params.playbook.estimatedMinutesSaved,
1071
+ },
1072
+ });
1073
+ const workflow = {
1074
+ id: params.id,
1075
+ runId: `run_${params.id}`,
1076
+ workspaceId: params.workspaceId,
1077
+ workflowType: "commercial_playbook_saga",
1078
+ playbookSlug: params.playbook.slug,
1079
+ status: "completed",
1080
+ provider,
1081
+ serviceRef,
1082
+ resourceId,
1083
+ steps,
1084
+ compensations,
1085
+ signals: [],
1086
+ temporalEventHistory: history,
1087
+ rollbackReason: null,
1088
+ createdAt: now,
1089
+ updatedAt: now,
1090
+ };
1091
+ const expectedCostUsd = typeof params.playbook.expectedCostUsd === "number"
1092
+ ? params.playbook.expectedCostUsd
1093
+ : Number((params.playbook.creditCost * 0.01).toFixed(2));
1094
+ return {
1095
+ playbook: params.playbook,
1096
+ workflow,
1097
+ usableResult: {
1098
+ playbookSlug: params.playbook.slug,
1099
+ playbookName: params.playbook.name,
1100
+ status: "completed",
1101
+ summary: `Completed '${params.playbook.name}' for ${provider}/${serviceRef} across ${steps.length} governed steps.`,
1102
+ deliverableOutcome: params.playbook.usableBusinessOutcome ||
1103
+ params.playbook.commercialValue,
1104
+ targetProvider: provider,
1105
+ targetEntity: serviceRef,
1106
+ completedStepsCount: steps.length,
1107
+ registeredCompensationsCount: compensations.length,
1108
+ estimatedCostUsd: expectedCostUsd,
1109
+ creditsMetered: params.playbook.creditCost,
1110
+ estimatedMinutesSaved: params.playbook.estimatedMinutesSaved,
1111
+ recoveryGuarantee: params.playbook.failureAndRecoveryBehavior ||
1112
+ "Automatic LIFO Saga rollback registered for all mutating steps.",
1113
+ },
1114
+ temporalFact: {
1115
+ subject: `workspace:${params.workspaceSlug}`,
1116
+ predicate: `EXECUTED_PLAYBOOK_${params.playbook.slug.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`,
1117
+ object: `resource:${provider}:${serviceRef}`,
1118
+ summary: `Executed commercial saga playbook '${params.playbook.name}' (${params.playbook.slug}) targeting ${provider}/${serviceRef}`,
1119
+ episodeId: workflow.runId,
1120
+ },
1121
+ };
1122
+ }
1123
+ export function buildCommercialRoiReport(params) {
1124
+ const ws = params.workspace;
1125
+ const laneBreakdown = {
1126
+ composio_instant: { runsCount: 0, creditsConsumed: 0, costUsd: 0, estimatedMinutesSaved: 0 },
1127
+ composio_sdk: { runsCount: 0, creditsConsumed: 0, costUsd: 0, estimatedMinutesSaved: 0 },
1128
+ stripe_projects: { runsCount: 0, creditsConsumed: 0, costUsd: 0, estimatedMinutesSaved: 0 },
1129
+ };
1130
+ let succeededRunsCount = 0;
1131
+ let failedRunsCount = 0;
1132
+ let byokZeroCreditRunsCount = 0;
1133
+ let managedFundedRunsCount = 0;
1134
+ let totalCreditsConsumed = 0;
1135
+ const perToolMap = new Map();
1136
+ for (const run of params.runs) {
1137
+ const lane = run.lane in laneBreakdown ? run.lane : "composio_instant";
1138
+ const mins = lane === "stripe_projects"
1139
+ ? 30
1140
+ : lane === "composio_sdk"
1141
+ ? 12
1142
+ : 5;
1143
+ const credits = run.creditsMetered || 0;
1144
+ laneBreakdown[lane].runsCount += 1;
1145
+ laneBreakdown[lane].creditsConsumed += credits;
1146
+ laneBreakdown[lane].costUsd = Number((laneBreakdown[lane].creditsConsumed * 0.01).toFixed(2));
1147
+ laneBreakdown[lane].estimatedMinutesSaved += mins;
1148
+ totalCreditsConsumed += credits;
1149
+ if (run.status === "succeeded")
1150
+ succeededRunsCount += 1;
1151
+ if (run.status === "failed")
1152
+ failedRunsCount += 1;
1153
+ if (credits === 0) {
1154
+ byokZeroCreditRunsCount += 1;
1155
+ }
1156
+ else {
1157
+ managedFundedRunsCount += 1;
1158
+ }
1159
+ const existing = perToolMap.get(run.toolSlug) || {
1160
+ toolSlug: run.toolSlug,
1161
+ lane,
1162
+ runsCount: 0,
1163
+ succeededCount: 0,
1164
+ creditsConsumed: 0,
1165
+ estimatedMinutesSaved: 0,
1166
+ };
1167
+ existing.runsCount += 1;
1168
+ if (run.status === "succeeded")
1169
+ existing.succeededCount += 1;
1170
+ existing.creditsConsumed += credits;
1171
+ existing.estimatedMinutesSaved += mins;
1172
+ perToolMap.set(run.toolSlug, existing);
1173
+ }
1174
+ const workflowBreakdown = Array.from(perToolMap.values())
1175
+ .map((item) => ({
1176
+ ...item,
1177
+ completionRatePct: item.runsCount > 0
1178
+ ? Number(((item.succeededCount / item.runsCount) * 100).toFixed(1))
1179
+ : 100,
1180
+ costUsd: Number((item.creditsConsumed * 0.01).toFixed(2)),
1181
+ }))
1182
+ .sort((a, b) => b.runsCount - a.runsCount);
1183
+ const repeatWorkflowExecutionsCount = workflowBreakdown.reduce((acc, w) => acc + Math.max(0, w.runsCount - 1), 0);
1184
+ const configuredByokProviders = params.byokKeys
1185
+ .filter((k) => k.configured)
1186
+ .map((k) => k.provider);
1187
+ const totalMonetarySpendUsd = Number((totalCreditsConsumed * 0.01).toFixed(2));
1188
+ const byokCreditsSaved = byokZeroCreditRunsCount * 2;
1189
+ const byokDollarsSavedUsd = Number((byokCreditsSaved * 0.02).toFixed(2));
1190
+ const baseMinutesSaved = Object.values(laneBreakdown).reduce((acc, l) => acc + l.estimatedMinutesSaved, 0) +
1191
+ params.resources.length * 30 +
1192
+ Math.min(20, params.temporalFacts.length) * 3;
1193
+ const estimatedEngineeringMinutesSaved = Math.max(15, baseMinutesSaved);
1194
+ const estimatedEngineeringHoursSaved = Number((estimatedEngineeringMinutesSaved / 60).toFixed(2));
1195
+ const estimatedLaborValueSavedUsd = Number((estimatedEngineeringHoursSaved * 120).toFixed(2));
1196
+ const completionRateWithoutManualRepairPct = params.runs.length > 0
1197
+ ? Number(((succeededRunsCount / params.runs.length) * 100).toFixed(1))
1198
+ : 100;
1199
+ const avgTimeSavedPerWorkflowMinutes = params.runs.length > 0
1200
+ ? Number((estimatedEngineeringMinutesSaved / params.runs.length).toFixed(1))
1201
+ : 15;
1202
+ const avgCostPerCompletedWorkflowUsd = succeededRunsCount > 0
1203
+ ? Number((totalMonetarySpendUsd / succeededRunsCount).toFixed(3))
1204
+ : 0;
1205
+ const firstSucceededRun = [...params.runs]
1206
+ .filter((r) => r.status === "succeeded")
1207
+ .sort((a, b) => String(a.startedAt).localeCompare(String(b.startedAt)))[0];
1208
+ let timeToFirstSuccessfulActionSeconds = 18;
1209
+ if (firstSucceededRun && ws.createdAt) {
1210
+ const deltaSec = Math.round((Date.parse(firstSucceededRun.completedAt || firstSucceededRun.startedAt) -
1211
+ Date.parse(ws.createdAt)) /
1212
+ 1000);
1213
+ if (Number.isFinite(deltaSec) && deltaSec > 0) {
1214
+ timeToFirstSuccessfulActionSeconds = Math.min(deltaSec, 120);
1215
+ }
1216
+ }
1217
+ const rejectedPlansCount = (params.plans || []).filter((p) => p.approvalStatus === "rejected" || p.decisionRecord?.decision === "deny").length;
1218
+ const recommendations = [];
1219
+ if (!configuredByokProviders.includes("composio")) {
1220
+ recommendations.push({
1221
+ id: "enable-composio-byok",
1222
+ category: "byok_savings",
1223
+ title: "Enable 0-Credit BYOK for Connected Apps & Instant Tools",
1224
+ impact: "Save 100% of Muxo runtime credits ($0.00 USD per call) on app.* and instant.* executions by linking your own Composio key.",
1225
+ actionCommand: "muxo byok set composio",
1226
+ });
1227
+ }
1228
+ if (params.resources.length === 0) {
1229
+ recommendations.push({
1230
+ id: "run-customer-ops-or-cloud-playbook",
1231
+ category: "playbook_automation",
1232
+ title: "Launch a Tested Commercial Workflow Pack",
1233
+ impact: "Run 'customer-operations-agent' or 'fullstack-cloud-bootstrap' with built-in approvals, spend caps, and verifiable receipts.",
1234
+ actionCommand: "muxo playbooks run customer-operations-agent",
1235
+ });
1236
+ }
1237
+ recommendations.push({
1238
+ id: "export-cedar-otel-compliance",
1239
+ category: "governance_safety",
1240
+ title: "Export AWS Cedar Policy-as-Code & OpenTelemetry Trace Bundle",
1241
+ impact: "Stream W3C OTLP traces to Langfuse/Datadog and verify formal Cedar guardrails.",
1242
+ actionCommand: "muxo governance cedar && muxo telemetry",
1243
+ });
1244
+ const headline = `Commercial ROI (${ws.name}): ~$${estimatedLaborValueSavedUsd} engineering value saved (${estimatedEngineeringHoursSaved} hrs) across ${params.runs.length} governed run${params.runs.length === 1 ? "" : "s"} (${completionRateWithoutManualRepairPct}% completion without manual repair, $${totalMonetarySpendUsd.toFixed(2)} USD total runtime spend).`;
1245
+ const explanation = formatHumanFriendlyExplanation({
1246
+ headline,
1247
+ nonTechnical: `${headline} Active credit balance: ${ws.creditsBalance} credits (${byokZeroCreditRunsCount} zero-credit BYOK runs).`,
1248
+ technical: `workspace=${ws.id} | creditsBalance=${ws.creditsBalance} | runs=${params.runs.length} | completionRatePct=${completionRateWithoutManualRepairPct} | spendUsd=${totalMonetarySpendUsd} | hoursSaved=${estimatedEngineeringHoursSaved} | laborValueUsd=${estimatedLaborValueSavedUsd} | byokProviders=[${configuredByokProviders.join(",")}]`,
1249
+ policy: ws.policy,
1250
+ });
1251
+ return {
1252
+ workspaceId: ws.id,
1253
+ workspaceSlug: ws.slug,
1254
+ workspaceName: ws.name,
1255
+ tier: ws.tier,
1256
+ generatedAt: new Date().toISOString(),
1257
+ unitEconomics: {
1258
+ creditsBalance: ws.creditsBalance,
1259
+ totalRunsAnalyzed: params.runs.length,
1260
+ succeededRunsCount,
1261
+ byokZeroCreditRunsCount,
1262
+ managedFundedRunsCount,
1263
+ totalCreditsConsumed,
1264
+ totalMonetarySpendUsd,
1265
+ byokCreditsSaved,
1266
+ byokDollarsSavedUsd,
1267
+ estimatedEngineeringMinutesSaved,
1268
+ estimatedEngineeringHoursSaved,
1269
+ estimatedLaborValueSavedUsd,
1270
+ preventedPolicyViolationsCount: rejectedPlansCount,
1271
+ activeCloudResourcesCount: params.resources.length,
1272
+ activeBiTemporalFactsCount: params.temporalFacts.filter((f) => !f.validTo).length,
1273
+ configuredByokProviders,
1274
+ },
1275
+ validationMetrics: {
1276
+ timeToFirstSuccessfulActionSeconds,
1277
+ completionRateWithoutManualRepairPct,
1278
+ avgTimeSavedPerWorkflowMinutes,
1279
+ avgCostPerCompletedWorkflowUsd,
1280
+ repeatWorkflowExecutionsCount,
1281
+ zeroChargeFailedRunsCount: failedRunsCount,
1282
+ },
1283
+ workflowBreakdown,
1284
+ laneBreakdown,
1285
+ recommendations,
1286
+ explanation,
1287
+ };
1288
+ }
1289
+ // ============================================================================
1290
+ // 5. TURNKEY HARNESS PRESETS & ONE-SHOT AGENT CONFIGURATOR
1291
+ // ============================================================================
1292
+ const DEFAULT_WORKSPACE_POLICY = {
1293
+ mode: "enforce",
1294
+ requireApprovalFor: ["admin", "financial", "destructive"],
1295
+ allowInstantWallet: true,
1296
+ allowProvisioning: true,
1297
+ maxCreditsPerRun: 25,
1298
+ executionRing: 2,
1299
+ killSwitchActive: false,
1300
+ killSwitchReason: null,
1301
+ blockDestructiveSql: true,
1302
+ languageMode: "hybrid",
1303
+ };
1304
+ export const MUXO_HARNESS_PRESETS = [
1305
+ {
1306
+ slug: "startup-builder",
1307
+ name: "Startup Builder (Balanced Velocity & Safety)",
1308
+ summary: "Auto-approves read, write, and cloud provisioning up to 50 credits/run while requiring human approval for financial, admin, and destructive actions.",
1309
+ recommendedFor: "Claude Code, Cursor, Codex, and Factory Droid full-stack shipping",
1310
+ naturalLanguageTriggers: [
1311
+ "Configure harness preset startup-builder",
1312
+ "Set agent profile to startup builder",
1313
+ "Balanced velocity mode",
1314
+ ],
1315
+ policyPatch: {
1316
+ mode: "enforce",
1317
+ executionRing: 1,
1318
+ requireApprovalFor: ["financial", "admin", "destructive"],
1319
+ maxCreditsPerRun: 50,
1320
+ allowProvisioning: true,
1321
+ allowInstantWallet: true,
1322
+ blockDestructiveSql: true,
1323
+ languageMode: "hybrid",
1324
+ },
1325
+ },
1326
+ {
1327
+ slug: "strict-production",
1328
+ name: "Strict Production (Zero-Trust & Human-in-the-Loop)",
1329
+ summary: "Auto-approves read-only tools, requires explicit human approval for every write, cloud provisioning, financial, or admin action, blocks destructive SQL, and caps runs at 25 credits.",
1330
+ recommendedFor: "Production SaaS operations, SecOps, and customer-facing ChatGPT / Claude agents",
1331
+ naturalLanguageTriggers: [
1332
+ "Configure harness preset strict-production",
1333
+ "Strict production mode",
1334
+ "Zero-trust human-in-the-loop mode",
1335
+ ],
1336
+ policyPatch: {
1337
+ mode: "enforce",
1338
+ executionRing: 2,
1339
+ requireApprovalFor: ["write", "provisioning", "financial", "admin", "destructive"],
1340
+ maxCreditsPerRun: 25,
1341
+ allowProvisioning: true,
1342
+ allowInstantWallet: true,
1343
+ blockDestructiveSql: true,
1344
+ languageMode: "technical",
1345
+ },
1346
+ },
1347
+ {
1348
+ slug: "read-only-auditor",
1349
+ name: "Read-Only Auditor (Zero Mutation & Compliance)",
1350
+ summary: "Allows read-only discovery, SEO/web intelligence, memory recall, Cedar policy compilation, and OTel/WORM audit exports while requiring approval or blocking mutations and cloud provisioning.",
1351
+ recommendedFor: "Security audits, research agents, and compliance reporting",
1352
+ naturalLanguageTriggers: [
1353
+ "Configure harness preset read-only-auditor",
1354
+ "Read-only auditor mode",
1355
+ "Compliance auditor profile",
1356
+ ],
1357
+ policyPatch: {
1358
+ mode: "enforce",
1359
+ executionRing: 3,
1360
+ requireApprovalFor: ["write", "provisioning", "financial", "admin", "destructive"],
1361
+ maxCreditsPerRun: 10,
1362
+ allowProvisioning: false,
1363
+ allowInstantWallet: true,
1364
+ blockDestructiveSql: true,
1365
+ languageMode: "hybrid",
1366
+ },
1367
+ },
1368
+ {
1369
+ slug: "finops-byok-zero-cost",
1370
+ name: "FinOps Zero-Cost (BYOK & Free-Tier Enforced)",
1371
+ summary: "Optimizes for 0-credit BYOK execution and free cloud infrastructure tiers with a tight 5-credit per-run cap and approval gates on paid operations.",
1372
+ recommendedFor: "High-volume background agents and cost-sensitive teams",
1373
+ naturalLanguageTriggers: [
1374
+ "Configure harness preset finops-byok-zero-cost",
1375
+ "FinOps zero-cost mode",
1376
+ "BYOK zero-credit profile",
1377
+ ],
1378
+ policyPatch: {
1379
+ mode: "enforce",
1380
+ executionRing: 2,
1381
+ requireApprovalFor: ["provisioning", "financial", "admin", "destructive"],
1382
+ maxCreditsPerRun: 5,
1383
+ allowProvisioning: true,
1384
+ allowInstantWallet: true,
1385
+ blockDestructiveSql: true,
1386
+ languageMode: "hybrid",
1387
+ customInstructions: [
1388
+ "Prefer 0-credit BYOK funding mode and free cloud plans whenever available.",
1389
+ ],
1390
+ },
1391
+ },
1392
+ ];
1393
+ export function resolveHarnessPreset(presetOrPrompt) {
1394
+ const raw = String(presetOrPrompt || "").trim().toLowerCase();
1395
+ if (!raw)
1396
+ return null;
1397
+ const exact = MUXO_HARNESS_PRESETS.find((p) => p.slug === raw);
1398
+ if (exact)
1399
+ return exact;
1400
+ if (/\b(strict[-\s]?prod|strict\s+production|zero[-\s]?trust|human[-\s]?in[-\s]?the[-\s]?loop)\b/i.test(raw)) {
1401
+ return MUXO_HARNESS_PRESETS[1];
1402
+ }
1403
+ if (/\b(read[-\s]?only\s+audit|auditor|zero[-\s]?mutation|compliance\s+auditor)\b/i.test(raw)) {
1404
+ return MUXO_HARNESS_PRESETS[2];
1405
+ }
1406
+ if (/\b(finops|zero[-\s]?cost|byok\s+mode|cost[-\s]?optimized)\b/i.test(raw)) {
1407
+ return MUXO_HARNESS_PRESETS[3];
1408
+ }
1409
+ if (/\b(startup[-\s]?builder|startup\s+mode|balanced\s+velocity|autonomous\s+dev|builder\s+preset)\b/i.test(raw)) {
1410
+ return MUXO_HARNESS_PRESETS[0];
1411
+ }
1412
+ return null;
1413
+ }
1414
+ export function buildHarnessConfigurationBundle(params) {
1415
+ const baseUrl = (params.baseUrl || "https://api.muxo.ai").replace(/\/+$/, "");
1416
+ const mcpUrl = `${baseUrl}/mcp`;
1417
+ const targetHarness = String(params.targetHarness || "all").toLowerCase();
1418
+ const policy = {
1419
+ ...DEFAULT_WORKSPACE_POLICY,
1420
+ ...(params.workspace.policy || {}),
1421
+ };
1422
+ const presetLabel = params.appliedPreset
1423
+ ? `${params.appliedPreset.name} (${params.appliedPreset.slug})`
1424
+ : `Current Workspace Policy (${policy.executionRing || "ring2_standard"}, max ${policy.maxCreditsPerRun ?? 25} credits/run)`;
1425
+ const headline = `Harness Configuration Ready for ${params.workspace.name}: ${presetLabel}.`;
1426
+ const explanation = formatHumanFriendlyExplanation({
1427
+ headline,
1428
+ nonTechnical: `${headline} You can control guardrails, memory time-travel, Temporal Saga playbooks, AWS Cedar policies, OpenTelemetry traces, and ROI analytics in plain English via 'POST /api/v1/do' or MCP 'get_run_context'.`,
1429
+ technical: `workspace=${params.workspace.id} | preset=${params.appliedPreset?.slug || "custom"} | mcpUrl=${mcpUrl} | ring=${policy.executionRing || "ring2_standard"} | maxCreditsPerRun=${policy.maxCreditsPerRun ?? 25}`,
1430
+ policy,
1431
+ });
1432
+ const naturalLanguageCheatsheet = [
1433
+ {
1434
+ category: "Turnkey & Custom Saga Playbooks",
1435
+ sayInPlainEnglish: "Run the fullstack cloud bootstrap playbook for acme",
1436
+ mcpEquivalent: {
1437
+ tool: "get_run_context",
1438
+ arguments: {
1439
+ action: "run_playbook",
1440
+ slug: "fullstack-cloud-bootstrap",
1441
+ input: { serviceRef: "acme" },
1442
+ },
1443
+ },
1444
+ restEndpoint: "POST /api/v1/playbooks/fullstack-cloud-bootstrap/run",
1445
+ },
1446
+ {
1447
+ category: "Custom Saga Playbook Authoring",
1448
+ sayInPlainEnglish: "Create playbook daily-seo-slack that runs instant.seo.audit and app.slack.send_message",
1449
+ mcpEquivalent: {
1450
+ tool: "get_run_context",
1451
+ arguments: {
1452
+ action: "create_playbook",
1453
+ prompt: "Create playbook daily-seo-slack that runs instant.seo.audit and app.slack.send_message",
1454
+ },
1455
+ },
1456
+ restEndpoint: "POST /api/v1/playbooks",
1457
+ },
1458
+ {
1459
+ category: "Temporal Workflow Rollback & Signals",
1460
+ sayInPlainEnglish: "Rollback the latest workflow because staging healthcheck failed",
1461
+ mcpEquivalent: {
1462
+ tool: "get_run_context",
1463
+ arguments: {
1464
+ action: "rollback_workflow",
1465
+ workflow_id: "latest",
1466
+ prompt: "Staging healthcheck failed",
1467
+ },
1468
+ },
1469
+ restEndpoint: "POST /api/v1/workflows/:id/rollback",
1470
+ },
1471
+ {
1472
+ category: "Graphiti Time-Travel & Multi-Hop Memory Graph",
1473
+ sayInPlainEnglish: "Show my knowledge graph as of 2026-10-20T00:00:00Z within 2 hops of workspace",
1474
+ mcpEquivalent: {
1475
+ tool: "get_run_context",
1476
+ arguments: {
1477
+ action: "memory_graph",
1478
+ as_of: "2026-10-20T00:00:00Z",
1479
+ focal_entity: "workspace",
1480
+ max_hops: 2,
1481
+ },
1482
+ },
1483
+ restEndpoint: "POST /api/v1/memory/graph",
1484
+ },
1485
+ {
1486
+ category: "AWS Cedar & OPA Policy-as-Code",
1487
+ sayInPlainEnglish: "Compile our guardrails to AWS Cedar and OPA Rego (or: Evaluate Cedar policy for resource.turso.database with DROP TABLE users)",
1488
+ mcpEquivalent: {
1489
+ tool: "get_run_context",
1490
+ arguments: {
1491
+ action: "cedar_policy",
1492
+ tool_slug: "resource.turso.database",
1493
+ input: { query: "DROP TABLE users" },
1494
+ },
1495
+ },
1496
+ restEndpoint: "GET /api/v1/governance/cedar | POST /api/v1/governance/cedar/evaluate",
1497
+ },
1498
+ {
1499
+ category: "OpenTelemetry GenAI & Langfuse Traces",
1500
+ sayInPlainEnglish: "Export OpenTelemetry traces and Langfuse batch",
1501
+ mcpEquivalent: {
1502
+ tool: "get_run_context",
1503
+ arguments: { action: "otel_traces", limit: 25 },
1504
+ },
1505
+ restEndpoint: "GET /api/v1/telemetry/otlp",
1506
+ },
1507
+ {
1508
+ category: "FinOps & Engineering ROI Analytics",
1509
+ sayInPlainEnglish: "What is our ROI and how many engineering hours have we saved?",
1510
+ mcpEquivalent: {
1511
+ tool: "get_run_context",
1512
+ arguments: { action: "roi_analytics" },
1513
+ },
1514
+ restEndpoint: "GET /api/v1/analytics/roi",
1515
+ },
1516
+ {
1517
+ category: "One-Shot Harness Preset & Guardrails",
1518
+ sayInPlainEnglish: "Configure harness preset strict-production and only allow emails to @muxo.ai",
1519
+ mcpEquivalent: {
1520
+ tool: "get_run_context",
1521
+ arguments: {
1522
+ action: "configure_harness",
1523
+ preset: "strict-production",
1524
+ prompt: "Only allow sending emails to @muxo.ai",
1525
+ },
1526
+ },
1527
+ restEndpoint: "POST /api/v1/harness/configure",
1528
+ },
1529
+ ];
1530
+ const systemPromptDirective = [
1531
+ `# Muxo Natural-Language & Harness Control Directive (${params.workspace.name})`,
1532
+ `- Active Profile: ${presetLabel}`,
1533
+ `- You can pass ANY plain-English instruction directly to \`get_run_context({ prompt: "..." })\` or \`POST ${baseUrl}/api/v1/do\` without needing to memorize sub-actions.`,
1534
+ `- Built-in Saga Playbooks: \`fullstack-cloud-bootstrap\`, \`competitor-seo-growth-brief\`, \`incident-containment-audit\`, \`customer-release-readiness\` (plus custom playbooks via "Create playbook <name> that runs ...").`,
1535
+ `- Time-Travel & BFS Memory: Ask "Show knowledge graph as of <ISO-date> within 2 hops of <entity>" or pass \`as_of\`, \`focal_entity\`, \`max_hops\`.`,
1536
+ `- Policy-as-Code & Telemetry: Ask "Compile policy to AWS Cedar", "Evaluate Cedar policy for <tool>", "Export OpenTelemetry traces", or "What is our ROI?".`,
1537
+ ].join("\n");
1538
+ return {
1539
+ ok: true,
1540
+ workspaceId: params.workspace.id,
1541
+ workspaceSlug: params.workspace.slug,
1542
+ targetHarness,
1543
+ appliedPreset: params.appliedPreset || null,
1544
+ availablePresets: MUXO_HARNESS_PRESETS,
1545
+ policy,
1546
+ harnessConfigs: {
1547
+ claudeCode: {
1548
+ installPluginCommand: `claude plugin marketplace add ${baseUrl}/.claude-plugin/marketplace.json && claude plugin install muxo@muxo`,
1549
+ addMcpCommand: `claude mcp add --transport http muxo ${mcpUrl}`,
1550
+ mcpJson: {
1551
+ mcpServers: {
1552
+ muxo: {
1553
+ type: "http",
1554
+ url: mcpUrl,
1555
+ headers: {
1556
+ Authorization: "Bearer ${MUXO_API_KEY}",
1557
+ },
1558
+ },
1559
+ },
1560
+ },
1561
+ },
1562
+ cursor: {
1563
+ filePath: ".cursor/mcp.json",
1564
+ mcpJson: {
1565
+ mcpServers: {
1566
+ muxo: {
1567
+ url: mcpUrl,
1568
+ headers: {
1569
+ Authorization: "Bearer ${MUXO_API_KEY}",
1570
+ },
1571
+ },
1572
+ },
1573
+ },
1574
+ },
1575
+ codex: {
1576
+ filePath: "~/.codex/config.toml",
1577
+ toml: `[mcp_servers.muxo]\nurl = "${mcpUrl}"\nbearer_token_env_var = "MUXO_API_KEY"\n`,
1578
+ },
1579
+ chatgpt: {
1580
+ mcpServerUrl: mcpUrl,
1581
+ authMode: "OAuth 2.1 (CIMD / DCR) or No Authentication for Instant tools",
1582
+ instructions: "In ChatGPT → Settings → Connectors / Plugins → Add custom MCP server, enter https://api.muxo.ai/mcp.",
1583
+ },
1584
+ claudeDesktop: {
1585
+ filePath: "claude_desktop_config.json",
1586
+ mcpJson: {
1587
+ mcpServers: {
1588
+ muxo: {
1589
+ command: "npx",
1590
+ args: ["-y", "@muxoai/cli@latest", "mcp"],
1591
+ env: {
1592
+ MUXO_API_KEY: "<YOUR_MUXO_API_KEY>",
1593
+ },
1594
+ },
1595
+ },
1596
+ },
1597
+ },
1598
+ factoryDroid: {
1599
+ mcpServerUrl: mcpUrl,
1600
+ skillCommand: `curl -fsSL ${baseUrl}/skill.md`,
1601
+ },
1602
+ },
1603
+ systemPromptDirective,
1604
+ naturalLanguageCheatsheet,
1605
+ explanation,
1606
+ humanMessage: explanation.preferred,
1607
+ };
1608
+ }
1609
+ export function extractPlaybookInputFromNaturalLanguage(prompt, explicitInput) {
1610
+ const out = { ...(explicitInput || {}) };
1611
+ const text = String(prompt || "").trim();
1612
+ const urlMatch = text.match(/https?:\/\/[^\s"'<>]+/i);
1613
+ if (urlMatch && !out.url) {
1614
+ out.url = urlMatch[0].replace(/[.,;!?)]+$/, "");
1615
+ }
1616
+ const providerMatch = text.match(/\b(neon|turso|supabase|upstash|cloudflare|vercel|firecrawl|github|slack|gmail|stripe|resend)\b/i);
1617
+ if (providerMatch && !out.provider) {
1618
+ out.provider = providerMatch[1].toLowerCase();
1619
+ }
1620
+ const forTargetMatch = text.match(/\b(?:for|on|target(?:ing)?|project|app|service)\s+["'`]?([a-zA-Z0-9._/-]{2,64})["'`]?/i);
1621
+ if (forTargetMatch?.[1] &&
1622
+ !/^(the|our|my|a|an|playbook|saga|workflow|cloud|production|staging)$/i.test(forTargetMatch[1]) &&
1623
+ !out.serviceRef) {
1624
+ out.serviceRef = forTargetMatch[1].replace(/[.,;!?)]+$/, "");
1625
+ }
1626
+ return out;
1627
+ }
1628
+ function parseRelativeOrIsoTimestamp(text) {
1629
+ const isoMatch = text.match(/\b(\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?)\b/);
1630
+ if (isoMatch?.[1]) {
1631
+ const raw = isoMatch[1];
1632
+ return raw.includes("T") ? raw : `${raw}T23:59:59.000Z`;
1633
+ }
1634
+ if (/\byesterday\b/i.test(text)) {
1635
+ return new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
1636
+ }
1637
+ const relMatch = text.match(/\b(\d+)\s*(hour|hr|day|week|minute|min)s?\s+ago\b/i);
1638
+ if (relMatch) {
1639
+ const count = Number(relMatch[1]);
1640
+ const unit = relMatch[2].toLowerCase();
1641
+ const mult = unit.startsWith("min")
1642
+ ? 60_000
1643
+ : unit.startsWith("h")
1644
+ ? 3_600_000
1645
+ : unit.startsWith("w")
1646
+ ? 7 * 86_400_000
1647
+ : 86_400_000;
1648
+ return new Date(Date.now() - count * mult).toISOString();
1649
+ }
1650
+ return null;
1651
+ }
1652
+ export function parseNaturalLanguageOssIntent(prompt, options) {
1653
+ const raw = String(prompt || "").trim();
1654
+ const cleaned = raw
1655
+ .replace(/^(?:hey\s+muxo[,:\s]*|muxo[,:\s]*|please\s+|can\s+you\s+)/i, "")
1656
+ .trim();
1657
+ if (!cleaned) {
1658
+ return { matched: false, kind: null, summary: "" };
1659
+ }
1660
+ // 1. Custom Playbook Creation ("Create playbook <name> that runs ...", "Define a saga playbook ...")
1661
+ if (/^(?:create|define|register|save|build|add)\s+(?:a\s+|new\s+|custom\s+)?(?:commercial\s+|saga\s+|durable\s+)?playbook\b/i.test(cleaned)) {
1662
+ const customPlaybook = parseNaturalLanguageCustomPlaybook(cleaned, options?.explicitInput);
1663
+ return {
1664
+ matched: true,
1665
+ kind: "create_playbook",
1666
+ customPlaybook,
1667
+ playbookSlug: customPlaybook.slug,
1668
+ summary: `Created custom ${customPlaybook.steps.length}-step Saga playbook '${customPlaybook.slug}'.`,
1669
+ };
1670
+ }
1671
+ // 2. List / Discover Playbooks ("List playbooks", "What playbooks are available?", "Show commercial saga playbooks")
1672
+ if (/^(?:list|show|what\s+are(?:\s+the|\s+our)?|get|inspect|browse)\s+(?:all\s+|available\s+|commercial\s+|turnkey\s+|saga\s+)?playbooks\b/i.test(cleaned) ||
1673
+ /\bwhat\s+playbooks\s+(?:can\s+we\s+run|are\s+available|do\s+you\s+have)\b/i.test(cleaned)) {
1674
+ return {
1675
+ matched: true,
1676
+ kind: "list_playbooks",
1677
+ summary: "Listed available turnkey and custom Saga playbooks.",
1678
+ };
1679
+ }
1680
+ // 3. Run Playbook ("Run fullstack cloud bootstrap playbook", "Bootstrap a fullstack cloud stack", "Run competitor SEO growth brief", "Execute playbook <slug>")
1681
+ const explicitPlaybookRun = /^(?:run|execute|launch|start|trigger)\s+(?:the\s+|our\s+|a\s+)?(?:commercial\s+|saga\s+|turnkey\s+)?playbook\b/i.test(cleaned) ||
1682
+ /\b(?:run|execute|launch|start|trigger)\b[\s\S]*\bplaybook\b/i.test(cleaned) ||
1683
+ /^(?:bootstrap\s+(?:a\s+|our\s+)?(?:fullstack|full-stack)\s+cloud|run\s+(?:fullstack|full-stack)\s+cloud\s+bootstrap|run\s+competitor\s+seo\s+growth\s+brief|run\s+incident\s+containment\s+audit|run\s+customer\s+release\s+readiness)\b/i.test(cleaned);
1684
+ if (explicitPlaybookRun) {
1685
+ const matchedPb = getCommercialPlaybook(cleaned, options?.customPlaybooks || []) ||
1686
+ MUXO_COMMERCIAL_PLAYBOOKS[0];
1687
+ const playbookInput = extractPlaybookInputFromNaturalLanguage(cleaned, options?.explicitInput);
1688
+ return {
1689
+ matched: true,
1690
+ kind: "run_playbook",
1691
+ playbookSlug: matchedPb.slug,
1692
+ playbookInput,
1693
+ summary: `Execute Saga playbook '${matchedPb.name}' (${matchedPb.slug}).`,
1694
+ };
1695
+ }
1696
+ // 4. Temporal Workflow Saga Rollback ("Rollback workflow wf_123 because ...", "Rollback the latest workflow", "Undo last saga workflow", "Compensate workflow wf_...")
1697
+ if (/^(?:rollback|roll\s+back|compensate|abort\s+and\s+rollback|undo)\s+(?:the\s+|our\s+|my\s+)?(?:latest\s+|last\s+|most\s+recent\s+)?(?:durable\s+|temporal\s+|saga\s+|playbook\s+)?(?:workflow|saga)(?:\s+(wf_[a-zA-Z0-9_-]+))?/i.test(cleaned) ||
1698
+ /\b(?:rollback|roll\s+back|compensate)\s+(wf_[a-zA-Z0-9_-]+)\b/i.test(cleaned)) {
1699
+ const wfIdMatch = cleaned.match(/\b(wf_[a-zA-Z0-9_-]+)\b/);
1700
+ const reasonMatch = cleaned.match(/(?:because|reason|due\s+to)[:\s]+(.+)$/i);
1701
+ const workflowId = wfIdMatch?.[1] || "latest";
1702
+ const workflowReason = reasonMatch?.[1]?.trim() ||
1703
+ `Rolled back via natural language: "${raw.slice(0, 100)}"`;
1704
+ return {
1705
+ matched: true,
1706
+ kind: "rollback_workflow",
1707
+ workflowId,
1708
+ workflowReason,
1709
+ summary: `Execute LIFO Saga rollback for workflow '${workflowId}'.`,
1710
+ };
1711
+ }
1712
+ // 5. Temporal Workflow Signal ("Signal workflow wf_123 ...", "Send approval signal to workflow wf_123", "Approve workflow wf_123")
1713
+ if (/^(?:signal|send\s+(?:a\s+)?signal\s+to|approve\s+workflow|resume\s+workflow)\b/i.test(cleaned) &&
1714
+ /\b(wf_[a-zA-Z0-9_-]+|workflow|saga)\b/i.test(cleaned)) {
1715
+ const wfIdMatch = cleaned.match(/\b(wf_[a-zA-Z0-9_-]+)\b/);
1716
+ const workflowId = wfIdMatch?.[1] || "latest";
1717
+ let signalName = "human.approval.granted";
1718
+ if (/\boauth\b|\bconnection\b/i.test(cleaned)) {
1719
+ signalName = "oauth.connection.active";
1720
+ }
1721
+ else if (/\b(abort|cancel|reject)\b/i.test(cleaned)) {
1722
+ signalName = "saga.abort";
1723
+ }
1724
+ else {
1725
+ const sigMatch = cleaned.match(/\b((?:human|oauth|saga|workflow)\.[a-z0-9_.]+)\b/i);
1726
+ if (sigMatch?.[1])
1727
+ signalName = sigMatch[1];
1728
+ }
1729
+ return {
1730
+ matched: true,
1731
+ kind: "signal_workflow",
1732
+ workflowId,
1733
+ signalName,
1734
+ signalPayload: {
1735
+ source: "natural_language",
1736
+ prompt: raw,
1737
+ ...(options?.explicitInput || {}),
1738
+ },
1739
+ summary: `Deliver Temporal signal '${signalName}' to workflow '${workflowId}'.`,
1740
+ };
1741
+ }
1742
+ // 6. Temporal Workflow Event History ("Show Temporal history for workflow wf_123", "Inspect latest workflow saga history")
1743
+ if (/\b(?:temporal\s+(?:event\s+)?history|workflow\s+(?:event\s+)?history|saga\s+history)\b/i.test(cleaned) ||
1744
+ (/^(?:show|inspect|get|explain)\s+(?:the\s+|our\s+)?(?:latest\s+|last\s+)?(?:durable\s+|temporal\s+)?workflow\b/i.test(cleaned) &&
1745
+ !/\bplaybooks\b/i.test(cleaned))) {
1746
+ const wfIdMatch = cleaned.match(/\b(wf_[a-zA-Z0-9_-]+)\b/);
1747
+ const workflowId = wfIdMatch?.[1] || "latest";
1748
+ return {
1749
+ matched: true,
1750
+ kind: "workflow_history",
1751
+ workflowId,
1752
+ summary: `Inspect Temporal EventHistory for workflow '${workflowId}'.`,
1753
+ };
1754
+ }
1755
+ // 7. AWS Cedar & OPA Rego Policy-as-Code Compile or Evaluate
1756
+ if (/\b(?:cedar|opa\s+rego|rego\s+policy|policy[-\s]as[-\s]code)\b/i.test(cleaned)) {
1757
+ const toolMatch = cleaned.match(/\b((?:instant|app|resource|billing)\.[a-z0-9_]+(?:\.[a-z0-9_]+)+)\b/i);
1758
+ const isEval = Boolean(toolMatch) ||
1759
+ /\b(?:evaluate|test|check|simulate|would\s+cedar\s+allow|drop\s+table|truncate\s+table|delete\s+from)\b/i.test(cleaned);
1760
+ if (isEval) {
1761
+ const toolSlug = toolMatch?.[1] || "resource.turso.database";
1762
+ const evaluationInput = {
1763
+ ...(options?.explicitInput || {}),
1764
+ };
1765
+ const sqlMatch = cleaned.match(/\b((?:DROP|TRUNCATE|DELETE|ALTER|SELECT|INSERT|UPDATE)\s+[\s\S]+)$/i);
1766
+ if (sqlMatch?.[1] && !evaluationInput.query) {
1767
+ evaluationInput.query = sqlMatch[1].trim();
1768
+ }
1769
+ const emailMatch = cleaned.match(/\b([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})\b/);
1770
+ if (emailMatch?.[1] && !evaluationInput.to && !evaluationInput.recipient_email) {
1771
+ evaluationInput.to = emailMatch[1];
1772
+ }
1773
+ return {
1774
+ matched: true,
1775
+ kind: "cedar_evaluate",
1776
+ toolSlug,
1777
+ evaluationInput,
1778
+ summary: `Evaluate AWS Cedar 4.0 & OPA Rego v1 policy for '${toolSlug}'.`,
1779
+ };
1780
+ }
1781
+ return {
1782
+ matched: true,
1783
+ kind: "cedar_compile",
1784
+ summary: "Compile workspace guardrails into AWS Cedar 4.0 and OPA Rego v1.",
1785
+ };
1786
+ }
1787
+ // 8. OpenTelemetry (OTel GenAI) & Langfuse Trace Export
1788
+ if (/\b(?:opentelemetry|otel\b|otlp\b|langfuse|w3c\s+trace|trace\s+spans|telemetry\s+traces|genai\s+spans)\b/i.test(cleaned)) {
1789
+ const limitMatch = cleaned.match(/\b(\d+)\s+(?:traces|spans|runs)\b/i);
1790
+ return {
1791
+ matched: true,
1792
+ kind: "otel_traces",
1793
+ limit: limitMatch ? Math.min(100, Math.max(1, Number(limitMatch[1]))) : 25,
1794
+ summary: "Export W3C OpenTelemetry GenAI 1.29.0 spans and Langfuse batch.",
1795
+ };
1796
+ }
1797
+ // 9. FinOps & Commercial ROI Unit-Economics Report
1798
+ if (/\b(?:commercial\s+roi|finops|unit\s+economics|engineering\s+(?:hours|time|value)\s+saved|byok\s+savings|return\s+on\s+investment)\b/i.test(cleaned) ||
1799
+ /^(?:what\s+is\s+(?:our|my)\s+roi|show\s+(?:our|my)?\s*roi|calculate\s+roi|how\s+much\s+(?:time|money|hours|credits)\s+have\s+we\s+saved)\b/i.test(cleaned)) {
1800
+ return {
1801
+ matched: true,
1802
+ kind: "roi_analytics",
1803
+ summary: "Generate FinOps unit-economics and engineering ROI report.",
1804
+ };
1805
+ }
1806
+ // 10. Harness Preset & Agent Configuration ("Configure harness preset strict-production", "Show Cursor harness config", "Set agent profile to startup-builder")
1807
+ const matchedPreset = resolveHarnessPreset(cleaned);
1808
+ if (matchedPreset ||
1809
+ /\b(?:configure\s+(?:muxo\s+)?harness|harness\s+(?:config|configuration|preset|setup)|agent\s+harness\s+profile|mcp\s+config\s+for\s+(?:claude|cursor|codex|chatgpt|droid))\b/i.test(cleaned)) {
1810
+ const harnessMatch = cleaned.match(/\b(claude[-\s]?code|claude[-\s]?desktop|cursor|codex|chatgpt|droid|factory)\b/i);
1811
+ const targetHarness = harnessMatch
1812
+ ? harnessMatch[1].toLowerCase().replace(/\s+/g, "-")
1813
+ : "all";
1814
+ // Check if the user also included an inline guardrail (e.g. "and only allow emails to @muxo.ai")
1815
+ const extraMatch = cleaned.match(/\band\s+((?:only|never|require|block|cap|limit|don't|do\s+not)\s+.+)$/i);
1816
+ return {
1817
+ matched: true,
1818
+ kind: "configure_harness",
1819
+ preset: matchedPreset,
1820
+ targetHarness,
1821
+ extraGuardrailPrompt: extraMatch?.[1]?.trim() || null,
1822
+ summary: matchedPreset
1823
+ ? `Configure harness preset '${matchedPreset.slug}' (${matchedPreset.name}).`
1824
+ : `Inspect harness configuration & presets for '${targetHarness}'.`,
1825
+ };
1826
+ }
1827
+ // 11. Graphiti Bi-Temporal Knowledge Graph with Time-Travel (`as of ...`) & Multi-Hop BFS (`within N hops of ...`)
1828
+ if (/\b(?:memory\s+graph|knowledge\s+graph|temporal\s+graph|fact\s+lineage|bi[-\s]?temporal\s+(?:graph|lineage|facts)|graphiti|subgraph)\b/i.test(cleaned)) {
1829
+ const asOf = parseRelativeOrIsoTimestamp(cleaned);
1830
+ const hopsMatch = cleaned.match(/\b(\d+)[-\s]*hops?\b/i);
1831
+ const maxHops = hopsMatch
1832
+ ? Math.min(4, Math.max(1, Number(hopsMatch[1])))
1833
+ : undefined;
1834
+ const focalMatch = cleaned.match(/\b(?:around|for\s+entity|focal\s+entity|centered\s+on|of\s+entity|neighborhood\s+of)\s+["'`]?([a-zA-Z0-9:._-]+)["'`]?/i) ||
1835
+ cleaned.match(/\bwithin\s+\d+\s+hops?\s+of\s+["'`]?([a-zA-Z0-9:._-]+)["'`]?/i);
1836
+ const focalEntity = focalMatch?.[1] &&
1837
+ !/^(the|our|my|graph|memory|knowledge|yesterday|today)$/i.test(focalMatch[1])
1838
+ ? focalMatch[1]
1839
+ : null;
1840
+ return {
1841
+ matched: true,
1842
+ kind: "memory_graph",
1843
+ asOf,
1844
+ focalEntity,
1845
+ maxHops,
1846
+ summary: `Query Graphiti bi-temporal knowledge graph${asOf ? ` as of ${asOf}` : ""}${focalEntity ? ` around '${focalEntity}' (${maxHops || 2} hops)` : ""}.`,
1847
+ };
1848
+ }
1849
+ return { matched: false, kind: null, summary: "" };
1850
+ }
1851
+ // ============================================================================
1852
+ // 7. COMMERCIAL APPROVAL IMPACT PREVIEW, BUSINESS RECEIPTS & RECONCILIATION
1853
+ // ============================================================================
1854
+ function inferTargetEntityFromInput(toolSlug, input) {
1855
+ const candidates = [
1856
+ input.customer_id,
1857
+ input.customerId,
1858
+ input.account_id,
1859
+ input.accountId,
1860
+ input.to,
1861
+ input.recipient_email,
1862
+ input.email,
1863
+ input.channel,
1864
+ input.repo,
1865
+ input.repository,
1866
+ input.url,
1867
+ input.domain,
1868
+ input.name,
1869
+ input.project_name,
1870
+ input.database_name,
1871
+ input.service_ref,
1872
+ input.query,
1873
+ ];
1874
+ for (const c of candidates) {
1875
+ if (typeof c === "string" && c.trim()) {
1876
+ return c.trim().slice(0, 80);
1877
+ }
1878
+ }
1879
+ const parts = String(toolSlug || "").split(".");
1880
+ return parts.length >= 2 ? `${parts[1]}:${parts.slice(2).join(".") || "resource"}` : toolSlug;
1881
+ }
1882
+ export function buildApprovalImpactPreview(params) {
1883
+ const input = params.input || {};
1884
+ const targetEntity = inferTargetEntityFromInput(params.toolSlug, input);
1885
+ const fundingMode = params.fundingMode ||
1886
+ params.supplierSettlement?.fundingMode ||
1887
+ (params.creditCost === 0 ? "byok" : "muxo_funded");
1888
+ const cents = typeof params.supplierSettlement?.userRetailChargeCents === "number"
1889
+ ? params.supplierSettlement.userRetailChargeCents
1890
+ : (params.creditCost || 0) * 1;
1891
+ const estimatedCostUsd = Number((cents / 100).toFixed(2));
1892
+ const costDisplay = fundingMode === "byok"
1893
+ ? `$0.00 USD (0 credits · Customer BYOK key)`
1894
+ : `$${estimatedCostUsd.toFixed(2)} USD (${params.creditCost} credit${params.creditCost === 1 ? "" : "s"} · Muxo Master Wallet)`;
1895
+ let whatChanges = params.reason && params.reason.trim() && params.reason !== `Execute ${params.toolSlug}`
1896
+ ? `${params.reason.trim()} via ${params.toolSlug} on ${targetEntity}`
1897
+ : `Execute ${params.toolSlug} (${params.riskLevel} risk) targeting ${targetEntity}`;
1898
+ if (params.riskLevel === "read") {
1899
+ whatChanges = `Read-only query via ${params.toolSlug} on ${targetEntity} (no external state mutation)`;
1900
+ }
1901
+ else if (params.lane === "stripe_projects" || params.riskLevel === "provisioning") {
1902
+ whatChanges = `Provision or mutate cloud infrastructure (${params.toolSlug}) for ${targetEntity}`;
1903
+ }
1904
+ else if (params.riskLevel === "financial") {
1905
+ whatChanges = `Execute financial/billing action (${params.toolSlug}) affecting ${targetEntity}`;
1906
+ }
1907
+ else if (params.riskLevel === "destructive") {
1908
+ whatChanges = `Execute destructive operation (${params.toolSlug}) on ${targetEntity}`;
1909
+ }
1910
+ let whoIsAffected = `Workspace ${params.workspaceName || "environment"} (${targetEntity})`;
1911
+ if (typeof input.customer_id === "string" || typeof input.customerId === "string") {
1912
+ whoIsAffected = `Customer account ${input.customer_id || input.customerId}`;
1913
+ }
1914
+ else if (typeof input.to === "string" || typeof input.recipient_email === "string") {
1915
+ whoIsAffected = `Recipient ${input.to || input.recipient_email}`;
1916
+ }
1917
+ else if (typeof input.channel === "string") {
1918
+ whoIsAffected = `Channel ${input.channel} subscribers`;
1919
+ }
1920
+ else if (typeof input.repo === "string" || typeof input.repository === "string") {
1921
+ whoIsAffected = `Repository ${input.repo || input.repository} collaborators`;
1922
+ }
1923
+ const triggeredRule = params.decisionRecord
1924
+ ? `${params.decisionRecord.matchedRule} (${params.decisionRecord.verdict.toUpperCase()}): ${params.decisionRecord.reason}`
1925
+ : `risk_gate:${params.riskLevel}`;
1926
+ const reversibility = params.riskLevel === "read"
1927
+ ? "reversible"
1928
+ : params.riskLevel === "destructive"
1929
+ ? "irreversible"
1930
+ : "compensatable_saga";
1931
+ const recoveryBehavior = reversibility === "reversible"
1932
+ ? "Read-only call; safe to retry idempotently with zero side effects and zero credit charge on failure."
1933
+ : reversibility === "compensatable_saga"
1934
+ ? "Execute-once idempotency lock prevents duplicate execution; LIFO Saga compensation available on downstream failure; 0 credits charged if call fails."
1935
+ : "High-impact destructive operation; guarded by execute-once lock and human approval gate; 0 credits charged if rejected or failed.";
1936
+ return {
1937
+ whatChanges,
1938
+ whoIsAffected,
1939
+ targetEntity,
1940
+ estimatedCostUsd,
1941
+ creditCost: params.creditCost,
1942
+ fundingMode,
1943
+ costDisplay,
1944
+ triggeredRule,
1945
+ reversibility,
1946
+ recoveryBehavior,
1947
+ };
1948
+ }
1949
+ export function buildBusinessReceiptSummary(params) {
1950
+ const input = params.input || {};
1951
+ const targetEntity = inferTargetEntityFromInput(params.toolSlug, input);
1952
+ const fundingMode = params.supplierSettlement?.fundingMode ||
1953
+ (params.creditsMetered === 0 ? "byok" : "muxo_funded");
1954
+ const cents = params.status === "succeeded"
1955
+ ? typeof params.supplierSettlement?.userRetailChargeCents === "number"
1956
+ ? params.supplierSettlement.userRetailChargeCents
1957
+ : (params.creditsMetered || 0) * 1
1958
+ : 0;
1959
+ const costUsd = Number((cents / 100).toFixed(2));
1960
+ const creditsCharged = params.status === "succeeded" ? params.creditsMetered : 0;
1961
+ const costDisplay = params.status !== "succeeded"
1962
+ ? `$0.00 USD (0 credits · Zero-charge failure protection)`
1963
+ : fundingMode === "byok"
1964
+ ? `$0.00 USD (0 credits · Customer BYOK key)`
1965
+ : `$${costUsd.toFixed(2)} USD (${creditsCharged} credit${creditsCharged === 1 ? "" : "s"} · Muxo Master Wallet)`;
1966
+ const whatChanged = params.status === "succeeded"
1967
+ ? params.riskLevel === "read"
1968
+ ? `Retrieved verified data via ${params.toolSlug} from ${targetEntity} (no external mutation)`
1969
+ : `Completed governed ${params.riskLevel} action via ${params.toolSlug} on ${targetEntity}`
1970
+ : params.status === "cancelled"
1971
+ ? `Cancelled ${params.toolSlug} on ${targetEntity} before completion (no changes persisted)`
1972
+ : `Attempted ${params.toolSlug} on ${targetEntity}, halted safely before completion`;
1973
+ const approver = params.approvedBy || "policy:auto";
1974
+ const ruleLabel = params.decisionRecord?.matchedRule || `ring_policy:${params.riskLevel}`;
1975
+ const whoAuthorized = approver === "policy:auto"
1976
+ ? `Auto-authorized by Workspace Policy (${ruleLabel})`
1977
+ : `Human-approved by ${approver} (enforced via ${ruleLabel})`;
1978
+ const whatSucceeded = params.status === "succeeded"
1979
+ ? `Action ${params.toolSlug} succeeded on ${targetEntity} and cryptographic receipt was sealed in the workspace Merkle audit chain.`
1980
+ : `Governance pre-flight and zero-charge wallet protection succeeded; external mutation did not complete.`;
1981
+ const whatRemainsUnresolved = params.status === "succeeded"
1982
+ ? []
1983
+ : [
1984
+ params.error
1985
+ ? `Resolve upstream error: ${params.error}`
1986
+ : `Inspect run state or retry via a fresh governed plan for ${params.toolSlug}`,
1987
+ ];
1988
+ const reconciliationStatus = params.status === "succeeded"
1989
+ ? "verified_complete"
1990
+ : params.status === "cancelled"
1991
+ ? "cancelled"
1992
+ : "failed_zero_charge";
1993
+ return {
1994
+ whatChanged,
1995
+ whoAuthorized,
1996
+ whatSucceeded,
1997
+ whatRemainsUnresolved,
1998
+ costUsd,
1999
+ creditsCharged,
2000
+ fundingMode,
2001
+ costDisplay,
2002
+ reconciliationStatus,
2003
+ };
2004
+ }
2005
+ export function buildRunReconciliationReport(params) {
2006
+ const { run, plan, receipt } = params;
2007
+ const toolSlug = run?.toolSlug || plan?.toolSlug || "instant.web.search";
2008
+ const lane = run?.lane || plan?.lane || "composio_instant";
2009
+ const riskLevel = run?.riskLevel || plan?.riskLevel || "read";
2010
+ const creditsMetered = run?.creditsMetered ?? 0;
2011
+ const status = run?.status || "queued";
2012
+ const businessSummary = receipt?.businessSummary ||
2013
+ buildBusinessReceiptSummary({
2014
+ toolSlug,
2015
+ lane,
2016
+ riskLevel,
2017
+ status: status === "succeeded"
2018
+ ? "succeeded"
2019
+ : status === "cancelled"
2020
+ ? "cancelled"
2021
+ : "failed",
2022
+ creditsMetered,
2023
+ input: run?.input || plan?.input,
2024
+ output: run?.output,
2025
+ error: run?.error,
2026
+ approvedBy: plan?.approvedBy,
2027
+ actorId: run?.actorId || plan?.actorId,
2028
+ decisionRecord: receipt?.decisionRecord || plan?.decisionRecord || null,
2029
+ supplierSettlement: receipt?.supplierSettlement || plan?.supplierSettlement || null,
2030
+ });
2031
+ const receiptVerified = params.signatureValid !== undefined
2032
+ ? Boolean(receipt && params.signatureValid)
2033
+ : Boolean(receipt && receipt.receiptHash && receipt.signature);
2034
+ const reconciliationStatus = status === "succeeded" && receiptVerified
2035
+ ? "verified_complete"
2036
+ : status === "failed" && creditsMetered === 0
2037
+ ? "failed_zero_charge"
2038
+ : status === "cancelled"
2039
+ ? "cancelled"
2040
+ : "needs_reconciliation";
2041
+ return {
2042
+ ok: true,
2043
+ runId: run?.id || plan?.runId || "unexecuted",
2044
+ planId: run?.planId || plan?.id || "unknown",
2045
+ workspaceId: run?.workspaceId || plan?.workspaceId || "unknown",
2046
+ toolSlug,
2047
+ status,
2048
+ reconciliationStatus,
2049
+ executeOnceEnforced: Boolean((plan?.runId && run?.id && plan.runId === run.id) || run?.id || plan?.id),
2050
+ idempotentReplaySafe: true,
2051
+ zeroChargeOnFailureVerified: status === "succeeded" || creditsMetered === 0,
2052
+ creditsMetered,
2053
+ estimatedCostUsd: businessSummary.costUsd,
2054
+ receiptVerified,
2055
+ receiptId: receipt?.id || run?.receiptId || null,
2056
+ businessSummary,
2057
+ recommendedNextAction: reconciliationStatus === "verified_complete"
2058
+ ? "No action required — execution and cryptographic receipt are verified complete."
2059
+ : reconciliationStatus === "failed_zero_charge"
2060
+ ? "Zero credits were charged. Inspect error details and create a new plan if retry is desired."
2061
+ : !run && plan
2062
+ ? `Plan '${plan.id}' (${plan.approvalStatus}) has not been executed yet; no credits charged.`
2063
+ : "Inspect upstream provider state or re-verify receipt chain.",
2064
+ };
2065
+ }