iterate.com / stdlib

git clone https://git.iterate.com/repos/stdlib

stdlib / agent-kinds / agent.tsmain at 41005ca

// agent-kinds/agent.ts — THE MIND'S SIDE OF THE AGENT: every-event.ts calls `agentKindEvent` with
// every event of the mind. The agent's own code is the facets of agent/, which agent-start.ts
// enables on each agent's context.
//
// EVERY AGENT OF THE MIND IS THIS AGENT. A person's new chat in the Dash is one: the Dash's New
// agent appends `agent-ui/agent-requested` and then the person's first words to
// `/agents/people/<person>/agent/<moment>`, as that member. Every other agent is one that
// `itx.agents.create(path)` started (agents.ts, agent-start.ts).
//
// The agent has one input, `agent/context-added`, and knows no channel. This file acts on these
// facts, each in ONE append to a context:
//
//   agent-ui/message-received   the Dash's composer                         → "— Web UI: …"
//   agent/message-received      the platform's `itx.agents.get(path).message()`: a tool, a page
//                               that stores no files                        → "— Agents API: …"
//       on the context of an agent: its start facts (all keyed: written once) and the transcribed
//       input (agent-ui.ts), under a key that names the raw fact;
//   agent-ui/agent-requested    the start facts alone;
//   agent/subagent-requested    the agent's script: the child's start, and the answer and its note
//                               to the parent (agent-start.ts `startSubagent`);
//   mcp/subscription-ended, mcp/task-settled
//                               an MCP server's notice to the agent whose script connected to it
//                               (`itx.connectToMcp`)                         → "— MCP server …"
//       The server's words, as data. They start a turn, and the agent's own acts bound how many
//       come: one for one `subscribe`, one for one tool call that became a task. An event that
//       a subscription brings (`mcp/webhook-received`) starts none: agent-ui.ts says why.
//
// THE GUARD. Other code can append the same facts to any context. So this file acts only on a
// context that runs this agent: its start facts are in its log, or the Dash asked for one there
// (agent-start.ts `agentAt`). On every other context it does nothing.
//
// WHAT THE DASH DRAWS FOR THIS KIND, and how its New agent starts one, is not here: the Dash loads
// that from a file of /repos/config (config/agent-kinds/agent.ts says why).
import type { StreamEvent } from "iterate/stream/processor";
import { agentAt, type Itx, startSubagent, toAgent } from "../agent-start.ts";
import {
  agentsApiContext,
  agentUiContext,
  agentUiStartConfig,
  MCP_NOTICES,
  mcpNoticeContext,
  senderEmail,
  transcriptionKey,
} from "../agent-ui.ts";

const T = "events.iterate.com/";
const UI_MESSAGE = `${T}agent-ui/message-received`;
const UI_AGENT_REQUESTED = `${T}agent-ui/agent-requested`;
const API_MESSAGE = `${T}agent/message-received`;
const CONTEXT_ADDED = `${T}agent/context-added`;
const SUBAGENT_REQUESTED = `${T}agent/subagent-requested`;
const [MCP_SUBSCRIPTION_ENDED, MCP_TASK_SETTLED] = MCP_NOTICES;

export async function agentKindEvent(itx: Itx, event: StreamEvent) {
  switch (event.type) {
    case UI_AGENT_REQUESTED: {
      // the Dash gives birth to an agent: its `itx` is linked to the mind's root
      const config = agentUiStartConfig(event);
      if (config) await toAgent(itx, event.path, [], { config, parent: "/" });
      return;
    }
    case SUBAGENT_REQUESTED:
      if (await agentAt(itx, event.path)) await startSubagent(itx, event);
      return;
    case MCP_SUBSCRIPTION_ENDED:
    case MCP_TASK_SETTLED: {
      // an MCP server's notice: the agent hears it as that server's data, and takes a turn
      if (!(await agentAt(itx, event.path))) return;
      const input = mcpNoticeContext(event);
      if (!input) return; // a payload that is no object
      await toAgent(
        itx,
        event.path,
        [{ type: CONTEXT_ADDED, idempotencyKey: transcriptionKey(event), payload: input }],
        {},
      );
      return;
    }
    case UI_MESSAGE:
    case API_MESSAGE: {
      const agent = await agentAt(itx, event.path);
      if (!agent) return;
      // WHETHER THE SENDER IS A MEMBER, asked once, here: the line above the words says it, so
      // the model does not spend a request on the same question. A check that fails says nothing.
      const email = senderEmail(event);
      const member = email ? await itx.members.has(email).catch(() => undefined) : undefined;
      const said = { member };
      const input =
        event.type === UI_MESSAGE ? agentUiContext(event, said) : agentsApiContext(event, said);
      if (!input) return; // a payload the schema refuses
      // Words that are handled before the Dash's request give birth to the agent themselves.
      // Any other start names no parent: the link of the agent's birth stands.
      await toAgent(
        itx,
        event.path,
        [{ type: CONTEXT_ADDED, idempotencyKey: transcriptionKey(event), payload: input }],
        agent.asked ? { parent: "/" } : {},
      );
    }
  }
}