@wheatley-ai/cli 0.0.0-stage → 0.1.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/LICENSE +15 -0
- package/bin/wheatley.js +2 -0
- package/dist/approvals/gate.js +278 -0
- package/dist/approvals/module.js +21 -0
- package/dist/approvals/policy.js +30 -0
- package/dist/approvals/preview.js +17 -0
- package/dist/approvals/prompt.js +98 -0
- package/dist/approvals/rpc.js +16 -0
- package/dist/approvals/store.js +159 -0
- package/dist/cli/ask.js +94 -0
- package/dist/cli/chat.js +178 -0
- package/dist/cli/client.js +104 -0
- package/dist/cli/daemon.js +35 -0
- package/dist/cli/init.js +72 -0
- package/dist/cli/io.js +45 -0
- package/dist/cli/main.js +206 -0
- package/dist/cli/session.js +86 -0
- package/dist/cli/status.js +46 -0
- package/dist/contracts/approval-gate.js +1 -0
- package/dist/contracts/config-store.js +1 -0
- package/dist/contracts/delivery-outbox.js +1 -0
- package/dist/contracts/errors.js +28 -0
- package/dist/contracts/extension-catalog.js +1 -0
- package/dist/contracts/maintenance-runner.js +1 -0
- package/dist/contracts/memory-store.js +1 -0
- package/dist/contracts/module.js +7 -0
- package/dist/contracts/tool-names.js +43 -0
- package/dist/contracts/trigger-runtime.js +1 -0
- package/dist/contracts/webhook-ingress.js +2 -0
- package/dist/core/agent/agent-store.js +300 -0
- package/dist/core/agent/agent.js +1033 -0
- package/dist/core/agent/gated-models.js +89 -0
- package/dist/core/agent/pi-adapter.js +401 -0
- package/dist/core/agent/policy-gate.js +44 -0
- package/dist/core/builtin-catalog.js +20 -0
- package/dist/core/concurrency-gate.js +87 -0
- package/dist/core/config/atomic-file.js +72 -0
- package/dist/core/config/config-store.js +138 -0
- package/dist/core/config/pending-restart.js +53 -0
- package/dist/core/config/secret-references.js +69 -0
- package/dist/core/config/secret-store.js +147 -0
- package/dist/core/config/validate.js +55 -0
- package/dist/core/config/yaml-patch.js +57 -0
- package/dist/core/daemon-socket.js +96 -0
- package/dist/core/daemon.js +97 -0
- package/dist/core/deployment.js +379 -0
- package/dist/core/error-message.js +4 -0
- package/dist/core/events.js +25 -0
- package/dist/core/logger.js +81 -0
- package/dist/core/models.js +27 -0
- package/dist/core/module.js +42 -0
- package/dist/core/rpc/agent-handlers.js +82 -0
- package/dist/core/rpc/deployment-handlers.js +63 -0
- package/dist/core/rpc/router.js +96 -0
- package/dist/core/server/connection.js +170 -0
- package/dist/core/server/control-server.js +152 -0
- package/dist/core/server/static-files.js +79 -0
- package/dist/core/supervisor.js +215 -0
- package/dist/core/tool-routing.js +41 -0
- package/dist/dashboard/assets/index-C9Rul5vE.css +2 -0
- package/dist/dashboard/assets/index-DXzGGAxQ.js +11 -0
- package/dist/dashboard/assets/sheet-presentation-DMljN0LW.js +1 -0
- package/dist/dashboard/index.html +18 -0
- package/dist/db/database.js +16 -0
- package/dist/db/migrations.js +184 -0
- package/dist/frontends/discord/approvals.js +199 -0
- package/dist/frontends/discord/attachments.js +115 -0
- package/dist/frontends/discord/binding.js +489 -0
- package/dist/frontends/discord/config.js +107 -0
- package/dist/frontends/discord/discord-runtime.js +52 -0
- package/dist/frontends/discord/errors.js +61 -0
- package/dist/frontends/discord/live-runs.js +189 -0
- package/dist/frontends/discord/module.js +39 -0
- package/dist/frontends/discord/recent-ids.js +20 -0
- package/dist/frontends/slack/approval-blocks.js +98 -0
- package/dist/frontends/slack/attachments.js +102 -0
- package/dist/frontends/slack/background-tasks.js +20 -0
- package/dist/frontends/slack/binding.js +405 -0
- package/dist/frontends/slack/bounded.js +9 -0
- package/dist/frontends/slack/chat-id.js +17 -0
- package/dist/frontends/slack/config.js +80 -0
- package/dist/frontends/slack/delivery-errors.js +81 -0
- package/dist/frontends/slack/inbound.js +76 -0
- package/dist/frontends/slack/live-progress.js +190 -0
- package/dist/frontends/slack/manifest.js +66 -0
- package/dist/frontends/slack/outbound.js +160 -0
- package/dist/frontends/slack/schemas.js +99 -0
- package/dist/frontends/slack/signature.js +30 -0
- package/dist/frontends/slack/slack-client.js +60 -0
- package/dist/frontends/slack/slack-frontend.js +38 -0
- package/dist/frontends/slack/state-store.js +112 -0
- package/dist/frontends/telegram/approvals.js +134 -0
- package/dist/frontends/telegram/attachments.js +126 -0
- package/dist/frontends/telegram/binding.js +144 -0
- package/dist/frontends/telegram/chat-key.js +43 -0
- package/dist/frontends/telegram/client.js +88 -0
- package/dist/frontends/telegram/config.js +93 -0
- package/dist/frontends/telegram/delivery.js +215 -0
- package/dist/frontends/telegram/frontend.js +42 -0
- package/dist/frontends/telegram/grammy-client.js +122 -0
- package/dist/frontends/telegram/http-status.js +6 -0
- package/dist/frontends/telegram/inbound.js +149 -0
- package/dist/frontends/telegram/live.js +182 -0
- package/dist/frontends/telegram/markdown.js +103 -0
- package/dist/frontends/telegram/recent-set.js +18 -0
- package/dist/frontends/telegram/serial-queue.js +23 -0
- package/dist/index.js +7 -0
- package/dist/mcp/content.js +61 -0
- package/dist/mcp/mcp-module.js +35 -0
- package/dist/mcp/mcp-tool-provider.js +93 -0
- package/dist/mcp/server-connection.js +297 -0
- package/dist/memory/consolidation.js +260 -0
- package/dist/memory/format.js +5 -0
- package/dist/memory/migrations.js +76 -0
- package/dist/memory/module.js +69 -0
- package/dist/memory/names.js +20 -0
- package/dist/memory/rows.js +22 -0
- package/dist/memory/rpc.js +49 -0
- package/dist/memory/snapshots.js +12 -0
- package/dist/memory/store.js +281 -0
- package/dist/memory/tools.js +158 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/config.d.ts +262 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/config.js +120 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/domain.d.ts +512 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/domain.js +441 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/duration.d.ts +8 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/duration.js +28 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/events.d.ts +234 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/events.js +124 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.d.ts +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.js +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.d.ts +81 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.js +157 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json.d.ts +14 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json.js +23 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/limits.d.ts +17 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/limits.js +17 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/methods.d.ts +1107 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/methods.js +201 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.d.ts +45 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.js +44 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/validation.d.ts +20 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/validation.js +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/package.json +14 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.d.ts +11 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.js +162 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/commands.d.ts +48 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/commands.js +39 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.d.ts +29 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.js +27 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.d.ts +236 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/index.d.ts +10 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/index.js +7 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/json.d.ts +9 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/json.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/logger.d.ts +18 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/logger.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.d.ts +48 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.js +5 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/schema.d.ts +69 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/schema.js +3 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/tool.d.ts +69 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/tool.js +3 -0
- package/dist/node_modules/@wheatley-ai/sdk/package.json +11 -0
- package/dist/ops/backup.js +185 -0
- package/dist/ops/cli.js +194 -0
- package/dist/ops/command-runner.js +34 -0
- package/dist/ops/dashboard-assets.js +37 -0
- package/dist/ops/migrate.js +63 -0
- package/dist/ops/module.js +47 -0
- package/dist/ops/paths.js +55 -0
- package/dist/ops/service.js +376 -0
- package/dist/ops/update.js +145 -0
- package/dist/plugins/contributions.js +89 -0
- package/dist/plugins/guards.js +111 -0
- package/dist/plugins/load.js +76 -0
- package/dist/plugins/module.js +31 -0
- package/dist/plugins/provider.js +349 -0
- package/dist/plugins/schema.js +69 -0
- package/dist/skills/disclosure.js +142 -0
- package/dist/skills/discovery.js +120 -0
- package/dist/skills/fs-errors.js +8 -0
- package/dist/skills/read-skill-tool.js +3 -0
- package/dist/skills/skill-file.js +90 -0
- package/dist/skills/skills.js +140 -0
- package/dist/tools/builtin-tools.js +61 -0
- package/dist/tools/input.js +45 -0
- package/dist/tools/paths.js +6 -0
- package/dist/tools/read-file.js +65 -0
- package/dist/tools/shell.js +156 -0
- package/dist/tools/write-file.js +58 -0
- package/dist/triggers/delivery-codec.js +99 -0
- package/dist/triggers/delivery-outbox.js +313 -0
- package/dist/triggers/due-timer.js +14 -0
- package/dist/triggers/errors.js +2 -0
- package/dist/triggers/migrations.js +91 -0
- package/dist/triggers/module.js +106 -0
- package/dist/triggers/rpc.js +35 -0
- package/dist/triggers/schedule.js +52 -0
- package/dist/triggers/sql-row.js +59 -0
- package/dist/triggers/trigger-runtime.js +445 -0
- package/dist/triggers/trigger-tools.js +210 -0
- package/dist/triggers/webhook-ingress.js +212 -0
- package/dist/wiring/agent-services.js +151 -0
- package/dist/wiring/catalog.js +81 -0
- package/dist/wiring/daemon.js +83 -0
- package/dist/wiring/frontend-host.js +268 -0
- package/package.json +50 -3
- package/README.md +0 -3
|
@@ -0,0 +1,1033 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdir } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { parseDuration, TOOL_INPUT_PREVIEW_MAX_LENGTH, TOOL_OUTPUT_PREVIEW_MAX_LENGTH, } from "@wheatley-ai/protocol";
|
|
5
|
+
import { BUILTIN_COMMANDS } from "@wheatley-ai/sdk";
|
|
6
|
+
import { SeamError } from "../../contracts/errors.js";
|
|
7
|
+
import { openAgentDatabase } from "../../db/database.js";
|
|
8
|
+
import { runMigrations } from "../../db/migrations.js";
|
|
9
|
+
import { ConcurrencyGate } from "../concurrency-gate.js";
|
|
10
|
+
import { SerialQueue } from "../config/atomic-file.js";
|
|
11
|
+
import { CLI_BINDING_ID } from "../config/validate.js";
|
|
12
|
+
import { errorMessage } from "../error-message.js";
|
|
13
|
+
import { toolErrorResult, withExtraTools } from "../tool-routing.js";
|
|
14
|
+
import { AgentStore, CORE_NAMESPACE, coreMigrations } from "./agent-store.js";
|
|
15
|
+
import { openPiAdapter } from "./pi-adapter.js";
|
|
16
|
+
import { createPolicyOnlyGate, evaluatePolicy } from "./policy-gate.js";
|
|
17
|
+
/** The Chat ID of the CLI Chat, which the dashboard shares (ADR 0007). */
|
|
18
|
+
export const CLI_CHAT_ID = "default";
|
|
19
|
+
/** The CLI Chat of every Agent. */
|
|
20
|
+
export const CLI_CHAT = {
|
|
21
|
+
bindingId: CLI_BINDING_ID,
|
|
22
|
+
chatId: CLI_CHAT_ID,
|
|
23
|
+
};
|
|
24
|
+
/** The default Approval timeout (ADR 0011). */
|
|
25
|
+
export const DEFAULT_APPROVAL_TIMEOUT = "15m";
|
|
26
|
+
/** The default limit of concurrent Runs of one Agent without `maxConcurrentRuns`. */
|
|
27
|
+
export const DEFAULT_MAX_CONCURRENT_RUNS = 4;
|
|
28
|
+
/** The time limit of one Tool call (ADR 0006). The Approval wait and the wait for a Tool slot do not count. */
|
|
29
|
+
export const TOOL_TIMEOUT_MS = 10 * 60 * 1000;
|
|
30
|
+
/** The most Tool calls that one Agent runs at the same time (ADR 0006). Later calls wait for a slot. */
|
|
31
|
+
export const MAX_CONCURRENT_TOOL_CALLS = 8;
|
|
32
|
+
/** The one `ConcurrencyGate` key of the Agent's Tool slots: all Tools of the Agent share the limit. */
|
|
33
|
+
const TOOL_SLOT_KEY = "tools";
|
|
34
|
+
/** The file name of the pi-durable storage inside the Agent folder (ADR 0001). */
|
|
35
|
+
export const HARNESS_FILE = "harness.sqlite";
|
|
36
|
+
/** The file name of the Agent's module database inside the Agent folder. */
|
|
37
|
+
export const AGENT_DB_FILE = "agent.sqlite";
|
|
38
|
+
/** The working directory of the Agent's Tools, inside the Agent folder. */
|
|
39
|
+
export const WORKSPACE_DIR = "workspace";
|
|
40
|
+
/** How the model sees a Trigger result that was delivered to its Chat (ADR 0010). */
|
|
41
|
+
const deliveredContext = (text) => `A Trigger Run sent this message to this Chat:\n\n${text}`;
|
|
42
|
+
const isCliChat = (chat) => chat?.bindingId === CLI_CHAT.bindingId && chat.chatId === CLI_CHAT.chatId;
|
|
43
|
+
const preview = (text, max) => text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
|
44
|
+
const resultText = (result) => result.content
|
|
45
|
+
.map((block) => block.type === "text" ? block.text : `[image ${block.mimeType}]`)
|
|
46
|
+
.join("\n");
|
|
47
|
+
const deliveryFor = (chat, source) => isCliChat(chat)
|
|
48
|
+
? null
|
|
49
|
+
: { bindingId: chat.bindingId, chatId: chat.chatId, source };
|
|
50
|
+
const parseModelArgument = (argument, current) => {
|
|
51
|
+
const slash = argument.indexOf("/");
|
|
52
|
+
return slash === -1
|
|
53
|
+
? { id: argument, provider: current.provider }
|
|
54
|
+
: { id: argument.slice(slash + 1), provider: argument.slice(0, slash) };
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* One running Agent: its `agent.sqlite`, its pi-durable Harness over `harness.sqlite`, its extensions, and its Runs
|
|
58
|
+
* (ADR 0001, ADR 0003). Agents share nothing except the Deployment's model access, so one Agent's failure leaves the
|
|
59
|
+
* others running.
|
|
60
|
+
*
|
|
61
|
+
* Ordering: `open` applies every migration, creates extensions and modules, opens the Harness, starts modules, and then
|
|
62
|
+
* continues the Runs that the last process left active.
|
|
63
|
+
*/
|
|
64
|
+
export class Agent {
|
|
65
|
+
name;
|
|
66
|
+
#options;
|
|
67
|
+
#db;
|
|
68
|
+
#store;
|
|
69
|
+
/** The catalog extensions, merged with module Tools once the modules mount. */
|
|
70
|
+
#extensions;
|
|
71
|
+
#moduleFrontends = [];
|
|
72
|
+
#gate;
|
|
73
|
+
#runSlots;
|
|
74
|
+
#toolSlots = new ConcurrencyGate(() => MAX_CONCURRENT_TOOL_CALLS);
|
|
75
|
+
#workspaceDir;
|
|
76
|
+
#active = new Map();
|
|
77
|
+
#runByConversation = new Map();
|
|
78
|
+
#conversationQueues = new Map();
|
|
79
|
+
#rpc = [];
|
|
80
|
+
#stops = [];
|
|
81
|
+
#pendingStarts = [];
|
|
82
|
+
#pi;
|
|
83
|
+
#closed = false;
|
|
84
|
+
constructor(options, db, extensions, gate) {
|
|
85
|
+
this.name = options.name;
|
|
86
|
+
this.#options = options;
|
|
87
|
+
this.#db = db;
|
|
88
|
+
this.#store = new AgentStore(db, options.name);
|
|
89
|
+
this.#extensions = extensions;
|
|
90
|
+
this.#gate = gate;
|
|
91
|
+
this.#workspaceDir = path.join(options.agentDir, WORKSPACE_DIR);
|
|
92
|
+
this.#runSlots = new ConcurrencyGate(() => options.config.maxConcurrentRuns ?? DEFAULT_MAX_CONCURRENT_RUNS);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Opens the Agent. Errors: rejects if a migration fails, the extensions cannot load, a module cannot be created, or
|
|
96
|
+
* the Harness cannot open. Everything opened so far is closed again before the promise rejects.
|
|
97
|
+
*/
|
|
98
|
+
static async open(options) {
|
|
99
|
+
await mkdir(path.join(options.agentDir, WORKSPACE_DIR), {
|
|
100
|
+
recursive: true,
|
|
101
|
+
});
|
|
102
|
+
const db = openAgentDatabase(path.join(options.agentDir, AGENT_DB_FILE));
|
|
103
|
+
let agent;
|
|
104
|
+
try {
|
|
105
|
+
const namespaces = [
|
|
106
|
+
{ migrations: coreMigrations, namespace: CORE_NAMESPACE },
|
|
107
|
+
...(options.modules ?? []).map((module) => module.migrations),
|
|
108
|
+
];
|
|
109
|
+
await (options.migrate === undefined
|
|
110
|
+
? Promise.try(() => runMigrations(db, namespaces))
|
|
111
|
+
: options.migrate(db, namespaces));
|
|
112
|
+
const abort = new AbortController();
|
|
113
|
+
const extensions = await options.extensions.createAgentExtensions({
|
|
114
|
+
agentDir: options.agentDir,
|
|
115
|
+
agentName: options.name,
|
|
116
|
+
config: options.config,
|
|
117
|
+
homeDir: options.homeDir,
|
|
118
|
+
log: options.log,
|
|
119
|
+
secrets: options.secrets,
|
|
120
|
+
signal: abort.signal,
|
|
121
|
+
});
|
|
122
|
+
// The gate exists before the Harness, and the Harness's wake exists after it, so the gate wakes through this.
|
|
123
|
+
const harness = { adapter: undefined };
|
|
124
|
+
const { approvalTimeout } = options.config;
|
|
125
|
+
const timeout = approvalTimeout === undefined
|
|
126
|
+
? DEFAULT_APPROVAL_TIMEOUT
|
|
127
|
+
: approvalTimeout;
|
|
128
|
+
const gateFactory = options.approvals ?? createPolicyOnlyGate;
|
|
129
|
+
const gate = gateFactory({
|
|
130
|
+
agentName: options.name,
|
|
131
|
+
clock: options.clock,
|
|
132
|
+
db,
|
|
133
|
+
// Module Tools join the Tool list once the modules mount, so this reads the Agent's list when it exists.
|
|
134
|
+
defaultAction: (toolName) => (agent === undefined ? extensions : agent.#extensions)
|
|
135
|
+
.tools()
|
|
136
|
+
.find((tool) => tool.name === toolName && tool.source === "builtin")
|
|
137
|
+
?.defaultAction,
|
|
138
|
+
events: options.events,
|
|
139
|
+
log: options.log,
|
|
140
|
+
policy: options.config.permissionPolicy ?? [],
|
|
141
|
+
timeoutMs: timeout === null ? null : parseDuration(timeout),
|
|
142
|
+
wake: async (calls) => {
|
|
143
|
+
await harness.adapter?.wake(calls);
|
|
144
|
+
},
|
|
145
|
+
});
|
|
146
|
+
agent = new Agent(options, db, extensions, gate);
|
|
147
|
+
agent.#stops.push(async () => {
|
|
148
|
+
abort.abort();
|
|
149
|
+
await extensions.close();
|
|
150
|
+
});
|
|
151
|
+
await agent.#mountModules();
|
|
152
|
+
harness.adapter = await agent.#openPi();
|
|
153
|
+
await agent.#startModules();
|
|
154
|
+
agent.#resumeRuns();
|
|
155
|
+
return agent;
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
if (agent === undefined) {
|
|
159
|
+
db.close();
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
await agent.close();
|
|
163
|
+
}
|
|
164
|
+
throw error;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
/** The JSON-RPC handlers of the hosted modules, in mount order. The core handlers come from `createAgentRpc`. */
|
|
168
|
+
get moduleRpc() {
|
|
169
|
+
return this.#rpc;
|
|
170
|
+
}
|
|
171
|
+
/** The Agent's `ApprovalGate`. */
|
|
172
|
+
get approvals() {
|
|
173
|
+
return this.#gate;
|
|
174
|
+
}
|
|
175
|
+
/** The Agent's maintenance Run starter (ADR 0009). */
|
|
176
|
+
get maintenance() {
|
|
177
|
+
return { start: this.#startMaintenance, wait: this.#waitRun };
|
|
178
|
+
}
|
|
179
|
+
/** The Agent's Trigger Run starter (ADR 0010). */
|
|
180
|
+
get triggers() {
|
|
181
|
+
return { isActive: this.#isTriggerActive, start: this.#startTrigger };
|
|
182
|
+
}
|
|
183
|
+
/** Health fields for `agents.get` and `system.status`. */
|
|
184
|
+
status = () => {
|
|
185
|
+
const health = this.#extensions.health();
|
|
186
|
+
return {
|
|
187
|
+
activeRuns: this.#active.size,
|
|
188
|
+
frontends: [
|
|
189
|
+
{ id: CLI_BINDING_ID, state: "ready", type: "cli" },
|
|
190
|
+
...this.#moduleFrontends.flatMap((frontends) => frontends()),
|
|
191
|
+
],
|
|
192
|
+
mcpServers: health.mcpServers,
|
|
193
|
+
plugins: health.plugins,
|
|
194
|
+
skillWarnings: health.skillWarnings,
|
|
195
|
+
};
|
|
196
|
+
};
|
|
197
|
+
/** The Tools of the Agent with the action of the Permission Policy in `config.yaml`, for `extensions.list`. */
|
|
198
|
+
tools = () => this.#extensions.tools().map((tool) => ({
|
|
199
|
+
action: evaluatePolicy(this.#options.config.permissionPolicy ?? [], tool.name, tool.defaultAction),
|
|
200
|
+
description: tool.description,
|
|
201
|
+
name: tool.name,
|
|
202
|
+
source: tool.source,
|
|
203
|
+
}));
|
|
204
|
+
/** The extensions of the Agent for `extensions.list`. */
|
|
205
|
+
get extensions() {
|
|
206
|
+
return this.#extensions;
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Stores a user message for `chat`, starts its Run, and resolves once both are stored. The reply arrives as a
|
|
210
|
+
* `chat.message` event for the CLI Chat, or through the outbox for any other Chat.
|
|
211
|
+
*/
|
|
212
|
+
send = async (chat, input) => {
|
|
213
|
+
const conversationId = await this.#chatConversation(chat);
|
|
214
|
+
return await this.#startRun({
|
|
215
|
+
chat,
|
|
216
|
+
conversationId,
|
|
217
|
+
delivery: deliveryFor(chat, "reply"),
|
|
218
|
+
interactive: input.interactive,
|
|
219
|
+
origin: { bindingId: chat.bindingId, chatId: chat.chatId, kind: "chat" },
|
|
220
|
+
prompt: input.text,
|
|
221
|
+
userMessage: {
|
|
222
|
+
senderDisplayName: input.senderDisplayName,
|
|
223
|
+
text: input.text,
|
|
224
|
+
},
|
|
225
|
+
});
|
|
226
|
+
};
|
|
227
|
+
/**
|
|
228
|
+
* Runs a built-in command for `chat` (ADR 0007). Resolves `false` if the command cannot run, for example `/model`
|
|
229
|
+
* without an argument or `/stop` without an active Run.
|
|
230
|
+
*
|
|
231
|
+
* Each call sends exactly one command reply to the Chat before it resolves, also when the command cannot run, so a
|
|
232
|
+
* Frontend shows only the reply and adds no message of its own. The exception is `/goal` with an objective, which
|
|
233
|
+
* sends no command reply and replies later through the Run that it starts. A command reply arrives like a Run reply,
|
|
234
|
+
* with source `command`.
|
|
235
|
+
*/
|
|
236
|
+
command = async (chat, name, args) => {
|
|
237
|
+
switch (name) {
|
|
238
|
+
case "new": {
|
|
239
|
+
return await this.#newConversation(chat);
|
|
240
|
+
}
|
|
241
|
+
case "model": {
|
|
242
|
+
return await this.#changeModel(chat, args);
|
|
243
|
+
}
|
|
244
|
+
case "compact": {
|
|
245
|
+
return await this.#compact(chat);
|
|
246
|
+
}
|
|
247
|
+
case "stop": {
|
|
248
|
+
return await this.#stopChat(chat);
|
|
249
|
+
}
|
|
250
|
+
case "goal": {
|
|
251
|
+
return await this.#goal(chat, args);
|
|
252
|
+
}
|
|
253
|
+
case "status": {
|
|
254
|
+
return await this.#reportStatus(chat);
|
|
255
|
+
}
|
|
256
|
+
case "restart": {
|
|
257
|
+
await this.#reply(chat, "Restarting this Agent.");
|
|
258
|
+
this.#options.onRestartRequested();
|
|
259
|
+
return true;
|
|
260
|
+
}
|
|
261
|
+
default: {
|
|
262
|
+
return false;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
/** Messages of the Chat's current Conversation, oldest first, before `before`. */
|
|
267
|
+
history = async (chat, before, limit) => {
|
|
268
|
+
const conversationId = await this.#chatConversation(chat);
|
|
269
|
+
const rows = this.#store.chatMessages(conversationId, before, limit);
|
|
270
|
+
const hasMore = rows.length > limit;
|
|
271
|
+
return {
|
|
272
|
+
conversationId,
|
|
273
|
+
hasMore,
|
|
274
|
+
messages: hasMore ? rows.slice(1) : rows,
|
|
275
|
+
};
|
|
276
|
+
};
|
|
277
|
+
/** Runs newest first. */
|
|
278
|
+
listRuns = (options) => {
|
|
279
|
+
const rows = this.#store.listRuns(options);
|
|
280
|
+
const hasMore = rows.length > options.limit;
|
|
281
|
+
return { hasMore, runs: hasMore ? rows.slice(0, options.limit) : rows };
|
|
282
|
+
};
|
|
283
|
+
/** One Run and its timeline. Throws `SeamError("not_found")` for an unknown Run. */
|
|
284
|
+
getRun = (runId) => {
|
|
285
|
+
const stored = this.#store.getRun(runId);
|
|
286
|
+
if (stored === undefined) {
|
|
287
|
+
throw new SeamError("not_found", `Unknown Run: ${runId}`);
|
|
288
|
+
}
|
|
289
|
+
return { run: stored.summary, timeline: this.#store.timeline(runId) };
|
|
290
|
+
};
|
|
291
|
+
/** Stops an active Run: cancels its Approvals and stops its Conversation's work. Resolves `false` if it ended. */
|
|
292
|
+
stopRun = async (runId) => {
|
|
293
|
+
const run = this.#active.get(runId);
|
|
294
|
+
if (run === undefined || this.#pi === undefined) {
|
|
295
|
+
return false;
|
|
296
|
+
}
|
|
297
|
+
run.controller.abort(new Error("The Run was stopped"));
|
|
298
|
+
await this.#gate.cancelRun(runId);
|
|
299
|
+
// A Run that still waits behind another Run of its Conversation ends when its turn comes, because its signal
|
|
300
|
+
// aborted. Only the Run that drives the Conversation stops the Conversation's work.
|
|
301
|
+
if (this.#runByConversation.get(run.conversationId) === runId) {
|
|
302
|
+
await this.#pi.stop(run.conversationId);
|
|
303
|
+
}
|
|
304
|
+
return true;
|
|
305
|
+
};
|
|
306
|
+
/**
|
|
307
|
+
* Stops modules in reverse order, closes the Harness, the extensions, and `agent.sqlite`. Active Runs stay active in
|
|
308
|
+
* storage and continue at the next `open`. Repeated calls do nothing.
|
|
309
|
+
*/
|
|
310
|
+
close = async () => {
|
|
311
|
+
if (this.#closed) {
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
this.#closed = true;
|
|
315
|
+
for (const run of this.#active.values()) {
|
|
316
|
+
run.controller.abort(new Error("The Agent stopped"));
|
|
317
|
+
}
|
|
318
|
+
for (const stop of this.#stops.toReversed()) {
|
|
319
|
+
try {
|
|
320
|
+
// oxlint-disable-next-line no-await-in-loop -- Modules stop one at a time in reverse creation order.
|
|
321
|
+
await stop();
|
|
322
|
+
}
|
|
323
|
+
catch (error) {
|
|
324
|
+
this.#options.log.error("A module failed to stop", {
|
|
325
|
+
error: errorMessage(error),
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
this.#db.close();
|
|
330
|
+
};
|
|
331
|
+
#mountModules = async () => {
|
|
332
|
+
const ctx = {
|
|
333
|
+
agentDir: this.#options.agentDir,
|
|
334
|
+
agentName: this.name,
|
|
335
|
+
clock: this.#options.clock,
|
|
336
|
+
db: this.#db,
|
|
337
|
+
events: this.#options.events,
|
|
338
|
+
log: this.#options.log,
|
|
339
|
+
};
|
|
340
|
+
const host = {
|
|
341
|
+
approvals: this.#gate,
|
|
342
|
+
chat: { command: this.command, send: this.send },
|
|
343
|
+
extensions: this.#extensions,
|
|
344
|
+
maintenance: this.maintenance,
|
|
345
|
+
recordDelivered: this.#recordDelivered,
|
|
346
|
+
triggers: this.triggers,
|
|
347
|
+
};
|
|
348
|
+
const moduleTools = [];
|
|
349
|
+
for (const module of this.#options.modules ?? []) {
|
|
350
|
+
// oxlint-disable-next-line no-await-in-loop -- Modules are created one at a time in configuration order.
|
|
351
|
+
const mounted = await module.mount(ctx, host);
|
|
352
|
+
this.#rpc.push(mounted.rpc);
|
|
353
|
+
if (mounted.stop !== undefined) {
|
|
354
|
+
this.#stops.push(mounted.stop);
|
|
355
|
+
}
|
|
356
|
+
if (mounted.tools !== undefined) {
|
|
357
|
+
moduleTools.push(mounted.tools);
|
|
358
|
+
this.#stops.push(mounted.tools.close);
|
|
359
|
+
}
|
|
360
|
+
if (mounted.frontends !== undefined) {
|
|
361
|
+
this.#moduleFrontends.push(mounted.frontends);
|
|
362
|
+
}
|
|
363
|
+
this.#pendingStarts.push(mounted.start);
|
|
364
|
+
}
|
|
365
|
+
this.#extensions = withExtraTools(this.#extensions, moduleTools);
|
|
366
|
+
};
|
|
367
|
+
/**
|
|
368
|
+
* Copies a delivered Trigger result into the current Conversation of its target Chat, so the Chat history and the
|
|
369
|
+
* model context of its next Run show it (ADR 0010). The CLI Chat records Trigger results when the Run ends, so this
|
|
370
|
+
* skips it.
|
|
371
|
+
*/
|
|
372
|
+
#recordDelivered = async (entry) => {
|
|
373
|
+
const { delivery } = entry;
|
|
374
|
+
if (delivery.kind !== "message" || isCliChat(entry)) {
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
const chat = { bindingId: entry.bindingId, chatId: entry.chatId };
|
|
378
|
+
const conversationId = await this.#chatConversation(chat);
|
|
379
|
+
const at = this.#now();
|
|
380
|
+
this.#recordMessage(chat, conversationId, {
|
|
381
|
+
at,
|
|
382
|
+
messageId: entry.deliveryId,
|
|
383
|
+
role: "assistant",
|
|
384
|
+
source: delivery.source,
|
|
385
|
+
text: delivery.text,
|
|
386
|
+
});
|
|
387
|
+
await this.#requirePi().addContext(conversationId, deliveredContext(delivery.text), `delivered:${entry.deliveryId}`);
|
|
388
|
+
await this.#archive({ bindingId: chat.bindingId, chatId: chat.chatId, kind: "chat" }, {
|
|
389
|
+
at: Date.parse(at),
|
|
390
|
+
conversationId,
|
|
391
|
+
role: "assistant",
|
|
392
|
+
text: delivery.text,
|
|
393
|
+
});
|
|
394
|
+
};
|
|
395
|
+
#startModules = async () => {
|
|
396
|
+
for (const start of this.#pendingStarts) {
|
|
397
|
+
// oxlint-disable-next-line no-await-in-loop -- Modules start in creation order.
|
|
398
|
+
await start?.();
|
|
399
|
+
}
|
|
400
|
+
};
|
|
401
|
+
#openPi = async () => {
|
|
402
|
+
const pi = await openPiAdapter({
|
|
403
|
+
harnessPath: path.join(this.#options.agentDir, HARNESS_FILE),
|
|
404
|
+
hooks: {
|
|
405
|
+
checkTool: this.#checkTool,
|
|
406
|
+
executeTool: this.#executeTool,
|
|
407
|
+
onFailed: (error) => {
|
|
408
|
+
this.#options.log.error("The Harness failed", {
|
|
409
|
+
error: error.message,
|
|
410
|
+
});
|
|
411
|
+
this.#options.onFailed(error);
|
|
412
|
+
},
|
|
413
|
+
flushPrompt: () => this.#options.memory?.compactionFlushPrompt(),
|
|
414
|
+
},
|
|
415
|
+
log: this.#options.log,
|
|
416
|
+
models: this.#options.models,
|
|
417
|
+
now: this.#options.clock.now,
|
|
418
|
+
tools: this.#extensions.tools().map((tool) => ({
|
|
419
|
+
description: tool.description,
|
|
420
|
+
inputSchema: tool.inputSchema,
|
|
421
|
+
name: tool.name,
|
|
422
|
+
})),
|
|
423
|
+
});
|
|
424
|
+
this.#pi = pi;
|
|
425
|
+
this.#stops.push(pi.close);
|
|
426
|
+
return pi;
|
|
427
|
+
};
|
|
428
|
+
#requirePi = () => {
|
|
429
|
+
if (this.#pi === undefined || this.#closed) {
|
|
430
|
+
throw new SeamError("agent_unavailable", `Agent ${this.name} is not running`);
|
|
431
|
+
}
|
|
432
|
+
return this.#pi;
|
|
433
|
+
};
|
|
434
|
+
#instructions = async () => {
|
|
435
|
+
const parts = [
|
|
436
|
+
this.#options.config.instructions,
|
|
437
|
+
this.#extensions.skillCatalogPrompt(),
|
|
438
|
+
await this.#options.memory?.snapshotPrompt(),
|
|
439
|
+
].filter((part) => part !== undefined && part.trim() !== "");
|
|
440
|
+
return parts.length === 0 ? undefined : parts.join("\n\n");
|
|
441
|
+
};
|
|
442
|
+
#createConversation = async (model = this.#options.config.model) => await this.#requirePi().createConversation({
|
|
443
|
+
cwd: this.#workspaceDir,
|
|
444
|
+
instructions: await this.#instructions(),
|
|
445
|
+
model,
|
|
446
|
+
});
|
|
447
|
+
#chatConversation = async (chat) => {
|
|
448
|
+
const existing = this.#store.chatConversation(chat.bindingId, chat.chatId);
|
|
449
|
+
if (existing !== undefined) {
|
|
450
|
+
return existing;
|
|
451
|
+
}
|
|
452
|
+
const created = await this.#createConversation();
|
|
453
|
+
this.#store.setChatConversation(chat.bindingId, chat.chatId, created);
|
|
454
|
+
return created;
|
|
455
|
+
};
|
|
456
|
+
#now = () => new Date(this.#options.clock.now()).toISOString();
|
|
457
|
+
#startRun = async (spec) => {
|
|
458
|
+
const pi = this.#requirePi();
|
|
459
|
+
const runId = randomUUID();
|
|
460
|
+
const messageId = randomUUID();
|
|
461
|
+
const startedAt = this.#now();
|
|
462
|
+
const model = await pi.modelOf(spec.conversationId);
|
|
463
|
+
this.#store.insertRun({
|
|
464
|
+
conversationId: spec.conversationId,
|
|
465
|
+
delivery: spec.delivery,
|
|
466
|
+
interactive: spec.interactive,
|
|
467
|
+
model,
|
|
468
|
+
origin: spec.origin,
|
|
469
|
+
runId,
|
|
470
|
+
startedAt,
|
|
471
|
+
});
|
|
472
|
+
if (spec.userMessage !== undefined) {
|
|
473
|
+
this.#recordMessage(spec.chat, spec.conversationId, {
|
|
474
|
+
at: startedAt,
|
|
475
|
+
messageId,
|
|
476
|
+
role: "user",
|
|
477
|
+
runId,
|
|
478
|
+
senderDisplayName: spec.userMessage.senderDisplayName,
|
|
479
|
+
text: spec.userMessage.text,
|
|
480
|
+
});
|
|
481
|
+
await this.#archive(spec.origin, {
|
|
482
|
+
at: Date.parse(startedAt),
|
|
483
|
+
conversationId: spec.conversationId,
|
|
484
|
+
role: "user",
|
|
485
|
+
text: spec.userMessage.text,
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
const run = this.#track(runId, spec);
|
|
489
|
+
const stored = this.#store.getRun(runId);
|
|
490
|
+
if (stored !== undefined) {
|
|
491
|
+
this.#options.events.emit("run.started", {
|
|
492
|
+
agent: this.name,
|
|
493
|
+
run: stored.summary,
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
void this.#drive(run, async () => {
|
|
497
|
+
const submissionId = await pi.submit(spec.conversationId, spec.prompt, runId);
|
|
498
|
+
this.#store.setSubmission(runId, submissionId);
|
|
499
|
+
return submissionId;
|
|
500
|
+
});
|
|
501
|
+
return { conversationId: spec.conversationId, messageId, runId };
|
|
502
|
+
};
|
|
503
|
+
#track = (runId, spec) => {
|
|
504
|
+
const run = {
|
|
505
|
+
chat: spec.chat,
|
|
506
|
+
controller: new AbortController(),
|
|
507
|
+
conversationId: spec.conversationId,
|
|
508
|
+
done: Promise.withResolvers(),
|
|
509
|
+
interactive: spec.interactive,
|
|
510
|
+
origin: spec.origin,
|
|
511
|
+
runId,
|
|
512
|
+
};
|
|
513
|
+
this.#active.set(runId, run);
|
|
514
|
+
return run;
|
|
515
|
+
};
|
|
516
|
+
#queueOf = (conversationId) => {
|
|
517
|
+
const existing = this.#conversationQueues.get(conversationId);
|
|
518
|
+
if (existing !== undefined) {
|
|
519
|
+
return existing;
|
|
520
|
+
}
|
|
521
|
+
const created = new SerialQueue();
|
|
522
|
+
this.#conversationQueues.set(conversationId, created);
|
|
523
|
+
return created;
|
|
524
|
+
};
|
|
525
|
+
/**
|
|
526
|
+
* Drives one Run to its end: one Run per Conversation at a time, within the Agent's `maxConcurrentRuns`. `submit`
|
|
527
|
+
* admits the input, or returns the stored submission of a Run from before a restart.
|
|
528
|
+
*/
|
|
529
|
+
#drive = async (run, submit) => {
|
|
530
|
+
let outcome;
|
|
531
|
+
try {
|
|
532
|
+
outcome = await this.#queueOf(run.conversationId).run(async () => {
|
|
533
|
+
const lease = await this.#runSlots.acquire("runs", run.controller.signal);
|
|
534
|
+
try {
|
|
535
|
+
const pi = this.#requirePi();
|
|
536
|
+
const stopText = await pi.watchText(run.conversationId, (delta) => {
|
|
537
|
+
this.#options.events.emit("run.delta", {
|
|
538
|
+
agent: this.name,
|
|
539
|
+
delta,
|
|
540
|
+
runId: run.runId,
|
|
541
|
+
});
|
|
542
|
+
});
|
|
543
|
+
try {
|
|
544
|
+
// A stop that came while the watch started finds no driving Run, so the Run must not submit after it.
|
|
545
|
+
run.controller.signal.throwIfAborted();
|
|
546
|
+
this.#runByConversation.set(run.conversationId, run.runId);
|
|
547
|
+
return await pi.wait(await submit());
|
|
548
|
+
}
|
|
549
|
+
finally {
|
|
550
|
+
stopText();
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
finally {
|
|
554
|
+
this.#runByConversation.delete(run.conversationId);
|
|
555
|
+
lease.release();
|
|
556
|
+
}
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
catch (error) {
|
|
560
|
+
outcome = run.controller.signal.aborted
|
|
561
|
+
? { status: "stopped", text: "" }
|
|
562
|
+
: {
|
|
563
|
+
error: errorMessage(error),
|
|
564
|
+
status: "failed",
|
|
565
|
+
text: "",
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
if (this.#closed) {
|
|
569
|
+
// The Run stays active in storage and continues at the next open.
|
|
570
|
+
this.#active.delete(run.runId);
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
await this.#finish(run, outcome);
|
|
574
|
+
};
|
|
575
|
+
/** Stores the end of a Run and resolves `run.done`. Never rejects: it logs a storage failure instead. */
|
|
576
|
+
#finish = async (run, outcome) => {
|
|
577
|
+
try {
|
|
578
|
+
await this.#storeOutcome(run, outcome);
|
|
579
|
+
}
|
|
580
|
+
catch (error) {
|
|
581
|
+
this.#options.log.error("The end of a Run could not be stored", {
|
|
582
|
+
error: errorMessage(error),
|
|
583
|
+
runId: run.runId,
|
|
584
|
+
});
|
|
585
|
+
}
|
|
586
|
+
finally {
|
|
587
|
+
this.#active.delete(run.runId);
|
|
588
|
+
run.done.resolve({
|
|
589
|
+
status: outcome.status,
|
|
590
|
+
text: outcome.text,
|
|
591
|
+
error: outcome.error,
|
|
592
|
+
});
|
|
593
|
+
}
|
|
594
|
+
};
|
|
595
|
+
#storeOutcome = async (run, outcome) => {
|
|
596
|
+
const stored = this.#store.getRun(run.runId);
|
|
597
|
+
const at = this.#now();
|
|
598
|
+
try {
|
|
599
|
+
if (outcome.text !== "") {
|
|
600
|
+
await this.#recordReply(run, stored?.delivery ?? null, outcome.text, at);
|
|
601
|
+
await this.#deliverReply(run, stored?.delivery ?? null, outcome.text);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
catch (error) {
|
|
605
|
+
this.#options.log.error("A Run reply could not be delivered", {
|
|
606
|
+
error: errorMessage(error),
|
|
607
|
+
runId: run.runId,
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
const ended = this.#store.endRun(run.runId, {
|
|
611
|
+
endedAt: at,
|
|
612
|
+
error: outcome.error,
|
|
613
|
+
status: outcome.status,
|
|
614
|
+
usage: outcome.usage,
|
|
615
|
+
});
|
|
616
|
+
this.#active.delete(run.runId);
|
|
617
|
+
const summary = this.#store.getRun(run.runId)?.summary;
|
|
618
|
+
if (ended && summary !== undefined) {
|
|
619
|
+
this.#options.events.emit("run.finished", {
|
|
620
|
+
agent: this.name,
|
|
621
|
+
run: summary,
|
|
622
|
+
});
|
|
623
|
+
}
|
|
624
|
+
};
|
|
625
|
+
/**
|
|
626
|
+
* Stores the final reply. A reply for the CLI Chat, also from a Trigger that targets it, goes into the Chat's current
|
|
627
|
+
* Conversation and out as a `chat.message` event.
|
|
628
|
+
*/
|
|
629
|
+
#recordReply = async (run, delivery, text, at) => {
|
|
630
|
+
const message = {
|
|
631
|
+
at,
|
|
632
|
+
messageId: randomUUID(),
|
|
633
|
+
role: "assistant",
|
|
634
|
+
runId: run.runId,
|
|
635
|
+
source: run.origin.kind === "trigger" ? "trigger" : "reply",
|
|
636
|
+
text,
|
|
637
|
+
};
|
|
638
|
+
const triggerToCli = run.chat === null && delivery !== null && isCliChat(delivery);
|
|
639
|
+
if (triggerToCli &&
|
|
640
|
+
(await this.#options.isDeliverySuppressed?.(run.runId)) !== true) {
|
|
641
|
+
const conversationId = await this.#chatConversation(CLI_CHAT);
|
|
642
|
+
this.#recordMessage(CLI_CHAT, conversationId, message);
|
|
643
|
+
await this.#requirePi().addContext(conversationId, deliveredContext(text), `delivered:${message.messageId}`);
|
|
644
|
+
await this.#archive(run.origin, {
|
|
645
|
+
at: Date.parse(at),
|
|
646
|
+
conversationId,
|
|
647
|
+
role: "assistant",
|
|
648
|
+
text,
|
|
649
|
+
});
|
|
650
|
+
return;
|
|
651
|
+
}
|
|
652
|
+
this.#recordMessage(isCliChat(run.chat) ? run.chat : null, run.conversationId, message);
|
|
653
|
+
await this.#archive(run.origin, {
|
|
654
|
+
at: Date.parse(at),
|
|
655
|
+
conversationId: run.conversationId,
|
|
656
|
+
role: "assistant",
|
|
657
|
+
text,
|
|
658
|
+
});
|
|
659
|
+
};
|
|
660
|
+
/**
|
|
661
|
+
* Adds a user or assistant message to the Memory archive. Maintenance Runs stay out of it, so that consolidation
|
|
662
|
+
* output does not feed the next consolidation. A failure only logs: the message is stored in `agent.sqlite` already.
|
|
663
|
+
*/
|
|
664
|
+
#archive = async (origin, message) => {
|
|
665
|
+
if (this.#options.memory === undefined || origin.kind === "maintenance") {
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
668
|
+
try {
|
|
669
|
+
await this.#options.memory.archive(message);
|
|
670
|
+
}
|
|
671
|
+
catch (error) {
|
|
672
|
+
this.#options.log.warn("A message could not be archived", {
|
|
673
|
+
conversationId: message.conversationId,
|
|
674
|
+
error: errorMessage(error),
|
|
675
|
+
});
|
|
676
|
+
}
|
|
677
|
+
};
|
|
678
|
+
#deliverReply = async (run, delivery, text) => {
|
|
679
|
+
if (delivery === null || isCliChat(delivery)) {
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
if (run.origin.kind === "trigger" &&
|
|
683
|
+
(await this.#options.isDeliverySuppressed?.(run.runId)) === true) {
|
|
684
|
+
return;
|
|
685
|
+
}
|
|
686
|
+
if (this.#options.outbox === undefined) {
|
|
687
|
+
this.#options.log.warn("No outbox: a reply was dropped", {
|
|
688
|
+
bindingId: delivery.bindingId,
|
|
689
|
+
runId: run.runId,
|
|
690
|
+
});
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
await this.#options.outbox.enqueue({
|
|
694
|
+
bindingId: delivery.bindingId,
|
|
695
|
+
chatId: delivery.chatId,
|
|
696
|
+
delivery: {
|
|
697
|
+
kind: "message",
|
|
698
|
+
runId: run.runId,
|
|
699
|
+
source: delivery.source,
|
|
700
|
+
text,
|
|
701
|
+
},
|
|
702
|
+
sourceConversationId: delivery.sourceConversationId,
|
|
703
|
+
});
|
|
704
|
+
};
|
|
705
|
+
#recordMessage = (chat, conversationId, message) => {
|
|
706
|
+
this.#store.insertMessage({ chat, conversationId, message });
|
|
707
|
+
if (message.runId !== undefined &&
|
|
708
|
+
(message.role === "user" || message.source !== "command")) {
|
|
709
|
+
const item = message.role === "user"
|
|
710
|
+
? {
|
|
711
|
+
at: message.at,
|
|
712
|
+
kind: "user_message",
|
|
713
|
+
senderDisplayName: message.senderDisplayName,
|
|
714
|
+
text: message.text,
|
|
715
|
+
}
|
|
716
|
+
: { at: message.at, kind: "assistant_text", text: message.text };
|
|
717
|
+
this.#store.putTimelineItem(message.runId, `message:${message.messageId}`, item);
|
|
718
|
+
}
|
|
719
|
+
if (isCliChat(chat)) {
|
|
720
|
+
this.#options.events.emit("chat.message", { agent: this.name, message });
|
|
721
|
+
}
|
|
722
|
+
};
|
|
723
|
+
/** Sends a command reply to the Chat: an event for the CLI Chat, or an outbox delivery for any other Chat. */
|
|
724
|
+
#reply = async (chat, text) => {
|
|
725
|
+
const conversationId = await this.#chatConversation(chat);
|
|
726
|
+
if (isCliChat(chat)) {
|
|
727
|
+
this.#recordMessage(chat, conversationId, {
|
|
728
|
+
at: this.#now(),
|
|
729
|
+
messageId: randomUUID(),
|
|
730
|
+
role: "assistant",
|
|
731
|
+
source: "command",
|
|
732
|
+
text,
|
|
733
|
+
});
|
|
734
|
+
return;
|
|
735
|
+
}
|
|
736
|
+
await this.#options.outbox?.enqueue({
|
|
737
|
+
bindingId: chat.bindingId,
|
|
738
|
+
chatId: chat.chatId,
|
|
739
|
+
delivery: { kind: "message", source: "command", text },
|
|
740
|
+
});
|
|
741
|
+
};
|
|
742
|
+
#resumeRuns = () => {
|
|
743
|
+
for (const stored of this.#store.activeRuns()) {
|
|
744
|
+
const { summary, submissionId } = stored;
|
|
745
|
+
const chat = summary.origin.kind === "chat"
|
|
746
|
+
? {
|
|
747
|
+
bindingId: summary.origin.bindingId,
|
|
748
|
+
chatId: summary.origin.chatId,
|
|
749
|
+
}
|
|
750
|
+
: null;
|
|
751
|
+
const run = this.#track(summary.runId, {
|
|
752
|
+
chat,
|
|
753
|
+
conversationId: summary.conversationId,
|
|
754
|
+
interactive: stored.interactive,
|
|
755
|
+
origin: summary.origin,
|
|
756
|
+
});
|
|
757
|
+
if (submissionId === undefined) {
|
|
758
|
+
void this.#finish(run, {
|
|
759
|
+
error: "The daemon stopped before the Run started",
|
|
760
|
+
status: "failed",
|
|
761
|
+
text: "",
|
|
762
|
+
});
|
|
763
|
+
}
|
|
764
|
+
else {
|
|
765
|
+
void this.#drive(run, async () => {
|
|
766
|
+
await Promise.resolve();
|
|
767
|
+
return submissionId;
|
|
768
|
+
});
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
};
|
|
772
|
+
#runOf = (conversationId) => {
|
|
773
|
+
const runId = this.#runByConversation.get(conversationId) ?? "";
|
|
774
|
+
return { run: this.#active.get(runId), runId };
|
|
775
|
+
};
|
|
776
|
+
#checkTool = async (call) => {
|
|
777
|
+
const { run, runId } = this.#runOf(call.conversationId);
|
|
778
|
+
const verdict = await this.#gate.check({
|
|
779
|
+
callKey: call.callKey,
|
|
780
|
+
chat: run?.chat ?? null,
|
|
781
|
+
conversationId: call.conversationId,
|
|
782
|
+
input: call.input,
|
|
783
|
+
interactive: run?.interactive ?? false,
|
|
784
|
+
runId: runId === "" ? `unknown:${call.conversationId}` : runId,
|
|
785
|
+
toolName: call.toolName,
|
|
786
|
+
});
|
|
787
|
+
if (runId !== "") {
|
|
788
|
+
this.#store.setActiveStatus(runId, verdict.kind === "wait" ? "waiting_approval" : "running");
|
|
789
|
+
}
|
|
790
|
+
if (verdict.kind === "wait") {
|
|
791
|
+
if (runId !== "" &&
|
|
792
|
+
this.#store.timelineItem(`approval:${verdict.approvalId}`) === undefined) {
|
|
793
|
+
this.#store.putTimelineItem(runId, `approval:${verdict.approvalId}`, {
|
|
794
|
+
approvalId: verdict.approvalId,
|
|
795
|
+
at: this.#now(),
|
|
796
|
+
kind: "approval",
|
|
797
|
+
toolName: call.toolName,
|
|
798
|
+
});
|
|
799
|
+
}
|
|
800
|
+
return {
|
|
801
|
+
expiresAt: verdict.expiresAt,
|
|
802
|
+
kind: "wait",
|
|
803
|
+
signalKey: verdict.signalKey,
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
return verdict.kind === "allow"
|
|
807
|
+
? { kind: "allow" }
|
|
808
|
+
: { kind: "deny", message: verdict.message };
|
|
809
|
+
};
|
|
810
|
+
#executeTool = async (call, signal) => {
|
|
811
|
+
const { run, runId } = this.#runOf(call.conversationId);
|
|
812
|
+
const inputPreview = preview(this.#options.secrets.redact(JSON.stringify(call.input)), TOOL_INPUT_PREVIEW_MAX_LENGTH);
|
|
813
|
+
const startedAt = this.#now();
|
|
814
|
+
const key = `tool:${call.callKey}`;
|
|
815
|
+
if (runId !== "") {
|
|
816
|
+
this.#options.events.emit("run.toolStarted", {
|
|
817
|
+
agent: this.name,
|
|
818
|
+
inputPreview,
|
|
819
|
+
runId,
|
|
820
|
+
toolCallId: call.toolCallId,
|
|
821
|
+
toolName: call.toolName,
|
|
822
|
+
});
|
|
823
|
+
this.#store.putTimelineItem(runId, key, {
|
|
824
|
+
endedAt: null,
|
|
825
|
+
inputPreview,
|
|
826
|
+
kind: "tool_call",
|
|
827
|
+
startedAt,
|
|
828
|
+
toolCallId: call.toolCallId,
|
|
829
|
+
toolName: call.toolName,
|
|
830
|
+
});
|
|
831
|
+
}
|
|
832
|
+
// ADR 0006: every Tool call runs within the Agent's Tool concurrency limit and a per-call time limit. The time
|
|
833
|
+
// limit starts once the call holds a slot, so the wait for a slot does not count.
|
|
834
|
+
const cancel = AbortSignal.any([
|
|
835
|
+
signal,
|
|
836
|
+
...(run === undefined ? [] : [run.controller.signal]),
|
|
837
|
+
]);
|
|
838
|
+
let result;
|
|
839
|
+
try {
|
|
840
|
+
const lease = await this.#toolSlots.acquire(TOOL_SLOT_KEY, cancel);
|
|
841
|
+
const toolSignal = AbortSignal.any([
|
|
842
|
+
cancel,
|
|
843
|
+
AbortSignal.timeout(TOOL_TIMEOUT_MS),
|
|
844
|
+
]);
|
|
845
|
+
try {
|
|
846
|
+
result = await this.#extensions.executeTool(call.toolName, call.input, {
|
|
847
|
+
agentName: this.name,
|
|
848
|
+
chat: run?.chat ?? null,
|
|
849
|
+
conversationId: call.conversationId,
|
|
850
|
+
log: this.#options.log,
|
|
851
|
+
runId,
|
|
852
|
+
signal: toolSignal,
|
|
853
|
+
toolCallId: call.toolCallId,
|
|
854
|
+
workspaceDir: this.#workspaceDir,
|
|
855
|
+
});
|
|
856
|
+
}
|
|
857
|
+
finally {
|
|
858
|
+
lease.release();
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
catch (error) {
|
|
862
|
+
result = toolErrorResult(errorMessage(error));
|
|
863
|
+
}
|
|
864
|
+
if (runId !== "") {
|
|
865
|
+
const outputPreview = preview(this.#options.secrets.redact(resultText(result)), TOOL_OUTPUT_PREVIEW_MAX_LENGTH);
|
|
866
|
+
const isError = result.isError === true;
|
|
867
|
+
this.#store.putTimelineItem(runId, key, {
|
|
868
|
+
endedAt: this.#now(),
|
|
869
|
+
inputPreview,
|
|
870
|
+
isError,
|
|
871
|
+
kind: "tool_call",
|
|
872
|
+
outputPreview,
|
|
873
|
+
startedAt,
|
|
874
|
+
toolCallId: call.toolCallId,
|
|
875
|
+
toolName: call.toolName,
|
|
876
|
+
});
|
|
877
|
+
this.#options.events.emit("run.toolFinished", {
|
|
878
|
+
agent: this.name,
|
|
879
|
+
isError,
|
|
880
|
+
outputPreview,
|
|
881
|
+
runId,
|
|
882
|
+
toolCallId: call.toolCallId,
|
|
883
|
+
toolName: call.toolName,
|
|
884
|
+
});
|
|
885
|
+
}
|
|
886
|
+
return result;
|
|
887
|
+
};
|
|
888
|
+
#activeRunOf = (chat) => [...this.#active.values()].find((run) => run.chat?.bindingId === chat.bindingId &&
|
|
889
|
+
run.chat.chatId === chat.chatId);
|
|
890
|
+
#newConversation = async (chat) => {
|
|
891
|
+
const previous = this.#store.chatConversation(chat.bindingId, chat.chatId);
|
|
892
|
+
const created = await this.#createConversation();
|
|
893
|
+
this.#store.setChatConversation(chat.bindingId, chat.chatId, created);
|
|
894
|
+
if (previous !== undefined) {
|
|
895
|
+
await this.#gate.clearConversationGrants(previous);
|
|
896
|
+
}
|
|
897
|
+
await this.#reply(chat, "Started a new Conversation.");
|
|
898
|
+
return true;
|
|
899
|
+
};
|
|
900
|
+
/** Replies with the usage of a command that needs an argument. Resolves `false`, because the command did not run. */
|
|
901
|
+
#replyUsage = async (chat, name) => {
|
|
902
|
+
const spec = BUILTIN_COMMANDS.find((command) => command.name === name);
|
|
903
|
+
await this.#reply(chat, `Usage: /${name} ${spec?.argument ?? ""}`.trim());
|
|
904
|
+
return false;
|
|
905
|
+
};
|
|
906
|
+
#changeModel = async (chat, args) => {
|
|
907
|
+
if (args === undefined) {
|
|
908
|
+
return await this.#replyUsage(chat, "model");
|
|
909
|
+
}
|
|
910
|
+
const model = parseModelArgument(args, this.#options.config.model);
|
|
911
|
+
if (this.#options.models.getModel(model.provider, model.id) === undefined) {
|
|
912
|
+
await this.#reply(chat, `Unknown model: ${model.provider}/${model.id}`);
|
|
913
|
+
return false;
|
|
914
|
+
}
|
|
915
|
+
const conversationId = await this.#chatConversation(chat);
|
|
916
|
+
await this.#requirePi().setModel(conversationId, model);
|
|
917
|
+
await this.#reply(chat, `This Conversation now uses ${model.provider}/${model.id}.`);
|
|
918
|
+
return true;
|
|
919
|
+
};
|
|
920
|
+
#compact = async (chat) => {
|
|
921
|
+
const pi = this.#requirePi();
|
|
922
|
+
const conversationId = await this.#chatConversation(chat);
|
|
923
|
+
const flushPrompt = this.#options.memory?.compactionFlushPrompt();
|
|
924
|
+
if (flushPrompt !== undefined) {
|
|
925
|
+
// The silent flush turn lets the model save facts to Memory before the summary replaces old messages (ADR 0009).
|
|
926
|
+
const submissionId = await pi.submit(conversationId, flushPrompt, `flush:${randomUUID()}`);
|
|
927
|
+
await pi.wait(submissionId);
|
|
928
|
+
}
|
|
929
|
+
await pi.compact(conversationId);
|
|
930
|
+
await pi.setInstructions(conversationId, await this.#instructions());
|
|
931
|
+
await this.#reply(chat, "Compacted the Conversation.");
|
|
932
|
+
return true;
|
|
933
|
+
};
|
|
934
|
+
#stopChat = async (chat) => {
|
|
935
|
+
const run = this.#activeRunOf(chat);
|
|
936
|
+
const stopped = run !== undefined && (await this.stopRun(run.runId));
|
|
937
|
+
await this.#reply(chat, stopped ? "Stopped the active Run." : "No Run is active.");
|
|
938
|
+
return stopped;
|
|
939
|
+
};
|
|
940
|
+
#goal = async (chat, args) => {
|
|
941
|
+
if (args === undefined) {
|
|
942
|
+
return await this.#replyUsage(chat, "goal");
|
|
943
|
+
}
|
|
944
|
+
const conversationId = await this.#chatConversation(chat);
|
|
945
|
+
await this.#startRun({
|
|
946
|
+
chat,
|
|
947
|
+
conversationId,
|
|
948
|
+
delivery: deliveryFor(chat, "reply"),
|
|
949
|
+
interactive: true,
|
|
950
|
+
origin: { bindingId: chat.bindingId, chatId: chat.chatId, kind: "chat" },
|
|
951
|
+
prompt: `Goal: ${args}\n\nWork on this goal autonomously with your Tools until it is done or blocked. Then report the result.`,
|
|
952
|
+
userMessage: { senderDisplayName: undefined, text: `/goal ${args}` },
|
|
953
|
+
});
|
|
954
|
+
return true;
|
|
955
|
+
};
|
|
956
|
+
#reportStatus = async (chat) => {
|
|
957
|
+
const conversationId = await this.#chatConversation(chat);
|
|
958
|
+
const model = (await this.#requirePi().modelOf(conversationId)) ?? "unknown";
|
|
959
|
+
const run = this.#activeRunOf(chat);
|
|
960
|
+
const status = this.status();
|
|
961
|
+
const lines = [
|
|
962
|
+
`Agent: ${this.name}`,
|
|
963
|
+
`Conversation: ${conversationId}`,
|
|
964
|
+
`Model: ${model}`,
|
|
965
|
+
`Active Run: ${run?.runId ?? "none"}`,
|
|
966
|
+
`Active Runs of the Agent: ${status.activeRuns}`,
|
|
967
|
+
`Failed extensions: ${[...status.plugins, ...status.mcpServers].filter((item) => item.state === "failed").length}`,
|
|
968
|
+
];
|
|
969
|
+
await this.#reply(chat, lines.join("\n"));
|
|
970
|
+
return true;
|
|
971
|
+
};
|
|
972
|
+
#startMaintenance = async (request) => {
|
|
973
|
+
const conversationId = await this.#createConversation(request.model);
|
|
974
|
+
const { runId } = await this.#startRun({
|
|
975
|
+
chat: null,
|
|
976
|
+
conversationId,
|
|
977
|
+
delivery: null,
|
|
978
|
+
interactive: false,
|
|
979
|
+
origin: { job: request.job, kind: "maintenance" },
|
|
980
|
+
prompt: request.prompt,
|
|
981
|
+
userMessage: undefined,
|
|
982
|
+
});
|
|
983
|
+
return { runId };
|
|
984
|
+
};
|
|
985
|
+
#waitRun = async (runId) => {
|
|
986
|
+
const active = this.#active.get(runId);
|
|
987
|
+
if (active !== undefined && active.origin.kind === "maintenance") {
|
|
988
|
+
return await active.done.promise;
|
|
989
|
+
}
|
|
990
|
+
const stored = this.#store.getRun(runId);
|
|
991
|
+
if (stored === undefined || stored.summary.origin.kind !== "maintenance") {
|
|
992
|
+
throw new SeamError("not_found", `Unknown maintenance Run: ${runId}`);
|
|
993
|
+
}
|
|
994
|
+
await Promise.resolve();
|
|
995
|
+
const { status, error } = stored.summary;
|
|
996
|
+
const ended = status === "completed" || status === "failed" || status === "stopped"
|
|
997
|
+
? status
|
|
998
|
+
: "failed";
|
|
999
|
+
return {
|
|
1000
|
+
status: ended,
|
|
1001
|
+
text: this.#store.runReply(runId),
|
|
1002
|
+
error,
|
|
1003
|
+
};
|
|
1004
|
+
};
|
|
1005
|
+
#startTrigger = async (firing) => {
|
|
1006
|
+
const { trigger } = firing;
|
|
1007
|
+
let conversationId = trigger.conversationMode === "shared"
|
|
1008
|
+
? this.#store.triggerConversation(trigger.id)
|
|
1009
|
+
: undefined;
|
|
1010
|
+
if (conversationId === undefined) {
|
|
1011
|
+
conversationId = await this.#createConversation();
|
|
1012
|
+
if (trigger.conversationMode === "shared") {
|
|
1013
|
+
this.#store.setTriggerConversation(trigger.id, conversationId);
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
const { runId } = await this.#startRun({
|
|
1017
|
+
chat: null,
|
|
1018
|
+
conversationId,
|
|
1019
|
+
delivery: {
|
|
1020
|
+
bindingId: firing.target.bindingId,
|
|
1021
|
+
chatId: firing.target.chatId,
|
|
1022
|
+
source: "trigger",
|
|
1023
|
+
sourceConversationId: conversationId,
|
|
1024
|
+
},
|
|
1025
|
+
interactive: false,
|
|
1026
|
+
origin: { kind: "trigger", triggerId: trigger.id },
|
|
1027
|
+
prompt: firing.prompt,
|
|
1028
|
+
userMessage: undefined,
|
|
1029
|
+
});
|
|
1030
|
+
return { runId };
|
|
1031
|
+
};
|
|
1032
|
+
#isTriggerActive = (triggerId) => [...this.#active.values()].some((run) => run.origin.kind === "trigger" && run.origin.triggerId === triggerId);
|
|
1033
|
+
}
|