Agents

TypeScript / JavaScript Memory + Consequence

This example builds a release-support agent. It remembers safe operational history, uses the AI Engineering Delivery industry pack, compares release options, records the selected scenario, waits for approval when required, and later creates a reviewable lesson from observed results.

The SDK works from TypeScript and JavaScript. This implementation uses TypeScript for typed consequence inputs; JavaScript uses the same package and method calls without type annotations.

1. Install industry knowledge

Use a workspace API key for installation. Built-in catalog packs require an active Enterprise workspace.

import { NeutronAIClient } from "@neutron-ai/sdk";

const workspaceClient = new NeutronAIClient({
  baseUrl: process.env.NEUTRON_API_URL!,
  token: process.env.NEUTRON_WORKSPACE_API_KEY!
});

await workspaceClient.installIndustryLibraryPlugin("ai-engineering-delivery", {
  nucleusId: "checkout-platform"
});

The installed skill and knowledge base live in industry:ai-engineering-delivery. Custom team runbooks can be uploaded as workspace-owned knowledge-base assets and installed into the same Nucleus.

2. Record safe historical actions

Use a Nucleus access token for the agent's normal memory operations. Store a compact reviewed outcome, not full logs or private reasoning.

const client = new NeutronAIClient({
  baseUrl: process.env.NEUTRON_API_URL!,
  token: process.env.NEUTRON_API_TOKEN!,
  nucleusId: "checkout-platform"
});

await client.remember({
  scopeId: "history:checkout-releases",
  agentId: "agent:release-manager",
  type: "experience",
  privacyClass: "tenant",
  text: [
    "Release 3.7 used a 5% cohort for 20 minutes before expansion.",
    "The rollout was paused after database lock time exceeded the 250 ms policy threshold.",
    "Rollback restored the previous version successfully.",
    "For similar schema changes, verify lock duration before expanding beyond the pilot cohort."
  ].join(" "),
  metadata: {
    source: "approved-release-review",
    release: "3.7",
    outcome: "rolled-back"
  }
});

Use stable scopes for durable subject areas. Do not create one global history scope that allows unrelated agents to retrieve everything.

3. Give the agent bounded working context

const context = await client.agentContext({
  scopeIds: [
    "industry:ai-engineering-delivery",
    "service:checkout-api",
    "history:checkout-releases",
    "policy:production-change"
  ],
  agentId: "agent:release-manager",
  task: "Prepare a safe release recommendation for checkout API version 3.8.",
  privacyClasses: ["tenant"],
  tokenBudget: 1_600,
  cachePolicy: {
    mode: "prefer_cache",
    keyMode: "intent_profile",
    ttlSeconds: 300,
    includeDynamicRag: true
  }
});

The application passes context.promptContext to its chosen model as supporting context. The current task and current deployment evidence remain primary.

4. Compare bounded consequences

const run = await client.consequencePlan({
  scopeIds: [
    "industry:ai-engineering-delivery",
    "service:checkout-api",
    "history:checkout-releases",
    "policy:production-change"
  ],
  agentId: "agent:release-manager",
  task: [
    "Compare delaying release 3.8, running a 1% pilot, running a 5% staged rollout,",
    "or releasing immediately. Preserve API compatibility and the database lock budget."
  ].join(" "),
  domain: "engineering_ops",
  objectiveHints: [
    "Reduce customer impact",
    "Preserve rollback capability",
    "Collect enough evidence before expansion"
  ],
  constraintHints: [
    "Database lock time must remain below the approved threshold",
    "Production expansion requires the accountable release owner",
    "Rollback must remain available throughout the staged rollout"
  ],
  idempotencyKey: "checkout-3.8-release-review-v1",
  retentionDays: 90,
  contextPolicy: {
    includeMemory: true,
    includeKnowledge: true,
    includeContextCapsules: true,
    includePastDecisions: true,
    includeReflections: true
  },
  policy: {
    mode: "deep",
    depth: 10,
    maxScenarios: 8,
    maxRuntimeMs: 8_000,
    requireApprovalAboveRisk: "medium",
    allowExecution: false,
    storeSafeArtifactsOnly: true,
    includeCounterfactuals: true,
    includeReflections: true
  }
});

