@corbat-tech/coco 2.37.0 → 2.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -19438,6 +19438,199 @@ z.string().regex(
19438
19438
  // src/cli/repl/agents/manager.ts
19439
19439
  init_logger();
19440
19440
 
19441
+ // src/runtime/multi-agent.ts
19442
+ var SharedWorkspaceState = class {
19443
+ facts = /* @__PURE__ */ new Map();
19444
+ decisions = /* @__PURE__ */ new Map();
19445
+ risks = /* @__PURE__ */ new Map();
19446
+ files = /* @__PURE__ */ new Map();
19447
+ testResults = /* @__PURE__ */ new Map();
19448
+ artifacts = [];
19449
+ writeFact(key, value) {
19450
+ this.facts.set(key, value);
19451
+ }
19452
+ recordDecision(key, value) {
19453
+ this.decisions.set(key, value);
19454
+ }
19455
+ recordRisk(key, value) {
19456
+ this.risks.set(key, value);
19457
+ }
19458
+ recordFile(path44, value) {
19459
+ this.files.set(path44, value);
19460
+ }
19461
+ recordTestResult(key, value) {
19462
+ this.testResults.set(key, value);
19463
+ }
19464
+ addArtifact(artifact) {
19465
+ this.artifacts.push(cloneArtifact(artifact));
19466
+ }
19467
+ readForRole(role) {
19468
+ const includeSensitive = role === "security" || role === "integrator" || role === "pm";
19469
+ return {
19470
+ facts: Object.fromEntries(this.facts),
19471
+ decisions: Object.fromEntries(this.decisions),
19472
+ risks: includeSensitive ? Object.fromEntries(this.risks) : {},
19473
+ files: Object.fromEntries(this.files),
19474
+ testResults: Object.fromEntries(this.testResults),
19475
+ artifacts: this.artifacts.filter((artifact) => includeSensitive || artifact.kind !== "riskReport").map(cloneArtifact)
19476
+ };
19477
+ }
19478
+ snapshot() {
19479
+ return {
19480
+ facts: Object.fromEntries(this.facts),
19481
+ decisions: Object.fromEntries(this.decisions),
19482
+ risks: Object.fromEntries(this.risks),
19483
+ files: Object.fromEntries(this.files),
19484
+ testResults: Object.fromEntries(this.testResults),
19485
+ artifacts: this.artifacts.map(cloneArtifact)
19486
+ };
19487
+ }
19488
+ };
19489
+ function createAgentArtifact(input) {
19490
+ return {
19491
+ ...input,
19492
+ id: input.id ?? `artifact-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
19493
+ createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
19494
+ };
19495
+ }
19496
+ function createSummaryArtifact(output, metadata = {}) {
19497
+ return createAgentArtifact({
19498
+ kind: "summary",
19499
+ content: output,
19500
+ title: metadata.title ?? "Agent summary",
19501
+ agentRunId: metadata.agentRunId,
19502
+ taskId: metadata.taskId
19503
+ });
19504
+ }
19505
+ function normalizeAgentRunResult(input) {
19506
+ const completedAt = input.completedAt ?? (/* @__PURE__ */ new Date()).toISOString();
19507
+ const startedAt = input.startedAt ?? completedAt;
19508
+ const status = input.status ?? (input.success ? "completed" : "failed");
19509
+ const artifacts = input.artifacts && input.artifacts.length > 0 ? input.artifacts.map(cloneArtifact) : [createSummaryArtifact(input.output, { agentRunId: input.id, taskId: input.taskId })];
19510
+ return {
19511
+ id: input.id,
19512
+ taskId: input.taskId,
19513
+ role: input.role,
19514
+ status,
19515
+ success: input.success,
19516
+ output: input.output,
19517
+ artifacts,
19518
+ toolsUsed: [...input.toolsUsed ?? []],
19519
+ turns: input.turns ?? 0,
19520
+ durationMs: input.durationMs ?? 0,
19521
+ usage: input.usage,
19522
+ error: input.error,
19523
+ startedAt,
19524
+ completedAt,
19525
+ metadata: input.metadata
19526
+ };
19527
+ }
19528
+ function validateAgentCapabilities(capability, requiredTools = []) {
19529
+ const allowed = new Set(capability.allowedTools);
19530
+ return requiredTools.filter((tool) => !allowed.has(tool)).map((tool) => ({
19531
+ code: "missing-dependency",
19532
+ message: `Tool '${tool}' is not allowed for agent role '${capability.role}'.`
19533
+ }));
19534
+ }
19535
+ function validateAgentGraph(graph) {
19536
+ const issues = [];
19537
+ const nodeIds = /* @__PURE__ */ new Set();
19538
+ const gateIds = new Set((graph.gates ?? []).map((gate) => gate.id));
19539
+ if (graph.parallelism !== void 0 && graph.parallelism < 1) {
19540
+ issues.push({
19541
+ code: "invalid-parallelism",
19542
+ message: "Graph parallelism must be greater than zero."
19543
+ });
19544
+ }
19545
+ for (const node of graph.nodes) {
19546
+ if (nodeIds.has(node.id)) {
19547
+ issues.push({
19548
+ code: "duplicate-node",
19549
+ message: `Duplicate graph node '${node.id}'.`,
19550
+ nodeId: node.id
19551
+ });
19552
+ }
19553
+ nodeIds.add(node.id);
19554
+ if (node.retryPolicy && node.retryPolicy.maxAttempts < 1) {
19555
+ issues.push({
19556
+ code: "invalid-retry-policy",
19557
+ message: `Node '${node.id}' retry policy must allow at least one attempt.`,
19558
+ nodeId: node.id
19559
+ });
19560
+ }
19561
+ for (const dep of node.dependsOn ?? []) {
19562
+ if (!nodeIds.has(dep) && !graph.nodes.some((candidate) => candidate.id === dep)) {
19563
+ issues.push({
19564
+ code: "missing-dependency",
19565
+ message: `Node '${node.id}' depends on missing node '${dep}'.`,
19566
+ nodeId: node.id
19567
+ });
19568
+ }
19569
+ }
19570
+ for (const gate of node.gates ?? []) {
19571
+ if (!gateIds.has(gate)) {
19572
+ issues.push({
19573
+ code: "missing-gate",
19574
+ message: `Node '${node.id}' references missing gate '${gate}'.`,
19575
+ nodeId: node.id,
19576
+ gateId: gate
19577
+ });
19578
+ }
19579
+ }
19580
+ }
19581
+ for (const edge of graph.edges ?? []) {
19582
+ if (!nodeIds.has(edge.from)) {
19583
+ issues.push({
19584
+ code: "missing-edge-node",
19585
+ message: `Graph edge references missing source node '${edge.from}'.`,
19586
+ nodeId: edge.from
19587
+ });
19588
+ }
19589
+ if (!nodeIds.has(edge.to)) {
19590
+ issues.push({
19591
+ code: "missing-edge-node",
19592
+ message: `Graph edge references missing target node '${edge.to}'.`,
19593
+ nodeId: edge.to
19594
+ });
19595
+ }
19596
+ }
19597
+ const levels = buildExecutionLevels(graph, issues);
19598
+ return { valid: issues.length === 0, issues, levels };
19599
+ }
19600
+ function buildExecutionLevels(graph, issues) {
19601
+ const dependencies = /* @__PURE__ */ new Map();
19602
+ for (const node of graph.nodes) {
19603
+ dependencies.set(node.id, new Set(node.dependsOn ?? []));
19604
+ }
19605
+ for (const edge of graph.edges ?? []) {
19606
+ if (dependencies.has(edge.to)) {
19607
+ dependencies.get(edge.to).add(edge.from);
19608
+ }
19609
+ }
19610
+ const completed = /* @__PURE__ */ new Set();
19611
+ const levels = [];
19612
+ while (completed.size < dependencies.size) {
19613
+ const level = [...dependencies.entries()].filter(([id, deps]) => !completed.has(id) && [...deps].every((dep) => completed.has(dep))).map(([id]) => id);
19614
+ if (level.length === 0) {
19615
+ const remaining = [...dependencies.keys()].filter((id) => !completed.has(id));
19616
+ issues.push({
19617
+ code: "cycle",
19618
+ message: `Graph contains a cycle involving: ${remaining.join(", ")}.`
19619
+ });
19620
+ return levels;
19621
+ }
19622
+ for (const id of level) completed.add(id);
19623
+ levels.push(level);
19624
+ }
19625
+ return levels;
19626
+ }
19627
+ function cloneArtifact(artifact) {
19628
+ return {
19629
+ ...artifact,
19630
+ metadata: artifact.metadata ? { ...artifact.metadata } : void 0
19631
+ };
19632
+ }
19633
+
19441
19634
  // src/cli/repl/agents/prompts.ts
19442
19635
  var EXPLORE_PROMPT = `You are an exploration agent for Corbat-Coco.
19443
19636
  Your purpose is to search the codebase to answer questions and gather information.
@@ -20018,11 +20211,15 @@ var AgentManager = class extends EventEmitter {
20018
20211
  failedAgent.status = "failed";
20019
20212
  failedAgent.error = error;
20020
20213
  failedAgent.completedAt = /* @__PURE__ */ new Date();
20021
- return {
20214
+ return this.buildResult({
20022
20215
  agent: failedAgent,
20023
20216
  success: false,
20024
- output: error
20025
- };
20217
+ output: error,
20218
+ turns: 0,
20219
+ toolsUsed: [],
20220
+ startedAt: failedAgent.createdAt.toISOString(),
20221
+ usage: { inputTokens: 0, outputTokens: 0 }
20222
+ });
20026
20223
  }
20027
20224
  const agent = this.createAgent(type, task);
20028
20225
  this.activeAgents.set(agent.id, agent);
@@ -20074,11 +20271,15 @@ var AgentManager = class extends EventEmitter {
20074
20271
  options.onStatusChange?.(agent);
20075
20272
  this.logger.error(`Agent ${agent.id} failed unexpectedly`, { error: errorMessage });
20076
20273
  this.emitEvent("fail", agent);
20077
- return {
20274
+ return this.buildResult({
20078
20275
  agent,
20079
20276
  success: false,
20080
- output: errorMessage
20081
- };
20277
+ output: errorMessage,
20278
+ turns: 0,
20279
+ toolsUsed: [],
20280
+ startedAt: agent.createdAt.toISOString(),
20281
+ usage: { inputTokens: 0, outputTokens: 0 }
20282
+ });
20082
20283
  }
20083
20284
  }
20084
20285
  /**
@@ -20199,6 +20400,8 @@ var AgentManager = class extends EventEmitter {
20199
20400
  let finalOutput = "";
20200
20401
  let iteration = 0;
20201
20402
  const maxTurns = config.maxTurns ?? 10;
20403
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
20404
+ const toolsUsed = /* @__PURE__ */ new Set();
20202
20405
  while (iteration < maxTurns) {
20203
20406
  iteration++;
20204
20407
  if (options.signal?.aborted) {
@@ -20207,12 +20410,15 @@ var AgentManager = class extends EventEmitter {
20207
20410
  agent.completedAt = /* @__PURE__ */ new Date();
20208
20411
  this.moveToCompleted(agent.id);
20209
20412
  options.onStatusChange?.(agent);
20210
- return {
20413
+ return this.buildResult({
20211
20414
  agent,
20212
20415
  success: false,
20213
20416
  output: "Agent execution was aborted",
20417
+ turns: iteration,
20418
+ toolsUsed: Array.from(toolsUsed),
20419
+ startedAt,
20214
20420
  usage: { inputTokens: totalInputTokens, outputTokens: totalOutputTokens }
20215
- };
20421
+ });
20216
20422
  }
20217
20423
  const response = await this.provider.chatWithTools(messages, {
20218
20424
  system: config.systemPrompt,
@@ -20229,7 +20435,7 @@ var AgentManager = class extends EventEmitter {
20229
20435
  messages.push({ role: "assistant", content: response.content });
20230
20436
  break;
20231
20437
  }
20232
- const toolResults = await this.executeToolCalls(response.toolCalls, config);
20438
+ const toolResults = await this.executeToolCalls(response.toolCalls, config, toolsUsed);
20233
20439
  const toolUses = response.toolCalls.map((tc) => ({
20234
20440
  type: "tool_use",
20235
20441
  id: tc.id,
@@ -20253,12 +20459,15 @@ var AgentManager = class extends EventEmitter {
20253
20459
  iterations: iteration,
20254
20460
  outputLength: finalOutput.length
20255
20461
  });
20256
- return {
20462
+ return this.buildResult({
20257
20463
  agent,
20258
20464
  success: true,
20259
20465
  output: finalOutput,
20466
+ turns: iteration,
20467
+ toolsUsed: Array.from(toolsUsed),
20468
+ startedAt,
20260
20469
  usage: { inputTokens: totalInputTokens, outputTokens: totalOutputTokens }
20261
- };
20470
+ });
20262
20471
  }
20263
20472
  /**
20264
20473
  * Get tool definitions filtered for the agent's allowed tools
@@ -20271,10 +20480,11 @@ var AgentManager = class extends EventEmitter {
20271
20480
  /**
20272
20481
  * Execute tool calls and return results
20273
20482
  */
20274
- async executeToolCalls(toolCalls, config) {
20483
+ async executeToolCalls(toolCalls, config, toolsUsed) {
20275
20484
  const results = [];
20276
20485
  const allowedTools = new Set(config.tools);
20277
20486
  for (const toolCall of toolCalls) {
20487
+ toolsUsed.add(toolCall.name);
20278
20488
  if (!allowedTools.has(toolCall.name)) {
20279
20489
  results.push({
20280
20490
  type: "tool_result",
@@ -20315,6 +20525,33 @@ var AgentManager = class extends EventEmitter {
20315
20525
  this.abortControllers.delete(agentId);
20316
20526
  }
20317
20527
  }
20528
+ buildResult(input) {
20529
+ const structuredResult = normalizeAgentRunResult({
20530
+ id: `${input.agent.id}-run`,
20531
+ taskId: input.agent.id,
20532
+ role: agentTypeToRuntimeRole(input.agent.type),
20533
+ success: input.success,
20534
+ output: input.output,
20535
+ turns: input.turns,
20536
+ toolsUsed: input.toolsUsed,
20537
+ usage: input.usage,
20538
+ startedAt: input.startedAt,
20539
+ durationMs: input.agent.completedAt ? input.agent.completedAt.getTime() - input.agent.createdAt.getTime() : 0,
20540
+ status: input.success ? "completed" : "failed",
20541
+ error: input.success ? void 0 : input.agent.error,
20542
+ metadata: { agentType: input.agent.type }
20543
+ });
20544
+ return {
20545
+ agent: input.agent,
20546
+ success: input.success,
20547
+ output: input.output,
20548
+ artifacts: structuredResult.artifacts,
20549
+ structuredResult,
20550
+ toolsUsed: input.toolsUsed,
20551
+ turns: input.turns,
20552
+ usage: input.usage
20553
+ };
20554
+ }
20318
20555
  /**
20319
20556
  * Emit an agent event
20320
20557
  */
@@ -20324,6 +20561,31 @@ var AgentManager = class extends EventEmitter {
20324
20561
  this.emit("agent", event);
20325
20562
  }
20326
20563
  };
20564
+ function agentTypeToRuntimeRole(type) {
20565
+ switch (type) {
20566
+ case "explore":
20567
+ return "researcher";
20568
+ case "plan":
20569
+ return "planner";
20570
+ case "test":
20571
+ case "e2e":
20572
+ case "tdd":
20573
+ return "tester";
20574
+ case "debug":
20575
+ case "refactor":
20576
+ return "coder";
20577
+ case "review":
20578
+ return "reviewer";
20579
+ case "architect":
20580
+ return "architect";
20581
+ case "security":
20582
+ return "security";
20583
+ case "docs":
20584
+ return "docs";
20585
+ case "database":
20586
+ return "database";
20587
+ }
20588
+ }
20327
20589
 
20328
20590
  // src/agents/provider-bridge.ts
20329
20591
  var agentProvider = null;
@@ -20355,6 +20617,140 @@ function getAgentManager() {
20355
20617
 
20356
20618
  // src/runtime/agent-runtime.ts
20357
20619
  init_env();
20620
+ var PUBLIC_WEB_TOOLS = /* @__PURE__ */ new Set(["search_public_docs", "list_public_services"]);
20621
+ var CUSTOMER_SUPPORT_TOOLS = /* @__PURE__ */ new Set([
20622
+ "search_public_docs",
20623
+ "knowledge_search",
20624
+ "create_support_draft",
20625
+ "request_human_escalation"
20626
+ ]);
20627
+ function createNoToolRegistry() {
20628
+ return new ToolRegistry();
20629
+ }
20630
+ function createCodingToolRegistry() {
20631
+ return createFullToolRegistry();
20632
+ }
20633
+ function createPublicWebToolRegistry(source) {
20634
+ return copyAllowedTools(PUBLIC_WEB_TOOLS, source);
20635
+ }
20636
+ function createCustomerSupportToolRegistry(source) {
20637
+ return copyAllowedTools(CUSTOMER_SUPPORT_TOOLS, source);
20638
+ }
20639
+ function createSupportRagToolRegistry(options = {}) {
20640
+ const registry = createRagToolRegistry(options.retriever);
20641
+ if (options.supportDraft) {
20642
+ registry.register(
20643
+ defineTool({
20644
+ name: "create_support_draft",
20645
+ description: "Create a support response draft from the customer message and approved retrieved sources.",
20646
+ category: "document",
20647
+ parameters: z.object({
20648
+ conversationId: z.string(),
20649
+ customerMessage: z.string(),
20650
+ retrievedSources: z.array(
20651
+ z.object({
20652
+ id: z.string(),
20653
+ title: z.string(),
20654
+ content: z.string(),
20655
+ url: z.string().optional(),
20656
+ score: z.number(),
20657
+ metadata: z.record(z.string(), z.unknown()).optional()
20658
+ })
20659
+ ).optional()
20660
+ }),
20661
+ execute: options.supportDraft
20662
+ })
20663
+ );
20664
+ }
20665
+ if (options.humanEscalation) {
20666
+ registry.register(
20667
+ defineTool({
20668
+ name: "request_human_escalation",
20669
+ description: "Prepare a human escalation request. Runtime consumers must confirmation-gate this external action.",
20670
+ category: "config",
20671
+ parameters: z.object({
20672
+ conversationId: z.string(),
20673
+ summary: z.string(),
20674
+ priority: z.enum(["low", "normal", "high", "urgent"]),
20675
+ reason: z.string()
20676
+ }),
20677
+ execute: options.humanEscalation
20678
+ })
20679
+ );
20680
+ }
20681
+ return registry;
20682
+ }
20683
+ function createSalesIntakeToolRegistry(options = {}) {
20684
+ const registry = new ToolRegistry();
20685
+ if (options.leadSummary) {
20686
+ registry.register(
20687
+ defineTool({
20688
+ name: "create_sales_lead_summary",
20689
+ description: "Create a structured lead intake summary and recommended commercial next step.",
20690
+ category: "document",
20691
+ parameters: z.object({
20692
+ conversationId: z.string(),
20693
+ company: z.string().optional(),
20694
+ contact: z.string().optional(),
20695
+ problem: z.string(),
20696
+ desiredOutcome: z.string().optional(),
20697
+ urgency: z.enum(["low", "normal", "high"]).optional(),
20698
+ budgetRange: z.string().optional(),
20699
+ currentStack: z.string().optional()
20700
+ }),
20701
+ execute: options.leadSummary
20702
+ })
20703
+ );
20704
+ }
20705
+ return registry;
20706
+ }
20707
+ function createInternalOpsToolRegistry(options = {}) {
20708
+ const registry = new ToolRegistry();
20709
+ if (options.opsDraft) {
20710
+ registry.register(
20711
+ defineTool({
20712
+ name: "create_internal_ops_draft",
20713
+ description: "Prepare an internal operations action draft. This does not execute the operation.",
20714
+ category: "document",
20715
+ parameters: z.object({
20716
+ requestId: z.string(),
20717
+ requester: z.string().optional(),
20718
+ workflow: z.string(),
20719
+ requestedAction: z.string(),
20720
+ context: z.string().optional()
20721
+ }),
20722
+ execute: options.opsDraft
20723
+ })
20724
+ );
20725
+ }
20726
+ return registry;
20727
+ }
20728
+ function createRagToolRegistry(retriever) {
20729
+ const registry = new ToolRegistry();
20730
+ if (!retriever) return registry;
20731
+ registry.register(
20732
+ defineTool({
20733
+ name: "knowledge_search",
20734
+ description: "Search the configured knowledge base and return ranked sources.",
20735
+ category: "search",
20736
+ parameters: z.object({
20737
+ query: z.string(),
20738
+ limit: z.number().optional()
20739
+ }),
20740
+ execute: async ({ query, limit }) => retriever.search(query, { limit })
20741
+ })
20742
+ );
20743
+ return registry;
20744
+ }
20745
+ function copyAllowedTools(allowed, source) {
20746
+ const registry = new ToolRegistry();
20747
+ if (!source) return registry;
20748
+ for (const name of allowed) {
20749
+ const tool = source.get(name);
20750
+ if (tool) registry.register(tool);
20751
+ }
20752
+ return registry;
20753
+ }
20358
20754
  init_errors();
20359
20755
  init_allowed_paths();
20360
20756
  function levenshtein(a, b) {
@@ -32316,7 +32712,8 @@ var DESTRUCTIVE_TOOL_NAMES = /* @__PURE__ */ new Set([
32316
32712
  "delete_file",
32317
32713
  "restore_checkpoint",
32318
32714
  "git_commit",
32319
- "git_push"
32715
+ "git_push",
32716
+ "request_human_escalation"
32320
32717
  ]);
32321
32718
  function riskForTool(tool) {
32322
32719
  if (READ_ONLY_TOOL_NAMES.has(tool.name)) return "read-only";
@@ -32543,7 +32940,32 @@ function cloneWorkflow(workflow) {
32543
32940
  steps: workflow.steps.map((step) => ({
32544
32941
  ...step,
32545
32942
  requiredTools: [...step.requiredTools]
32546
- }))
32943
+ })),
32944
+ nodes: workflow.nodes?.map((node) => ({
32945
+ ...node,
32946
+ dependsOn: node.dependsOn ? [...node.dependsOn] : void 0,
32947
+ requiredTools: node.requiredTools ? [...node.requiredTools] : void 0,
32948
+ gates: node.gates ? [...node.gates] : void 0,
32949
+ retryPolicy: node.retryPolicy ? { ...node.retryPolicy } : void 0
32950
+ })),
32951
+ edges: workflow.edges?.map((edge) => ({ ...edge })),
32952
+ gates: workflow.gates?.map((gate) => ({ ...gate })),
32953
+ retryPolicy: workflow.retryPolicy ? { ...workflow.retryPolicy } : void 0
32954
+ };
32955
+ }
32956
+ function workflowToAgentGraph(workflow) {
32957
+ const nodes = workflow.nodes ?? workflow.steps.map((step, index) => ({
32958
+ id: step.id,
32959
+ description: step.description,
32960
+ requiredTools: [...step.requiredTools],
32961
+ risk: step.risk,
32962
+ dependsOn: index > 0 ? [workflow.steps[index - 1].id] : []
32963
+ }));
32964
+ return {
32965
+ nodes,
32966
+ edges: workflow.edges,
32967
+ gates: workflow.gates,
32968
+ parallelism: workflow.parallelism
32547
32969
  };
32548
32970
  }
32549
32971
  var WorkflowCatalog = class {
@@ -32554,6 +32976,12 @@ var WorkflowCatalog = class {
32554
32976
  }
32555
32977
  }
32556
32978
  register(workflow) {
32979
+ const validation = validateAgentGraph(workflowToAgentGraph(workflow));
32980
+ if (!validation.valid) {
32981
+ throw new Error(
32982
+ `Invalid workflow graph for '${workflow.id}': ${validation.issues.map((issue) => issue.message).join("; ")}`
32983
+ );
32984
+ }
32557
32985
  this.workflows.set(workflow.id, cloneWorkflow(workflow));
32558
32986
  }
32559
32987
  get(id) {
@@ -32579,7 +33007,8 @@ var WorkflowCatalog = class {
32579
33007
  workflowId,
32580
33008
  planId: plan.id,
32581
33009
  replayable: workflow.replayable,
32582
- checks: workflow.checks
33010
+ checks: workflow.checks,
33011
+ graphLevels: validateAgentGraph(workflowToAgentGraph(workflow)).levels
32583
33012
  });
32584
33013
  return plan;
32585
33014
  }
@@ -33177,6 +33606,115 @@ async function createAgentRuntime(options) {
33177
33606
  await runtime.initialize();
33178
33607
  return runtime;
33179
33608
  }
33609
+
33610
+ // src/runtime/tool-calling-turn-runner.ts
33611
+ function runtimeWithTools(runtime) {
33612
+ if (runtime && typeof runtime === "object" && "executeTool" in runtime && typeof runtime.executeTool === "function") {
33613
+ return runtime;
33614
+ }
33615
+ throw new Error("ToolCallingRuntimeTurnRunner requires a runtime with executeTool().");
33616
+ }
33617
+ function toolResultToContent(result) {
33618
+ if (!result.success) {
33619
+ return `Error: ${result.error ?? "Tool failed."}`;
33620
+ }
33621
+ if (typeof result.output === "string") return result.output;
33622
+ return JSON.stringify(result.output ?? null);
33623
+ }
33624
+ var ToolCallingRuntimeTurnRunner = class {
33625
+ maxToolIterations;
33626
+ constructor(options = {}) {
33627
+ this.maxToolIterations = options.maxToolIterations ?? 10;
33628
+ }
33629
+ async run(input, context) {
33630
+ const runtime = runtimeWithTools(context.runtime);
33631
+ const messages = [
33632
+ ...context.session.messages,
33633
+ {
33634
+ role: "user",
33635
+ content: input.content
33636
+ }
33637
+ ];
33638
+ const tools = context.toolRegistry.getToolDefinitionsForLLM();
33639
+ const confirmedTools = new Set(input.confirmedTools ?? []);
33640
+ let inputTokens = 0;
33641
+ let outputTokens = 0;
33642
+ let lastModel = input.options?.model ?? context.provider.id;
33643
+ for (let iteration = 0; iteration < this.maxToolIterations; iteration++) {
33644
+ const response = await context.provider.chatWithTools(messages, {
33645
+ tools,
33646
+ model: input.options?.model,
33647
+ maxTokens: input.options?.maxTokens,
33648
+ temperature: input.options?.temperature,
33649
+ stopSequences: input.options?.stopSequences,
33650
+ system: context.session.instructions ?? input.options?.system,
33651
+ timeout: input.options?.timeout,
33652
+ signal: input.options?.signal,
33653
+ thinking: input.options?.thinking
33654
+ });
33655
+ inputTokens += response.usage.inputTokens;
33656
+ outputTokens += response.usage.outputTokens;
33657
+ lastModel = response.model;
33658
+ if (response.stopReason !== "tool_use" || response.toolCalls.length === 0) {
33659
+ return {
33660
+ sessionId: context.session.id,
33661
+ content: response.content,
33662
+ usage: { inputTokens, outputTokens },
33663
+ model: response.model,
33664
+ mode: context.session.mode
33665
+ };
33666
+ }
33667
+ const assistantContent = [];
33668
+ if (response.content.trim().length > 0) {
33669
+ assistantContent.push({ type: "text", text: response.content });
33670
+ }
33671
+ for (const toolCall of response.toolCalls) {
33672
+ assistantContent.push({
33673
+ type: "tool_use",
33674
+ id: toolCall.id,
33675
+ name: toolCall.name,
33676
+ input: toolCall.input,
33677
+ geminiThoughtSignature: toolCall.geminiThoughtSignature
33678
+ });
33679
+ }
33680
+ messages.push({
33681
+ role: "assistant",
33682
+ content: assistantContent
33683
+ });
33684
+ const toolResults = [];
33685
+ for (const toolCall of response.toolCalls) {
33686
+ const result = await runtime.executeTool({
33687
+ sessionId: context.session.id,
33688
+ mode: context.session.mode,
33689
+ toolName: toolCall.name,
33690
+ input: toolCall.input,
33691
+ confirmed: confirmedTools.has(toolCall.name),
33692
+ metadata: input.metadata
33693
+ });
33694
+ toolResults.push({
33695
+ type: "tool_result",
33696
+ tool_use_id: toolCall.id,
33697
+ content: toolResultToContent(result),
33698
+ is_error: !result.success
33699
+ });
33700
+ }
33701
+ messages.push({
33702
+ role: "user",
33703
+ content: toolResults
33704
+ });
33705
+ }
33706
+ return {
33707
+ sessionId: context.session.id,
33708
+ content: "The tool-calling runtime reached its maximum tool iteration budget.",
33709
+ usage: { inputTokens, outputTokens },
33710
+ model: lastModel,
33711
+ mode: context.session.mode
33712
+ };
33713
+ }
33714
+ };
33715
+ function createToolCallingRuntimeTurnRunner(options) {
33716
+ return new ToolCallingRuntimeTurnRunner(options);
33717
+ }
33180
33718
  var HttpRequestError = class extends Error {
33181
33719
  constructor(message, status) {
33182
33720
  super(message);
@@ -33288,11 +33826,543 @@ function createMcpToolPolicy(server, tool, risk, allowedModes = ["ask", "plan",
33288
33826
  };
33289
33827
  }
33290
33828
 
33829
+ // src/runtime/guardrails.ts
33830
+ var DEFAULT_REDACTION = "[REDACTED]";
33831
+ var SECRET_PATTERNS = [
33832
+ { id: "openai-api-key", pattern: /\bsk-[A-Za-z0-9_-]{20,}\b/g },
33833
+ { id: "anthropic-api-key", pattern: /\bsk-ant-[A-Za-z0-9_-]{20,}\b/g },
33834
+ { id: "github-token", pattern: /\bgh[pousr]_[A-Za-z0-9_]{20,}\b/g },
33835
+ { id: "generic-bearer-token", pattern: /\bBearer\s+[A-Za-z0-9._~+/=-]{20,}\b/gi },
33836
+ {
33837
+ id: "private-key",
33838
+ pattern: /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g
33839
+ }
33840
+ ];
33841
+ var PROMPT_INJECTION_PATTERNS = [
33842
+ {
33843
+ id: "ignore-instructions",
33844
+ pattern: /\b(ignore|forget|override)\b.{0,40}\b(instructions|system|developer)\b/i
33845
+ },
33846
+ {
33847
+ id: "reveal-prompt",
33848
+ pattern: /\b(reveal|print|show|dump)\b.{0,40}\b(system prompt|instructions|developer message)\b/i
33849
+ },
33850
+ {
33851
+ id: "tool-exfiltration",
33852
+ pattern: /\b(use|call|run)\b.{0,40}\b(tool|shell|filesystem|git)\b.{0,40}\b(secret|token|key)\b/i
33853
+ }
33854
+ ];
33855
+ var defaultPublicGuardrails = {
33856
+ maxInputChars: 4e3,
33857
+ maxOutputChars: 6e3,
33858
+ secretRedaction: { enabled: true },
33859
+ promptInjectionDetection: true
33860
+ };
33861
+ function redactSecrets(content, config = { enabled: true }) {
33862
+ if (!config.enabled) return { content, findings: [] };
33863
+ let redacted = content;
33864
+ const findings = [];
33865
+ const replacement = config.replacement ?? DEFAULT_REDACTION;
33866
+ for (const { id, pattern } of SECRET_PATTERNS) {
33867
+ const before = redacted;
33868
+ redacted = redacted.replace(pattern, replacement);
33869
+ if (before !== redacted) {
33870
+ findings.push({
33871
+ id,
33872
+ stage: "input",
33873
+ severity: "warning",
33874
+ message: `Potential secret redacted: ${id}`,
33875
+ redacted: true
33876
+ });
33877
+ }
33878
+ }
33879
+ return { content: redacted, findings };
33880
+ }
33881
+ function runGuardrails(stage, content, config = {}) {
33882
+ const findings = [];
33883
+ const maxChars = stage === "input" ? config.maxInputChars : config.maxOutputChars;
33884
+ let checked = content;
33885
+ if (typeof maxChars === "number" && checked.length > maxChars) {
33886
+ findings.push({
33887
+ id: `${stage}-too-long`,
33888
+ stage,
33889
+ severity: "blocked",
33890
+ message: `${stage} exceeds ${maxChars} characters.`
33891
+ });
33892
+ }
33893
+ const redaction = redactSecrets(checked, config.secretRedaction);
33894
+ checked = redaction.content;
33895
+ findings.push(...redaction.findings.map((finding) => ({ ...finding, stage })));
33896
+ if (config.promptInjectionDetection) {
33897
+ for (const { id, pattern } of PROMPT_INJECTION_PATTERNS) {
33898
+ if (pattern.test(checked)) {
33899
+ findings.push({
33900
+ id,
33901
+ stage,
33902
+ severity: "warning",
33903
+ message: `Potential prompt-injection pattern detected: ${id}`
33904
+ });
33905
+ }
33906
+ }
33907
+ }
33908
+ const blockedTopics = config.topicBoundary?.blockedTopics ?? [];
33909
+ for (const topic of blockedTopics) {
33910
+ if (topic && checked.toLowerCase().includes(topic.toLowerCase())) {
33911
+ findings.push({
33912
+ id: "blocked-topic",
33913
+ stage,
33914
+ severity: "blocked",
33915
+ message: `Content mentions blocked topic: ${topic}`
33916
+ });
33917
+ }
33918
+ }
33919
+ return {
33920
+ allowed: !findings.some((finding) => finding.severity === "blocked"),
33921
+ content: checked,
33922
+ findings
33923
+ };
33924
+ }
33925
+ function validateStructuredOutput(output, schema) {
33926
+ if (!schema) return [];
33927
+ const result = schema.safeParse(output);
33928
+ if (result.success) return [];
33929
+ return [
33930
+ {
33931
+ id: "invalid-structured-output",
33932
+ stage: "output",
33933
+ severity: "blocked",
33934
+ message: result.error.issues.map((issue) => issue.message).join("; ")
33935
+ }
33936
+ ];
33937
+ }
33938
+
33939
+ // src/runtime/blueprints.ts
33940
+ function mapActionModeToRuntimeMode(mode) {
33941
+ if (mode === "act") return "build";
33942
+ if (mode === "review") return "review";
33943
+ return "ask";
33944
+ }
33945
+ function createSafeToolRegistry(allowedTools, source) {
33946
+ const safe = new ToolRegistry();
33947
+ if (!source) return safe;
33948
+ for (const toolName of allowedTools) {
33949
+ const tool = source.get(toolName);
33950
+ if (tool) safe.register(tool);
33951
+ }
33952
+ return safe;
33953
+ }
33954
+ async function createAgentFromBlueprint(blueprint, options) {
33955
+ const runtime = await createAgentRuntime({
33956
+ providerType: options.providerType,
33957
+ model: options.model,
33958
+ providerConfig: options.providerConfig,
33959
+ provider: options.provider,
33960
+ eventLog: options.eventLog,
33961
+ turnRunner: options.turnRunner,
33962
+ toolRegistry: options.toolRegistry ?? createSafeToolRegistry(blueprint.allowedTools.length > 0 ? blueprint.allowedTools : []),
33963
+ publishToGlobalBridge: false
33964
+ });
33965
+ return {
33966
+ blueprint,
33967
+ runtime,
33968
+ createSession(metadata = {}) {
33969
+ return runtime.createSession({
33970
+ mode: mapActionModeToRuntimeMode(blueprint.defaultMode),
33971
+ instructions: blueprint.instructions,
33972
+ metadata: {
33973
+ blueprintId: blueprint.id,
33974
+ surface: blueprint.surface,
33975
+ ...metadata
33976
+ }
33977
+ });
33978
+ },
33979
+ async runTurn(input) {
33980
+ const guardrails = { ...defaultPublicGuardrails, ...blueprint.guardrails };
33981
+ const checkedInput = runGuardrails("input", input.content, guardrails);
33982
+ runtime.eventLog.record("guardrail.input", {
33983
+ blueprintId: blueprint.id,
33984
+ allowed: checkedInput.allowed,
33985
+ findings: checkedInput.findings
33986
+ });
33987
+ if (!checkedInput.allowed) {
33988
+ throw new Error(formatGuardrailBlock(checkedInput.findings));
33989
+ }
33990
+ const result = await runtime.runTurn({
33991
+ ...input,
33992
+ content: checkedInput.content,
33993
+ mode: input.mode ?? mapActionModeToRuntimeMode(blueprint.defaultMode)
33994
+ });
33995
+ const checkedOutput = runGuardrails("output", result.content, guardrails);
33996
+ runtime.eventLog.record("guardrail.output", {
33997
+ blueprintId: blueprint.id,
33998
+ allowed: checkedOutput.allowed,
33999
+ findings: checkedOutput.findings
34000
+ });
34001
+ if (!checkedOutput.allowed) {
34002
+ throw new Error(formatGuardrailBlock(checkedOutput.findings));
34003
+ }
34004
+ return { ...result, content: checkedOutput.content };
34005
+ }
34006
+ };
34007
+ }
34008
+ function formatGuardrailBlock(findings) {
34009
+ const messages = findings.filter((finding) => finding.severity === "blocked").map((finding) => finding.message);
34010
+ return messages.length > 0 ? messages.join("; ") : "Guardrail blocked the request.";
34011
+ }
34012
+ function createBaseBlueprint(input) {
34013
+ return {
34014
+ ...input,
34015
+ guardrails: input.guardrails ?? defaultPublicGuardrails,
34016
+ memory: input.memory ?? { enabled: true, retention: "session" },
34017
+ approval: input.approval ?? { requireHumanForExternalActions: true },
34018
+ observability: input.observability ?? { logEvents: true, redactSensitiveData: true }
34019
+ };
34020
+ }
34021
+
34022
+ // src/runtime/rag.ts
34023
+ var InMemoryKnowledgeRetriever = class {
34024
+ constructor(documents) {
34025
+ this.documents = documents;
34026
+ }
34027
+ documents;
34028
+ async search(query, options = {}) {
34029
+ const terms = tokenize(query);
34030
+ const limit = options.limit ?? 5;
34031
+ const minScore = options.minScore ?? 0;
34032
+ return this.documents.map((document) => ({
34033
+ ...document,
34034
+ score: scoreDocument(document, terms)
34035
+ })).filter((source) => source.score >= minScore && source.score > 0).sort((a, b) => b.score - a.score).slice(0, limit);
34036
+ }
34037
+ };
34038
+ function createInMemoryKnowledgeRetriever(documents) {
34039
+ return new InMemoryKnowledgeRetriever(documents);
34040
+ }
34041
+ function formatRetrievedSourcesForPrompt(sources) {
34042
+ if (sources.length === 0) return "No retrieved sources.";
34043
+ return sources.map((source, index) => {
34044
+ const url = source.url ? `
34045
+ URL: ${source.url}` : "";
34046
+ return `[${index + 1}] ${source.title}${url}
34047
+ ${source.content}`;
34048
+ }).join("\n\n");
34049
+ }
34050
+ function tokenize(text2) {
34051
+ return text2.toLowerCase().split(/[^a-z0-9áéíóúüñ]+/i).map((term) => term.trim()).filter((term) => term.length > 2);
34052
+ }
34053
+ function scoreDocument(document, terms) {
34054
+ const haystack = `${document.title}
34055
+ ${document.content}`.toLowerCase();
34056
+ if (terms.length === 0) return 0;
34057
+ const matches = terms.filter((term) => haystack.includes(term)).length;
34058
+ return matches / terms.length;
34059
+ }
34060
+
34061
+ // src/presets/index.ts
34062
+ var publicWebsiteAssistantPreset = {
34063
+ id: "public-website-assistant",
34064
+ name: "Public Website Assistant",
34065
+ createBlueprint(config) {
34066
+ return createBaseBlueprint({
34067
+ id: "public-website-assistant",
34068
+ name: "Public Website Assistant",
34069
+ description: "Safe public assistant for landing pages, FAQs, service explanation, and lead intake.",
34070
+ surface: "web",
34071
+ defaultMode: "ask",
34072
+ maturity: "experimental",
34073
+ instructions: [
34074
+ `You are the public website assistant for ${config.brand}.`,
34075
+ "Help visitors understand services, ask concise qualification questions, and suggest a safe next step.",
34076
+ "Do not claim that you sent messages, changed systems, booked meetings, or created records unless a registered tool result proves it.",
34077
+ "If you are unsure, say so and offer to route the visitor to a human.",
34078
+ config.audience ? `Primary audience: ${config.audience}.` : "",
34079
+ config.extraInstructions ?? ""
34080
+ ].filter(Boolean).join("\n"),
34081
+ allowedTools: []
34082
+ });
34083
+ },
34084
+ async createRuntime(config) {
34085
+ return createPresetRuntime(config, publicWebsiteAssistantPreset.createBlueprint(config));
34086
+ }
34087
+ };
34088
+ var ragKnowledgeAssistantPreset = {
34089
+ id: "rag-knowledge-assistant",
34090
+ name: "RAG Knowledge Assistant",
34091
+ createBlueprint(config) {
34092
+ return createBaseBlueprint({
34093
+ id: "rag-knowledge-assistant",
34094
+ name: "RAG Knowledge Assistant",
34095
+ description: "Assistant that answers from a configured knowledge base and cites retrieved sources.",
34096
+ surface: "web",
34097
+ defaultMode: "ask",
34098
+ maturity: "experimental",
34099
+ instructions: [
34100
+ `You are a knowledge assistant for ${config.brand}.`,
34101
+ "Answer only from retrieved or approved knowledge.",
34102
+ "Cite source titles when using retrieved content.",
34103
+ "If the answer is not in the available knowledge, say you do not know and suggest escalation.",
34104
+ config.extraInstructions ?? ""
34105
+ ].filter(Boolean).join("\n"),
34106
+ allowedTools: config.retriever ? ["knowledge_search"] : []
34107
+ });
34108
+ },
34109
+ async createRuntime(config) {
34110
+ const blueprint = ragKnowledgeAssistantPreset.createBlueprint(config);
34111
+ return createPresetRuntime(config, blueprint, createRagToolRegistry(config.retriever));
34112
+ }
34113
+ };
34114
+ var supportRagAssistantPreset = {
34115
+ id: "support-rag-assistant",
34116
+ name: "Support RAG Assistant",
34117
+ createBlueprint(config) {
34118
+ const allowedTools = [];
34119
+ if (config.retriever) allowedTools.push("knowledge_search");
34120
+ if (config.supportDraft) allowedTools.push("create_support_draft");
34121
+ if (config.humanEscalation) allowedTools.push("request_human_escalation");
34122
+ return createBaseBlueprint({
34123
+ id: "support-rag-assistant",
34124
+ name: "Support RAG Assistant",
34125
+ description: "Support assistant that answers from approved knowledge, drafts responses, and escalates uncertain cases.",
34126
+ surface: "web",
34127
+ defaultMode: "draft",
34128
+ maturity: "experimental",
34129
+ instructions: [
34130
+ `You are a support assistant for ${config.brand}.`,
34131
+ "Answer only from approved retrieved knowledge.",
34132
+ "Cite source titles when using retrieved content.",
34133
+ "If retrieval is weak or the case is sensitive, say you are unsure and prepare an escalation.",
34134
+ "Never claim a ticket was created, closed, or escalated unless a registered tool result proves it.",
34135
+ config.extraInstructions ?? ""
34136
+ ].filter(Boolean).join("\n"),
34137
+ allowedTools,
34138
+ approval: { requireHumanForExternalActions: true, requireHumanForSensitiveData: true }
34139
+ });
34140
+ },
34141
+ async createRuntime(config) {
34142
+ const blueprint = supportRagAssistantPreset.createBlueprint(config);
34143
+ return createPresetRuntime(
34144
+ config,
34145
+ blueprint,
34146
+ createSupportRagToolRegistry({
34147
+ retriever: config.retriever,
34148
+ supportDraft: config.supportDraft,
34149
+ humanEscalation: config.humanEscalation
34150
+ }),
34151
+ createToolCallingRuntimeTurnRunner()
34152
+ );
34153
+ }
34154
+ };
34155
+ var salesIntakeAssistantPreset = {
34156
+ id: "sales-intake-assistant",
34157
+ name: "Sales Intake Assistant",
34158
+ createBlueprint(config) {
34159
+ return createBaseBlueprint({
34160
+ id: "sales-intake-assistant",
34161
+ name: "Sales Intake Assistant",
34162
+ description: "Assistant for lead qualification, project context, urgency, budget, and next step capture.",
34163
+ surface: "web",
34164
+ defaultMode: "ask",
34165
+ maturity: "experimental",
34166
+ instructions: [
34167
+ `You are the sales intake assistant for ${config.brand}.`,
34168
+ "Collect problem, desired outcome, urgency, approximate budget, current stack, decision process, and contact preference.",
34169
+ "Keep the conversation concise and useful. Produce a clear summary and recommended next step when enough context is available.",
34170
+ "Do not promise pricing, timelines, or delivery commitments.",
34171
+ "Use create_sales_lead_summary only to prepare an internal summary; do not claim a CRM record was created.",
34172
+ config.extraInstructions ?? ""
34173
+ ].filter(Boolean).join("\n"),
34174
+ allowedTools: config.leadSummary ? ["create_sales_lead_summary"] : []
34175
+ });
34176
+ },
34177
+ async createRuntime(config) {
34178
+ return createPresetRuntime(
34179
+ config,
34180
+ salesIntakeAssistantPreset.createBlueprint(config),
34181
+ createSalesIntakeToolRegistry({ leadSummary: config.leadSummary }),
34182
+ createToolCallingRuntimeTurnRunner()
34183
+ );
34184
+ }
34185
+ };
34186
+ var customerSupportAssistantPreset = {
34187
+ id: "customer-support-assistant",
34188
+ name: "Customer Support Assistant",
34189
+ createBlueprint(config) {
34190
+ return createBaseBlueprint({
34191
+ id: "customer-support-assistant",
34192
+ name: "Customer Support Assistant",
34193
+ description: "Assistant for support triage, answer drafts, and escalation recommendations.",
34194
+ surface: "web",
34195
+ defaultMode: "draft",
34196
+ maturity: "experimental",
34197
+ instructions: [
34198
+ `You are the customer support assistant for ${config.brand}.`,
34199
+ "Classify the issue, suggest a helpful answer, and escalate sensitive or uncertain cases to a human.",
34200
+ "Do not close tickets or make account changes without explicit approval and a registered tool result.",
34201
+ config.extraInstructions ?? ""
34202
+ ].filter(Boolean).join("\n"),
34203
+ allowedTools: []
34204
+ });
34205
+ },
34206
+ async createRuntime(config) {
34207
+ return createPresetRuntime(
34208
+ config,
34209
+ customerSupportAssistantPreset.createBlueprint(config),
34210
+ createCustomerSupportToolRegistry(config.toolRegistry)
34211
+ );
34212
+ }
34213
+ };
34214
+ var appointmentBookingAssistantPreset = {
34215
+ id: "appointment-booking-assistant",
34216
+ name: "Appointment Booking Assistant",
34217
+ createBlueprint(config) {
34218
+ return createBaseBlueprint({
34219
+ id: "appointment-booking-assistant",
34220
+ name: "Appointment Booking Assistant",
34221
+ description: "Assistant for appointment intake, availability discussion, and confirmation-gated booking.",
34222
+ surface: "web",
34223
+ defaultMode: "draft",
34224
+ maturity: "experimental",
34225
+ instructions: [
34226
+ `You are the appointment assistant for ${config.brand}.`,
34227
+ config.businessHours ? `Business hours: ${config.businessHours}.` : "",
34228
+ "Collect preferred time, timezone, purpose, and contact details.",
34229
+ "Never book, cancel, or move an appointment without explicit user confirmation and an approved tool call.",
34230
+ config.extraInstructions ?? ""
34231
+ ].filter(Boolean).join("\n"),
34232
+ allowedTools: []
34233
+ });
34234
+ },
34235
+ async createRuntime(config) {
34236
+ return createPresetRuntime(config, appointmentBookingAssistantPreset.createBlueprint(config));
34237
+ }
34238
+ };
34239
+ var internalOpsAssistantPreset = {
34240
+ id: "internal-ops-assistant",
34241
+ name: "Internal Ops Assistant",
34242
+ createBlueprint(config) {
34243
+ return createBaseBlueprint({
34244
+ id: "internal-ops-assistant",
34245
+ name: "Internal Ops Assistant",
34246
+ description: "Internal automation assistant for controlled operations workflows.",
34247
+ surface: "internal",
34248
+ defaultMode: "draft",
34249
+ maturity: "experimental",
34250
+ instructions: [
34251
+ `You are an internal operations assistant for ${config.brand}.`,
34252
+ "Prefer drafts and summaries before actions. Ask for confirmation before external side effects.",
34253
+ "Use create_internal_ops_draft for controlled planning only. Do not execute ERP, CRM, billing, or account changes unless a separate allowlisted tool exists.",
34254
+ "Follow the configured tool policy and record decisions for audit.",
34255
+ config.extraInstructions ?? ""
34256
+ ].filter(Boolean).join("\n"),
34257
+ allowedTools: config.opsDraft ? ["create_internal_ops_draft"] : [],
34258
+ approval: { requireHumanForExternalActions: true, requireHumanForSensitiveData: true }
34259
+ });
34260
+ },
34261
+ async createRuntime(config) {
34262
+ return createPresetRuntime(
34263
+ config,
34264
+ internalOpsAssistantPreset.createBlueprint(config),
34265
+ createInternalOpsToolRegistry({ opsDraft: config.opsDraft }),
34266
+ createToolCallingRuntimeTurnRunner()
34267
+ );
34268
+ }
34269
+ };
34270
+ var codingAgentPreset = {
34271
+ id: "coding-agent",
34272
+ name: "Coco Coding Agent",
34273
+ createBlueprint(config) {
34274
+ return createBaseBlueprint({
34275
+ id: "coding-agent",
34276
+ name: "Coco Coding Agent",
34277
+ description: "Coco's full coding-agent surface for trusted developer environments.",
34278
+ surface: "cli",
34279
+ defaultMode: "act",
34280
+ maturity: "beta",
34281
+ instructions: config.extraInstructions ?? "You are Coco, a coding agent for trusted repositories.",
34282
+ allowedTools: [],
34283
+ guardrails: { secretRedaction: { enabled: true }, promptInjectionDetection: true },
34284
+ approval: { requireHumanForExternalActions: true, requireHumanForSensitiveData: true }
34285
+ });
34286
+ },
34287
+ async createRuntime(config) {
34288
+ return createPresetRuntime(
34289
+ config,
34290
+ codingAgentPreset.createBlueprint(config),
34291
+ createCodingToolRegistry()
34292
+ );
34293
+ }
34294
+ };
34295
+ async function createPresetRuntime(config, blueprint, fallbackToolRegistry = createNoToolRegistry(), fallbackTurnRunner = config.turnRunner) {
34296
+ return createAgentRuntime({
34297
+ providerType: config.providerType,
34298
+ model: config.model,
34299
+ providerConfig: config.providerConfig,
34300
+ provider: config.provider,
34301
+ eventLog: config.eventLog,
34302
+ turnRunner: config.turnRunner ?? fallbackTurnRunner,
34303
+ toolRegistry: blueprint.id === "coding-agent" ? config.toolRegistry ?? fallbackToolRegistry : config.toolRegistry ? createSafeToolRegistry(blueprint.allowedTools, config.toolRegistry) : fallbackToolRegistry,
34304
+ publishToGlobalBridge: false
34305
+ });
34306
+ }
34307
+ var AGENT_PRESETS = [
34308
+ publicWebsiteAssistantPreset,
34309
+ ragKnowledgeAssistantPreset,
34310
+ supportRagAssistantPreset,
34311
+ salesIntakeAssistantPreset,
34312
+ customerSupportAssistantPreset,
34313
+ appointmentBookingAssistantPreset,
34314
+ internalOpsAssistantPreset,
34315
+ codingAgentPreset
34316
+ ];
34317
+
34318
+ // src/adapters/index.ts
34319
+ function createHttpAssistantAdapter(runtime) {
34320
+ return {
34321
+ createSession(metadata = {}) {
34322
+ const session = runtime.createSession({ mode: "ask", metadata });
34323
+ return { sessionId: session.id };
34324
+ },
34325
+ async handleMessage(input) {
34326
+ const sessionId = input.sessionId ?? runtime.createSession({ mode: "ask", metadata: input.metadata }).id;
34327
+ const result = await runtime.runTurn({
34328
+ sessionId,
34329
+ content: input.content,
34330
+ metadata: input.metadata
34331
+ });
34332
+ return { sessionId, content: result.content, metadata: { model: result.model } };
34333
+ }
34334
+ };
34335
+ }
34336
+ function createStreamingHttpAssistantAdapter(runtime) {
34337
+ const base = createHttpAssistantAdapter(runtime);
34338
+ return {
34339
+ ...base,
34340
+ async *streamMessage(input) {
34341
+ const sessionId = input.sessionId ?? runtime.createSession({ mode: "ask", metadata: input.metadata }).id;
34342
+ yield* runtime.streamTurn({
34343
+ sessionId,
34344
+ content: input.content,
34345
+ metadata: input.metadata
34346
+ });
34347
+ }
34348
+ };
34349
+ }
34350
+ function createWebhookAssistantAdapter(runtime, options = {}) {
34351
+ return {
34352
+ id: options.id ?? "webhook-assistant",
34353
+ surface: options.surface ?? "api",
34354
+ async handle(input) {
34355
+ const adapter = createHttpAssistantAdapter(runtime);
34356
+ return adapter.handleMessage(input);
34357
+ }
34358
+ };
34359
+ }
34360
+
33291
34361
  // src/index.ts
33292
34362
  init_errors();
33293
34363
  init_logger();
33294
34364
  init_proxy();
33295
34365
 
33296
- export { ADRGenerator, AGENT_MODES, AgentRuntime, AnthropicProvider, ArchitectureGenerator, BacklogGenerator, CICDGenerator, CocoError, CodeGenerator, CodeReviewer, CompleteExecutor, ConfigError, ConvergeExecutor, DEFAULT_WORKFLOWS, DefaultPermissionPolicy, DefaultRuntimeTurnRunner, DiscoveryEngine, DockerGenerator, DocsGenerator, FileEventLog, FileRuntimeSessionStore, InMemoryEventLog, InMemoryRuntimeSessionStore, OrchestrateExecutor, OutputExecutor, PhaseError, ProviderRegistry, SessionManager, SpecificationGenerator, TaskError, TaskIterator, ToolRegistry, VERSION, WorkflowCatalog, WorkflowEngine, WorkflowRegistry, configExists, createADRGenerator, createAgentRuntime, createAnthropicProvider, createArchitectureGenerator, createBacklogGenerator, createCICDGenerator, createCodeGenerator, createCodeReviewer, createCompleteExecutor, createConvergeExecutor, createDefaultConfig, createDefaultRuntimeTurnRunner, createDiscoveryEngine, createDockerGenerator, createDocsGenerator, createEventLog, createFileEventLog, createFileRuntimeSessionStore, createFullToolRegistry, createLogger, createMcpToolPolicy, createOrchestrateExecutor, createOrchestrator, createOutputExecutor, createPermissionPolicy, createProvider, createProviderRegistry, createRuntimeHttpServer, createRuntimeSessionStore, createSessionManager, createSpecificationGenerator, createTaskIterator, createToolRegistry, createWorkflowCatalog, createWorkflowEngine, createWorkflowRegistry, getAgentMode, installProxyDispatcher, isAgentMode, listAgentModes, loadConfig, registerAllTools, saveConfig };
34366
+ export { ADRGenerator, AGENT_MODES, AGENT_PRESETS, AgentRuntime, AnthropicProvider, ArchitectureGenerator, BacklogGenerator, CICDGenerator, CocoError, CodeGenerator, CodeReviewer, CompleteExecutor, ConfigError, ConvergeExecutor, DEFAULT_WORKFLOWS, DefaultPermissionPolicy, DefaultRuntimeTurnRunner, DiscoveryEngine, DockerGenerator, DocsGenerator, FileEventLog, FileRuntimeSessionStore, InMemoryEventLog, InMemoryKnowledgeRetriever, InMemoryRuntimeSessionStore, OrchestrateExecutor, OutputExecutor, PhaseError, ProviderRegistry, SessionManager, SharedWorkspaceState, SpecificationGenerator, TaskError, TaskIterator, ToolCallingRuntimeTurnRunner, ToolRegistry, VERSION, WorkflowCatalog, WorkflowEngine, WorkflowRegistry, appointmentBookingAssistantPreset, codingAgentPreset, configExists, createADRGenerator, createAgentArtifact, createAgentFromBlueprint, createAgentRuntime, createAnthropicProvider, createArchitectureGenerator, createBacklogGenerator, createBaseBlueprint, createCICDGenerator, createCodeGenerator, createCodeReviewer, createCodingToolRegistry, createCompleteExecutor, createConvergeExecutor, createCustomerSupportToolRegistry, createDefaultConfig, createDefaultRuntimeTurnRunner, createDiscoveryEngine, createDockerGenerator, createDocsGenerator, createEventLog, createFileEventLog, createFileRuntimeSessionStore, createFullToolRegistry, createHttpAssistantAdapter, createInMemoryKnowledgeRetriever, createLogger, createMcpToolPolicy, createNoToolRegistry, createOrchestrateExecutor, createOrchestrator, createOutputExecutor, createPermissionPolicy, createProvider, createProviderRegistry, createPublicWebToolRegistry, createRagToolRegistry, createRuntimeHttpServer, createRuntimeSessionStore, createSafeToolRegistry, createSessionManager, createSpecificationGenerator, createStreamingHttpAssistantAdapter, createSummaryArtifact, createSupportRagToolRegistry, createTaskIterator, createToolCallingRuntimeTurnRunner, createToolRegistry, createWebhookAssistantAdapter, createWorkflowCatalog, createWorkflowEngine, createWorkflowRegistry, customerSupportAssistantPreset, defaultPublicGuardrails, formatRetrievedSourcesForPrompt, getAgentMode, installProxyDispatcher, internalOpsAssistantPreset, isAgentMode, listAgentModes, loadConfig, mapActionModeToRuntimeMode, normalizeAgentRunResult, publicWebsiteAssistantPreset, ragKnowledgeAssistantPreset, redactSecrets, registerAllTools, runGuardrails, salesIntakeAssistantPreset, saveConfig, supportRagAssistantPreset, validateAgentCapabilities, validateAgentGraph, validateStructuredOutput, workflowToAgentGraph };
33297
34367
  //# sourceMappingURL=index.js.map
33298
34368
  //# sourceMappingURL=index.js.map