Inspect run.scenarios, run.counterfactuals, run.warnings, run.riskEnvelope, and run.trace. Do not select a scenario when required data is missing or a hard constraint is violated or unknown.

5. Record the selected decision

The application or accountable user chooses a scenario. Do not let the agent equate recommendedScenarioId with authorization.

if (!run.recommendedScenarioId) {
  throw new Error("No scenario satisfied the current decision boundary");
}

const decided = await client.consequenceDecide({
  runId: run.runId,
  scopeIds: ["service:checkout-api", "policy:production-change"],
  selectedScenarioId: run.recommendedScenarioId,
  decisionSummary: "Selected the bounded pilot scenario for owner review.",
  rationaleSummary: [
    "The pilot preserves rollback capability and gathers current lock-duration evidence.",
    "Expansion remains conditional on the approved threshold and owner review."
  ].join(" ")
});

const decision = decided.decisionRecord;
if (!decision) {
  throw new Error("The decision record was not created");
}

If decision.status is draft, stop. An authorized human or the application’s existing approval workflow must call consequenceApprove. The same agent must not approve its own high-risk recommendation.

await approverClient.consequenceApprove({
  decisionId: decision.decisionId,
  scopeIds: ["service:checkout-api", "policy:production-change"],
  note: "Release owner approved the pilot only; expansion requires a second review."
});

approverClient represents a server-side client acting for the authenticated human approver. Construct it only after your application has verified the approver’s identity, role, decision scope, and current intent.

Approval records authorization; it does not execute the release. Keep allowExecution: false when the agent is providing decision support only.

6. Record what actually happened

After the application performs its separately authorized action, attach bounded evidence:

const observed = await client.consequenceObserve({
  decisionId: decision.decisionId,
  scopeIds: ["service:checkout-api", "history:checkout-releases"],
  summary: "The 1% pilot completed without customer errors and was held for review.",
  observedMetrics: {
    pilot_percent: 1,
    pilot_minutes: 30,
    database_lock_p95_ms: 180,
    customer_error_rate: 0
  },
  unexpectedConsequences: [
    "Cache warm-up took ten minutes longer than the original estimate."
  ],
  sourceRefs: [
    "release-run:checkout-3.8-pilot",
    "dashboard:database-locks-2026-08-15"
  ]
});

Do not use model-generated observations. Derive them from trusted operational, transactional, or reviewed human evidence.

7. Create and review the lesson

Reflection compares recorded predictions with observations and creates a structured lesson candidate:

const reflected = await internalClient.consequenceReflect({
  decisionId: decision.decisionId,
  scopeIds: ["service:checkout-api", "history:checkout-releases"]
});

const lesson = reflected.reflectionLessons.at(-1);

internalClient represents a server-side client with developer or global API authority; reflection writes are intentionally unavailable to lower-authority agent credentials. Review lesson.predictedVsObservedDelta, lesson.regretScore, lesson.confidenceAdjustment, lesson.futurePolicySuggestion, and lesson.memoryWritePolicy before promoting anything into durable memory.

The next release run can retrieve this prior decision and reviewed reflection through the same scopes. It should use the lesson to adjust evidence requirements, not blindly repeat the old action.

Production checklist

  • Keep workspace installation, agent recall, human approval, internal reflection, and external execution credentials separate.
  • Use idempotency keys for retried plan requests and action adapters.
  • Keep depth, runtime, nodes, branches, model calls, scenarios, and cost bounded.
  • Require specialist solvers and current source evidence for safety-critical calculations.
  • Audit every decision, approval, observation, reflection, deletion, and external action.
  • Tombstone lifecycle data when its user, scope, or retention boundary requires deletion.