@ouro.bot/cli 0.1.0-alpha.1702 → 0.1.0-alpha.1704
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/changelog.json +7 -0
- package/deploy/unraid/sanctuary.ouro/bundle-meta.json +1 -1
- package/deploy/unraid/sanctuary.xml +1 -1
- package/dist/heart/config.js +5 -7
- package/dist/heart/product/active.js +76 -2
- package/dist/heart/session-path.js +49 -0
- package/dist/nerves/coverage/file-completeness.js +2 -0
- package/dist/products/butler.js +40 -1
- package/dist/repertoire/butler-status.js +248 -0
- package/dist/repertoire/tools-sanctuary-host.js +11 -7
- package/dist/repertoire/tools-session.js +7 -211
- package/dist/repertoire/tools.js +36 -25
- package/dist/senses/shared-turn.js +4 -7
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/changelog.json
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"_note": "Each pull request writes its own change note under changes/; the release job on main gives each landed change its version and adds the notes here (scripts/release-version.cjs). On main this file stops at the last version set by hand; the published package has every release. Agents read this file directly via read_file to understand what changed between versions.",
|
|
3
3
|
"versions": [
|
|
4
|
+
{
|
|
5
|
+
"version": "0.1.0-alpha.1704",
|
|
6
|
+
"changes": [
|
|
7
|
+
"Update the Ouro UI files to Ouro UI v1.3.634.",
|
|
8
|
+
"The Butler's tool rules now come from its product registration, not from core. The product says the Butler's remote and relationship turns are scoped to a relationship. It adds the root-host tool (`sanctuary_host_execute`) in the owner's Telegram chat, and the house-care tools to the Butler's own scheduled inner turns. Its operational status (house health, policy, awaits, Telegram, events, provider lanes) is the section `query_active_work` adds. A tool can now carry its own `authorize` check, which the dispatcher runs after argument validation and before the handler. The root-host tool uses it in place of the dispatcher's special case for that one tool. On the Butler's image every turn's tool menu is the same as before, and so is every root-host call. An agent no product runs no longer gets the Butler's tool rules just because it is named `butler` or `sanctuary`. The in-turn tools X-ray loads the Butler's product, so it lists the same tools as before."
|
|
9
|
+
]
|
|
10
|
+
},
|
|
4
11
|
{
|
|
5
12
|
"version": "0.1.0-alpha.1702",
|
|
6
13
|
"changes": [
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
<?xml version="1.0"?>
|
|
2
2
|
<Container version="2">
|
|
3
3
|
<Name>ouro-butler</Name>
|
|
4
|
-
<Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.
|
|
4
|
+
<Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1704</Repository>
|
|
5
5
|
<Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
|
|
6
6
|
<Network>host</Network>
|
|
7
7
|
<Shell>sh</Shell>
|
package/dist/heart/config.js
CHANGED
|
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.InvalidSessionPathError = void 0;
|
|
36
|
+
exports.InvalidSessionPathError = exports.sanitizeKey = void 0;
|
|
37
37
|
exports.loadConfig = loadConfig;
|
|
38
38
|
exports.resetConfigCache = resetConfigCache;
|
|
39
39
|
exports.cacheRuntimeConfigForTests = cacheRuntimeConfigForTests;
|
|
@@ -57,7 +57,6 @@ exports.getIntegrationsConfig = getIntegrationsConfig;
|
|
|
57
57
|
exports.getSyncConfig = getSyncConfig;
|
|
58
58
|
exports.getOpenAIEmbeddingsApiKey = getOpenAIEmbeddingsApiKey;
|
|
59
59
|
exports.getLogsDir = getLogsDir;
|
|
60
|
-
exports.sanitizeKey = sanitizeKey;
|
|
61
60
|
exports.canonicalizeTelegramSessionKey = canonicalizeTelegramSessionKey;
|
|
62
61
|
exports.slugify = slugify;
|
|
63
62
|
exports.isValidSessionCoordinate = isValidSessionCoordinate;
|
|
@@ -72,6 +71,8 @@ const identity_1 = require("./identity");
|
|
|
72
71
|
const provider_credentials_1 = require("./provider-credentials");
|
|
73
72
|
const runtime_credentials_1 = require("./runtime-credentials");
|
|
74
73
|
const runtime_1 = require("../nerves/runtime");
|
|
74
|
+
const session_path_1 = require("./session-path");
|
|
75
|
+
Object.defineProperty(exports, "sanitizeKey", { enumerable: true, get: function () { return session_path_1.sanitizeKey; } });
|
|
75
76
|
const DEFAULT_LOCAL_RUNTIME_CONFIG = {
|
|
76
77
|
teams: {
|
|
77
78
|
clientId: "",
|
|
@@ -359,9 +360,6 @@ function getOpenAIEmbeddingsApiKey() {
|
|
|
359
360
|
function getLogsDir() {
|
|
360
361
|
return path.join((0, identity_1.getAgentRoot)(), "state", "logs");
|
|
361
362
|
}
|
|
362
|
-
function sanitizeKey(key) {
|
|
363
|
-
return key.replace(/[/:]/g, "_");
|
|
364
|
-
}
|
|
365
363
|
function canonicalizeTelegramSessionKey(key) {
|
|
366
364
|
if (key.startsWith("telegram:"))
|
|
367
365
|
return key;
|
|
@@ -401,7 +399,7 @@ function resolveSessionPath(friendId, channel, key, options) {
|
|
|
401
399
|
}
|
|
402
400
|
const sessionsRoot = path.join(agentRoot, "state", "sessions");
|
|
403
401
|
const dir = path.join(sessionsRoot, friendId, channel);
|
|
404
|
-
const file = path.join(dir, sanitizeKey(key) + ".json");
|
|
402
|
+
const file = path.join(dir, (0, session_path_1.sanitizeKey)(key) + ".json");
|
|
405
403
|
if (options?.confined) {
|
|
406
404
|
if (!isInsideSessionRoot(sessionsRoot, file))
|
|
407
405
|
throw new InvalidSessionPathError("session path escapes its root");
|
|
@@ -422,5 +420,5 @@ function sessionPath(friendId, channel, key) {
|
|
|
422
420
|
return resolveSessionPath(friendId, channel, key, { ensureDir: true });
|
|
423
421
|
}
|
|
424
422
|
function logPath(channel, key) {
|
|
425
|
-
return path.join(getLogsDir(), channel, sanitizeKey(key) + ".ndjson");
|
|
423
|
+
return path.join(getLogsDir(), channel, (0, session_path_1.sanitizeKey)(key) + ".ndjson");
|
|
426
424
|
}
|
|
@@ -8,11 +8,18 @@ exports.productAgentAmong = productAgentAmong;
|
|
|
8
8
|
exports.productHabit = productHabit;
|
|
9
9
|
exports.productEventSource = productEventSource;
|
|
10
10
|
exports.productTurnContext = productTurnContext;
|
|
11
|
+
exports.productTools = productTools;
|
|
12
|
+
exports.productToolDefinitions = productToolDefinitions;
|
|
13
|
+
exports.productToolSelection = productToolSelection;
|
|
14
|
+
exports.productActiveWorkSections = productActiveWorkSections;
|
|
11
15
|
const runtime_1 = require("../../nerves/runtime");
|
|
12
16
|
const container_runtime_1 = require("../daemon/container-runtime");
|
|
13
17
|
/** The seam version this harness runs. A product built for another stops the start. */
|
|
14
18
|
exports.PRODUCT_SEAM_VERSION = 1;
|
|
15
19
|
let active = null;
|
|
20
|
+
// Unit tests run on machines with no image, often with fs mocked; their setup sets this before any module loads, so a
|
|
21
|
+
// process that hasn't loaded a product answers as one with no image policy, without reading it.
|
|
22
|
+
const TEST_NO_IMAGE_PRODUCT = Symbol.for("ouro.test.noImageProduct");
|
|
16
23
|
// Whether this process has settled which product it runs: by an explicit load, or by the first productFor reading the image's policy.
|
|
17
24
|
let settled = false;
|
|
18
25
|
function invalid(modulePath, problem) {
|
|
@@ -39,6 +46,22 @@ function validProduct(value, modulePath) {
|
|
|
39
46
|
}
|
|
40
47
|
if (new Set(agents).size !== agents.length)
|
|
41
48
|
throw invalid(modulePath, "its agents list a name twice");
|
|
49
|
+
const tools = product.tools;
|
|
50
|
+
if (tools !== undefined) {
|
|
51
|
+
const definitions = tools?.definitions;
|
|
52
|
+
if (!Array.isArray(definitions))
|
|
53
|
+
throw invalid(modulePath, "its tools have no list of definitions");
|
|
54
|
+
for (const definition of definitions) {
|
|
55
|
+
const name = definition?.tool?.function?.name;
|
|
56
|
+
if (typeof name !== "string" || name.length === 0)
|
|
57
|
+
throw invalid(modulePath, "one of its tools has no name");
|
|
58
|
+
if (definition.ax?.id !== `tool:${name}`)
|
|
59
|
+
throw invalid(modulePath, `its tool ${name} has no Ouro AX card`);
|
|
60
|
+
}
|
|
61
|
+
const names = definitions.map((definition) => definition.tool.function.name);
|
|
62
|
+
if (new Set(names).size !== names.length)
|
|
63
|
+
throw invalid(modulePath, "its tools list a name twice");
|
|
64
|
+
}
|
|
42
65
|
return product;
|
|
43
66
|
}
|
|
44
67
|
/**
|
|
@@ -80,10 +103,17 @@ function loadImageProduct(options = {}) {
|
|
|
80
103
|
const policy = (0, container_runtime_1.readContainerRuntimePolicy)(options.policyPath === undefined ? {} : { path: options.policyPath });
|
|
81
104
|
return loadProduct(policy?.product, options.load);
|
|
82
105
|
}
|
|
106
|
+
function settle() {
|
|
107
|
+
if (settled)
|
|
108
|
+
return;
|
|
109
|
+
if (globalThis[TEST_NO_IMAGE_PRODUCT] === true)
|
|
110
|
+
loadProduct(undefined);
|
|
111
|
+
else
|
|
112
|
+
loadImageProduct();
|
|
113
|
+
}
|
|
83
114
|
/** The loaded product when this agent (or a saved record's `agent`) is one of its names, else null. */
|
|
84
115
|
function productFor(agentName) {
|
|
85
|
-
|
|
86
|
-
loadImageProduct();
|
|
116
|
+
settle();
|
|
87
117
|
return active && typeof agentName === "string" && active.agents.includes(agentName) ? active : null;
|
|
88
118
|
}
|
|
89
119
|
/** The one agent among `agents` that the product runs, or null when there is none or more than one. */
|
|
@@ -125,3 +155,47 @@ async function productTurnContext(input, options = {}) {
|
|
|
125
155
|
throw error;
|
|
126
156
|
}
|
|
127
157
|
}
|
|
158
|
+
function hookFailed(product, hook, agent, error, message) {
|
|
159
|
+
(0, runtime_1.emitNervesEvent)({
|
|
160
|
+
level: "error",
|
|
161
|
+
component: "daemon",
|
|
162
|
+
event: "daemon.product_hook_error",
|
|
163
|
+
message,
|
|
164
|
+
meta: { productId: product.id, hook, agent, reason: error instanceof Error ? error.message : String(error) },
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
/** The tools the product adds for this agent's turns (J3), or null when the agent has no product or the product adds none. */
|
|
168
|
+
function productTools(agentName) {
|
|
169
|
+
return productFor(agentName)?.tools ?? null;
|
|
170
|
+
}
|
|
171
|
+
/** The loaded product's own tool definitions, whichever agent asks: they are registered for the whole process, as core's are. */
|
|
172
|
+
function productToolDefinitions() {
|
|
173
|
+
settle();
|
|
174
|
+
return active?.tools?.definitions ?? [];
|
|
175
|
+
}
|
|
176
|
+
/** The tools the product adds to this turn's menu (J3), or none. A throw from the product fails the selection. */
|
|
177
|
+
function productToolSelection(agentName, input) {
|
|
178
|
+
const product = productFor(agentName);
|
|
179
|
+
if (!product?.tools?.select)
|
|
180
|
+
return [];
|
|
181
|
+
try {
|
|
182
|
+
return product.tools.select(input);
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
hookFailed(product, "tools.select", agentName, error, "the product's tool selection failed, so the turn's tools can't be selected");
|
|
186
|
+
throw error;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/** The sections the product adds to `query_active_work` for this agent (J7), or null when it adds none. A rejection fails the call. */
|
|
190
|
+
async function productActiveWorkSections(input) {
|
|
191
|
+
const product = productFor(input.agentName);
|
|
192
|
+
if (!product?.status)
|
|
193
|
+
return null;
|
|
194
|
+
try {
|
|
195
|
+
return await product.status.activeWorkSections(input);
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
hookFailed(product, "status.activeWorkSections", input.agentName, error, "the product's status sections failed, so query_active_work fails");
|
|
199
|
+
throw error;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.sanitizeKey = sanitizeKey;
|
|
37
|
+
exports.getSenseSessionPath = getSenseSessionPath;
|
|
38
|
+
const path = __importStar(require("path"));
|
|
39
|
+
const identity_1 = require("./identity");
|
|
40
|
+
// Where a sense keeps a session's file. Kept apart from heart/config and senses/shared-turn, which load far more, so code
|
|
41
|
+
// that only needs the path (the Butler's root-host tool, which every process on its image loads) stays light.
|
|
42
|
+
/** A session key as a file name: slashes and colons become underscores. */
|
|
43
|
+
function sanitizeKey(key) {
|
|
44
|
+
return key.replace(/[/:]/g, "_");
|
|
45
|
+
}
|
|
46
|
+
/** One session's file: under the agent's state/sessions, by friend, channel and sanitized key. */
|
|
47
|
+
function getSenseSessionPath(agentName, friendId, channel, sessionKey, agentRootOverride) {
|
|
48
|
+
return path.join(agentRootOverride ?? (0, identity_1.getAgentRoot)(agentName), "state", "sessions", friendId, channel, `${sanitizeKey(sessionKey)}.json`);
|
|
49
|
+
}
|
|
@@ -71,6 +71,8 @@ const DISPATCH_EXEMPT_PATTERNS = [
|
|
|
71
71
|
// Shared utility modules: pure helpers consumed by modules that own observability.
|
|
72
72
|
// The Butler's names and the one check that picks Butler behaviour; each caller owns its observability.
|
|
73
73
|
"heart/butler-agent",
|
|
74
|
+
// A session's file path from its coordinates; each caller owns its observability.
|
|
75
|
+
"heart/session-path",
|
|
74
76
|
"arc/json-store",
|
|
75
77
|
"heart/mail-import-discovery",
|
|
76
78
|
"repertoire/api-client",
|
package/dist/products/butler.js
CHANGED
|
@@ -33,7 +33,8 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.product = void 0;
|
|
36
|
+
exports.product = exports.BUTLER_HOUSE_CARE_TOOL_NAMES = void 0;
|
|
37
|
+
exports.selectButlerTools = selectButlerTools;
|
|
37
38
|
const path = __importStar(require("node:path"));
|
|
38
39
|
const butler_agent_1 = require("../heart/butler-agent");
|
|
39
40
|
const identity_1 = require("../heart/identity");
|
|
@@ -41,6 +42,7 @@ const sanctuary_acceptance_marker_1 = require("../heart/daemon/sanctuary-accepta
|
|
|
41
42
|
const sanctuary_scheduler_liveness_1 = require("../heart/daemon/sanctuary-scheduler-liveness");
|
|
42
43
|
const sanctuary_package_management_1 = require("../heart/daemon/sanctuary-package-management");
|
|
43
44
|
const runtime_1 = require("../nerves/runtime");
|
|
45
|
+
const tools_sanctuary_host_1 = require("../repertoire/tools-sanctuary-host");
|
|
44
46
|
const telegram_identity_key_1 = require("../senses/telegram-identity-key");
|
|
45
47
|
/** The acceptance run that proves a cron fire reaches the health sweep (Unit 16f), when one is running. */
|
|
46
48
|
function cronFingerprintScenario(agent) {
|
|
@@ -97,6 +99,28 @@ async function runSanctuaryHealth(input) {
|
|
|
97
99
|
}
|
|
98
100
|
return result;
|
|
99
101
|
}
|
|
102
|
+
/**
|
|
103
|
+
* The house-care tools the Butler's own scheduled turns get (tools-house-care.ts). Named, not imported: their module loads
|
|
104
|
+
* core's whole tool registry, and every process on the image loads the product. Core registers them, so a turn gets core's own.
|
|
105
|
+
*/
|
|
106
|
+
exports.BUTLER_HOUSE_CARE_TOOL_NAMES = ["house_sweep", "house_digest_send"];
|
|
107
|
+
/** The tools the Butler adds to a turn's menu: the root-host tool in the owner's Telegram chat, and house care on its own private turns. */
|
|
108
|
+
function selectButlerTools(input) {
|
|
109
|
+
if (input.channel === "telegram") {
|
|
110
|
+
// Offered only when this turn carries the owner's current, verified request; selectRootHostTool says so.
|
|
111
|
+
const hostTool = (0, tools_sanctuary_host_1.selectRootHostTool)(input.context, input.providerCapabilities);
|
|
112
|
+
return hostTool ? [hostTool] : [];
|
|
113
|
+
}
|
|
114
|
+
// The Butler's own scheduled turns (the daily house-care await) carry no relationship, so they cannot take the owner profile's menu.
|
|
115
|
+
if (input.channel !== "inner" || input.relationshipScoped)
|
|
116
|
+
return [];
|
|
117
|
+
return exports.BUTLER_HOUSE_CARE_TOOL_NAMES.map((name) => {
|
|
118
|
+
const definition = input.registered(name);
|
|
119
|
+
if (!definition)
|
|
120
|
+
throw new Error(`the Butler's house-care tool ${name} is not registered`);
|
|
121
|
+
return definition;
|
|
122
|
+
});
|
|
123
|
+
}
|
|
100
124
|
/**
|
|
101
125
|
* The Butler, registered with the harness through the product seam. The Unraid image names this module in
|
|
102
126
|
* /opt/ouro/container-runtime.json, so core loads it at runtime and never imports it. Each of the Butler's jobs gets its
|
|
@@ -121,6 +145,21 @@ exports.product = {
|
|
|
121
145
|
},
|
|
122
146
|
// J4: every turn gets the house runtime its tools read, and the answer gates the Butler opts in to.
|
|
123
147
|
turnContext: async ({ agentName }) => (await sanctuaryRuntime()).createSanctuaryToolContext(agentName),
|
|
148
|
+
// J3: remote and relationship turns get only the relationship menu; the root-host tool is the Butler's own.
|
|
149
|
+
tools: {
|
|
150
|
+
definitions: [tools_sanctuary_host_1.rootHostToolDefinition],
|
|
151
|
+
relationshipScoped: true,
|
|
152
|
+
select: selectButlerTools,
|
|
153
|
+
},
|
|
154
|
+
// J7: query_active_work adds the Butler's operational status. Loaded at the call: it reads Telegram's and the house's stores.
|
|
155
|
+
status: {
|
|
156
|
+
activeWorkSections: async ({ agentName, section, offset, limit }) => {
|
|
157
|
+
const { formatButlerOperationalVisibility, readButlerOperationalVisibility } = await Promise.resolve().then(() => __importStar(require("../repertoire/butler-status")));
|
|
158
|
+
return formatButlerOperationalVisibility(readButlerOperationalVisibility((0, identity_1.getAgentRoot)(), agentName), {
|
|
159
|
+
section: section, offset, limit,
|
|
160
|
+
});
|
|
161
|
+
},
|
|
162
|
+
},
|
|
124
163
|
// J5: the house check runs in the daemon, and only Supercronic may fire it on its cron schedule.
|
|
125
164
|
habits: {
|
|
126
165
|
"sanctuary-health": {
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.readButlerOperationalVisibility = readButlerOperationalVisibility;
|
|
37
|
+
exports.formatButlerOperationalVisibility = formatButlerOperationalVisibility;
|
|
38
|
+
const fs = __importStar(require("node:fs"));
|
|
39
|
+
const path = __importStar(require("node:path"));
|
|
40
|
+
const identity_1 = require("../heart/identity");
|
|
41
|
+
const router_1 = require("../heart/external-events/router");
|
|
42
|
+
const steward_policy_1 = require("../heart/steward-policy");
|
|
43
|
+
const await_parser_1 = require("../heart/awaiting/await-parser");
|
|
44
|
+
const daemon_health_1 = require("../heart/daemon/daemon-health");
|
|
45
|
+
const turn_context_1 = require("../heart/turn-context");
|
|
46
|
+
const telegram_effect_adapter_1 = require("../senses/telegram-effect-adapter");
|
|
47
|
+
const telegram_admission_1 = require("../senses/telegram-admission");
|
|
48
|
+
const sanctuary_health_1 = require("../senses/sanctuary-health");
|
|
49
|
+
const run_ledger_1 = require("../heart/run-ledger");
|
|
50
|
+
const runtime_1 = require("../nerves/runtime");
|
|
51
|
+
function boundedStatusText(value, max = 180) {
|
|
52
|
+
const normalized = value.replace(/\s+/g, " ").trim();
|
|
53
|
+
return normalized.length <= max ? normalized : `${normalized.slice(0, max - 3)}...`;
|
|
54
|
+
}
|
|
55
|
+
function readButlerOperationalVisibility(agentRoot = (0, identity_1.getAgentRoot)(), agentName = (0, identity_1.getAgentName)()) {
|
|
56
|
+
const sourceErrors = {};
|
|
57
|
+
const read = (source, operation, fallback) => {
|
|
58
|
+
try {
|
|
59
|
+
return operation();
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
sourceErrors[source] = boundedStatusText(error instanceof Error ? error.message : String(error)) || "unknown read failure";
|
|
63
|
+
return fallback;
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
const awaitsDir = path.join(agentRoot, "awaiting");
|
|
67
|
+
const awaits = read("awaits", () => fs.existsSync(awaitsDir) ? fs.readdirSync(awaitsDir, { withFileTypes: true })
|
|
68
|
+
.filter((entry) => entry.isFile() && entry.name.endsWith(".md"))
|
|
69
|
+
.map((entry) => {
|
|
70
|
+
const filePath = path.join(awaitsDir, entry.name);
|
|
71
|
+
return (0, await_parser_1.parseAwaitFile)(fs.readFileSync(filePath, "utf8"), filePath);
|
|
72
|
+
})
|
|
73
|
+
.filter((entry) => entry.status === "pending") : [], []);
|
|
74
|
+
const effectsRoot = path.join(agentRoot, "state", "telegram", "effects");
|
|
75
|
+
const telegramEffects = read("telegram_effects", () => {
|
|
76
|
+
if (!fs.existsSync(effectsRoot))
|
|
77
|
+
throw new Error("Telegram effect journal has not been created yet");
|
|
78
|
+
const journal = new telegram_effect_adapter_1.FileTelegramEffectJournal(effectsRoot);
|
|
79
|
+
try {
|
|
80
|
+
return journal.list().map((artifact) => ({
|
|
81
|
+
id: artifact.id,
|
|
82
|
+
authorClass: artifact.authorClass,
|
|
83
|
+
targetKind: artifact.target.kind,
|
|
84
|
+
state: artifact.parts.some((part) => part.state === "indeterminate") ? "indeterminate"
|
|
85
|
+
: artifact.parts.some((part) => part.state === "attempting") ? "attempting"
|
|
86
|
+
: artifact.parts.every((part) => part.state === "session_recorded") ? "session_recorded"
|
|
87
|
+
: artifact.parts.some((part) => part.state === "accepted") ? "accepted"
|
|
88
|
+
: "prepared",
|
|
89
|
+
acceptedAt: artifact.parts.flatMap((part) => part.acceptedAt ? [part.acceptedAt] : []).sort().at(-1) ?? null,
|
|
90
|
+
sessionRecordedAt: artifact.parts.flatMap((part) => part.sessionRecordedAt ? [part.sessionRecordedAt] : []).sort().at(-1) ?? null,
|
|
91
|
+
messageIds: artifact.parts.flatMap((part) => part.messageId ? [part.messageId] : []),
|
|
92
|
+
sessionEventIds: artifact.parts.flatMap((part) => part.sessionEventId ? [part.sessionEventId] : []),
|
|
93
|
+
updatedAt: artifact.updatedAt,
|
|
94
|
+
}));
|
|
95
|
+
}
|
|
96
|
+
finally {
|
|
97
|
+
journal.close();
|
|
98
|
+
}
|
|
99
|
+
}, []);
|
|
100
|
+
const admissionsRoot = path.join(agentRoot, "state", "senses", "telegram", "admissions");
|
|
101
|
+
const telegramAdmissions = read("telegram_admissions", () => {
|
|
102
|
+
if (!fs.existsSync(admissionsRoot))
|
|
103
|
+
throw new Error("Telegram admission store has not been created yet");
|
|
104
|
+
const store = new telegram_admission_1.FileTelegramAdmissionStore(admissionsRoot);
|
|
105
|
+
try {
|
|
106
|
+
return store.list().map((record) => ({ id: record.id, status: record.status, displayCode: record.displayCode, createdAt: record.createdAt, expiresAt: record.expiresAt }));
|
|
107
|
+
}
|
|
108
|
+
finally {
|
|
109
|
+
store.close();
|
|
110
|
+
}
|
|
111
|
+
}, []);
|
|
112
|
+
const status = {
|
|
113
|
+
agentName,
|
|
114
|
+
externalEvents: read("external_events", () => (0, router_1.listExternalEventStatus)((0, router_1.getExternalEventRoot)()).filter((event) => event.agent === agentName), []),
|
|
115
|
+
stewardPolicy: read("steward_policy", () => (0, steward_policy_1.readStewardPolicy)(agentRoot), { schemaVersion: 1, version: 0, desiredStates: {}, routineActionGrants: {}, updatedAt: null }),
|
|
116
|
+
awaits,
|
|
117
|
+
telegramEffects,
|
|
118
|
+
telegramAdmissions,
|
|
119
|
+
daemonHealth: read("daemon_health", () => {
|
|
120
|
+
const health = (0, daemon_health_1.readHealth)((0, daemon_health_1.getDefaultHealthPath)());
|
|
121
|
+
if (!health)
|
|
122
|
+
throw new Error("daemon health is missing or invalid");
|
|
123
|
+
return health;
|
|
124
|
+
}, null),
|
|
125
|
+
healthState: read("health_state", () => (0, sanctuary_health_1.readSanctuaryHealthState)(path.join(agentRoot, "state", "health", "sanctuary-health.json")), undefined),
|
|
126
|
+
routineActions: read("routine_actions", () => (0, steward_policy_1.readRoutineActionReceipts)(agentRoot), []),
|
|
127
|
+
providerLanes: read("provider", () => {
|
|
128
|
+
const config = (0, identity_1.loadAgentConfig)();
|
|
129
|
+
if (!config.humanFacing || !config.agentFacing)
|
|
130
|
+
throw new Error("provider lanes are unavailable");
|
|
131
|
+
return { outward: config.humanFacing, inner: config.agentFacing };
|
|
132
|
+
}, null),
|
|
133
|
+
lastAutomatedEventRun: read("run_ledger", () => (0, run_ledger_1.readRunLedger)(agentRoot)
|
|
134
|
+
.filter((row) => row.sourceKind === "private-runtime" && row.senseOrHabit === "external-event" && row.lifecycle === "completed")
|
|
135
|
+
.sort((left, right) => (right.endedAt ?? right.recordedAt).localeCompare(left.endedAt ?? left.recordedAt))[0] ?? null, null),
|
|
136
|
+
senseStatusLines: read("senses", () => (0, turn_context_1.readSenseStatusLines)(), []),
|
|
137
|
+
sourceErrors,
|
|
138
|
+
};
|
|
139
|
+
(0, runtime_1.emitNervesEvent)({ component: "tools", event: "tool.butler_status_read", message: "read the Butler's operational status", meta: { agentName, unavailable: Object.keys(sourceErrors) } });
|
|
140
|
+
return status;
|
|
141
|
+
}
|
|
142
|
+
function formatButlerOperationalVisibility(status, options = {}) {
|
|
143
|
+
const section = options.section ?? "all";
|
|
144
|
+
const offset = Math.max(0, options.offset ?? 0);
|
|
145
|
+
const limit = Math.min(20, Math.max(1, options.limit ?? 10));
|
|
146
|
+
const show = (wanted) => section === "all" || section === wanted;
|
|
147
|
+
const page = (rows) => rows.slice(offset, offset + limit);
|
|
148
|
+
const more = (label, total) => total > offset + limit ? ` - ${total - offset - limit} more ${label}; call query_active_work with section=${label}, offset=${offset + limit}, limit=${limit}` : null;
|
|
149
|
+
const daemon = status.daemonHealth;
|
|
150
|
+
const agentHealth = daemon?.agents[status.agentName];
|
|
151
|
+
const lines = ["## butler operational visibility"];
|
|
152
|
+
const error = (source) => status.sourceErrors[source] ? `unavailable (${status.sourceErrors[source]})` : null;
|
|
153
|
+
if (show("health")) {
|
|
154
|
+
lines.push(`- daemon: ${error("daemon_health") ?? daemon?.status ?? "unavailable"}${daemon ? `; mode ${daemon.mode}; pid ${daemon.pid}` : ""}`);
|
|
155
|
+
lines.push(`- butler: ${agentHealth ? `${agentHealth.status}; pid ${agentHealth.pid ?? "none"}; crashes ${agentHealth.crashes}` : "unavailable"}`);
|
|
156
|
+
lines.push("- senses:");
|
|
157
|
+
lines.push(...(error("senses") ? [` - ${error("senses")}`] : status.senseStatusLines.length > 0 ? status.senseStatusLines.map((line) => ` ${line}`) : [" - unavailable"]));
|
|
158
|
+
const health = status.healthState;
|
|
159
|
+
lines.push(`- health sweeps: ${error("health_state") ?? health?.sweepReceipts.length ?? 0}; delivered ${health?.deliveredReceipts.length ?? 0}; indeterminate ${health?.indeterminateDeliveries.length ?? 0}; outbox ${health?.outbox ? `${health.outbox.status}:${health.outbox.id}` : "clear"}; open incidents ${health ? Object.keys(health.incidents).length : 0}; updated ${health?.updatedAt ?? "unavailable"}`);
|
|
160
|
+
const healthRows = [
|
|
161
|
+
...(health?.sweepReceipts ?? []).map((sweep) => ({ at: sweep.completedAt, text: `sweep ${sweep.sweepId}: opened ${sweep.opened}; recovered ${sweep.recovered}; completed ${sweep.completedAt}${sweep.deliveryId ? `; delivery ${sweep.deliveryId}` : ""}` })),
|
|
162
|
+
...(health?.deliveredReceipts ?? []).map((delivery) => ({ at: delivery.deliveredAt, text: `delivered ${delivery.deliveryId}: ${delivery.kind}; messages ${delivery.messageIds.join(",")}; at ${delivery.deliveredAt}` })),
|
|
163
|
+
...(health?.indeterminateDeliveries ?? []).map((delivery) => ({ at: delivery.createdAt, text: `indeterminate ${delivery.id}: ${delivery.kind}; ${delivery.status}; created ${delivery.createdAt}` })),
|
|
164
|
+
].sort((a, b) => b.at.localeCompare(a.at));
|
|
165
|
+
for (const row of page(healthRows))
|
|
166
|
+
lines.push(` - ${row.text}`);
|
|
167
|
+
const overflow = more("health", healthRows.length);
|
|
168
|
+
if (overflow)
|
|
169
|
+
lines.push(overflow);
|
|
170
|
+
}
|
|
171
|
+
if (show("provider"))
|
|
172
|
+
lines.push(`- provider lanes: ${error("provider") ?? (status.providerLanes ? `outward ${status.providerLanes.outward.provider}/${status.providerLanes.outward.model}; inner ${status.providerLanes.inner.provider}/${status.providerLanes.inner.model}` : "unavailable")}`);
|
|
173
|
+
if (show("policy")) {
|
|
174
|
+
lines.push(`- steward policy: ${error("steward_policy") ?? `version ${status.stewardPolicy.version}; ${Object.keys(status.stewardPolicy.desiredStates).length} desired states; ${Object.keys(status.stewardPolicy.routineActionGrants).length} routine grants`}`);
|
|
175
|
+
const entries = [...Object.entries(status.stewardPolicy.desiredStates).map(([key, value]) => ({ key, kind: "desired", value })), ...Object.entries(status.stewardPolicy.routineActionGrants).map(([key, value]) => ({ key, kind: "grant", value }))];
|
|
176
|
+
for (const entry of page(entries)) {
|
|
177
|
+
const expiry = entry.value.expiresAt;
|
|
178
|
+
const active = !expiry || Date.parse(expiry) > Date.now();
|
|
179
|
+
lines.push(entry.kind === "desired" ? ` - ${entry.key} = ${boundedStatusText(entry.value.value)}; ${active ? "active" : "expired"}; ${entry.value.provenance}; source ${boundedStatusText(entry.value.source)}; v${entry.value.version}${expiry ? `; expires ${expiry}` : ""}` : ` - ${entry.key}: ${entry.value.action} on ${entry.value.targets.join(", ")}; ${active ? "active" : "expired"}; max ${entry.value.maxCount}/${entry.value.windowMs}ms; ${entry.value.verificationRequired ? "verification required" : "no verification"}; v${entry.value.version}${expiry ? `; expires ${expiry}` : ""}`);
|
|
180
|
+
}
|
|
181
|
+
const overflow = more("policy", entries.length);
|
|
182
|
+
if (overflow)
|
|
183
|
+
lines.push(overflow);
|
|
184
|
+
}
|
|
185
|
+
if (show("actions")) {
|
|
186
|
+
const actions = [...(status.routineActions ?? [])].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
|
187
|
+
lines.push(`- routine action receipts: ${error("routine_actions") ?? actions.length}`);
|
|
188
|
+
for (const action of page(actions)) {
|
|
189
|
+
const verification = action.state === "verified" ? `verified ${action.verifiedAfterState ?? "state unavailable"}` : action.state === "failed" ? "failed" : action.state === "indeterminate" ? "indeterminate; manual inspection required" : action.state === "recovered_no_effect" ? "no effect occurred" : "pending";
|
|
190
|
+
lines.push(` - ${action.id}: ${action.action} ${action.target}; ${action.state}; updated ${action.updatedAt}; verification ${verification}`);
|
|
191
|
+
}
|
|
192
|
+
const overflow = more("actions", actions.length);
|
|
193
|
+
if (overflow)
|
|
194
|
+
lines.push(overflow);
|
|
195
|
+
}
|
|
196
|
+
if (show("awaits")) {
|
|
197
|
+
lines.push(`- pending awaits: ${status.awaits.length}`);
|
|
198
|
+
if (error("awaits"))
|
|
199
|
+
lines.push(` - ${error("awaits")}`);
|
|
200
|
+
for (const pending of page(status.awaits))
|
|
201
|
+
lines.push(` - ${pending.name}: ${boundedStatusText(pending.condition ?? (pending.body || "condition unavailable"))}${pending.wake_at ? `; wake ${pending.wake_at}` : ""}`);
|
|
202
|
+
const overflow = more("awaits", status.awaits.length);
|
|
203
|
+
if (overflow)
|
|
204
|
+
lines.push(overflow);
|
|
205
|
+
}
|
|
206
|
+
if (show("telegram")) {
|
|
207
|
+
const acceptedTimes = status.telegramEffects.flatMap((effect) => effect.acceptedAt ? [effect.acceptedAt] : []).sort().reverse();
|
|
208
|
+
const recordedTimes = status.telegramEffects.flatMap((effect) => effect.sessionRecordedAt ? [effect.sessionRecordedAt] : []).sort().reverse();
|
|
209
|
+
const legacyAccepted = status.telegramEffects.some((effect) => !effect.acceptedAt && (effect.state === "accepted" || effect.state === "session_recorded"));
|
|
210
|
+
const legacyRecorded = status.telegramEffects.some((effect) => !effect.sessionRecordedAt && effect.state === "session_recorded");
|
|
211
|
+
lines.push(`- latest Telegram accepted: ${acceptedTimes[0] ?? (legacyAccepted ? "timestamp unavailable (legacy artifacts present)" : "none")}; latest session recorded: ${recordedTimes[0] ?? (legacyRecorded ? "timestamp unavailable (legacy artifacts present)" : "none")}`);
|
|
212
|
+
lines.push(`- Telegram effects: ${error("telegram_effects") ?? status.telegramEffects.length}`);
|
|
213
|
+
lines.push(`- Telegram admissions: ${error("telegram_admissions") ?? status.telegramAdmissions.length}`);
|
|
214
|
+
const telegramRows = [
|
|
215
|
+
...status.telegramEffects.map((effect) => ({ at: effect.updatedAt, effect })),
|
|
216
|
+
...status.telegramAdmissions.map((admission) => ({ at: new Date(admission.createdAt).toISOString(), admission })),
|
|
217
|
+
].sort((a, b) => b.at.localeCompare(a.at));
|
|
218
|
+
for (const row of page(telegramRows)) {
|
|
219
|
+
if ("admission" in row) {
|
|
220
|
+
const admission = row.admission;
|
|
221
|
+
lines.push(` - admission ${admission.id}: ${admission.status}; code ${admission.displayCode}; expires ${new Date(admission.expiresAt).toISOString()}`);
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
const effect = row.effect;
|
|
225
|
+
const accepted = effect.acceptedAt ?? ((effect.state === "accepted" || effect.state === "session_recorded") ? "timestamp unavailable (legacy)" : "not accepted");
|
|
226
|
+
const recorded = effect.sessionRecordedAt ?? (effect.state === "session_recorded" ? "timestamp unavailable (legacy)" : "not recorded");
|
|
227
|
+
lines.push(` - ${effect.id}: ${effect.state}; ${effect.authorClass}; ${effect.targetKind}; accepted ${accepted}; session recorded ${recorded}; message ids ${effect.messageIds?.join(",") || "none"}; session events ${effect.sessionEventIds?.join(",") || "none"}; updated ${effect.updatedAt}`);
|
|
228
|
+
}
|
|
229
|
+
const overflow = more("telegram", telegramRows.length);
|
|
230
|
+
if (overflow)
|
|
231
|
+
lines.push(overflow);
|
|
232
|
+
}
|
|
233
|
+
if (show("events")) {
|
|
234
|
+
const events = [...status.externalEvents].sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
|
|
235
|
+
const completedRun = status.lastAutomatedEventRun;
|
|
236
|
+
lines.push(`- external issues: ${events.length}; last successful automated event turn ${error("run_ledger") ?? (completedRun ? `${completedRun.endedAt ?? completedRun.recordedAt}; run ${completedRun.runId}; target ${completedRun.targetHash}` : "none")}`);
|
|
237
|
+
if (error("external_events"))
|
|
238
|
+
lines.push(` - ${error("external_events")}`);
|
|
239
|
+
for (const event of page(events)) {
|
|
240
|
+
const policy = event.stewardPolicy?.kind === "current" ? `${event.stewardPolicy.key}@${event.stewardPolicy.version}` : "none";
|
|
241
|
+
lines.push(` - ${event.source}/${event.eventType}/${event.eventId}: ${event.executionState}; disposition ${event.classification ?? "pending"}/${event.decision ?? "pending"}; reason ${boundedStatusText(event.reason ?? event.lastError ?? "not yet recorded")}; silence/wake ${event.nextWake ? JSON.stringify(event.nextWake) : "pending"}; steward ${policy}${event.awaitId ? `; await ${event.awaitId}` : ""}${event.careId ? `; care ${event.careId}` : ""}`);
|
|
242
|
+
}
|
|
243
|
+
const overflow = more("events", events.length);
|
|
244
|
+
if (overflow)
|
|
245
|
+
lines.push(overflow);
|
|
246
|
+
}
|
|
247
|
+
return lines.join("\n");
|
|
248
|
+
}
|
|
@@ -43,10 +43,10 @@ const node_util_1 = require("node:util");
|
|
|
43
43
|
const runtime_1 = require("../nerves/runtime");
|
|
44
44
|
const sanctuary_host_authority_1 = require("../heart/daemon/sanctuary-host-authority");
|
|
45
45
|
const session_events_1 = require("../heart/session-events");
|
|
46
|
-
const
|
|
46
|
+
const session_path_1 = require("../heart/session-path");
|
|
47
47
|
const relationship_authorization_1 = require("./relationship-authorization");
|
|
48
48
|
const tool_arguments_1 = require("./tool-arguments");
|
|
49
|
-
const
|
|
49
|
+
const tool_error_code_1 = require("./tool-error-code");
|
|
50
50
|
const butler_agent_1 = require("../heart/butler-agent");
|
|
51
51
|
const NAME = "sanctuary_host_execute";
|
|
52
52
|
const bindings = new WeakMap();
|
|
@@ -60,7 +60,7 @@ function boundBinding(ctx) {
|
|
|
60
60
|
}
|
|
61
61
|
function requireOwner(condition) {
|
|
62
62
|
if (!condition)
|
|
63
|
-
throw new RootHostAuthorizationError((0,
|
|
63
|
+
throw new RootHostAuthorizationError((0, tool_error_code_1.withCode)("Sanctuary root host authorization denied", "root-host-denied"));
|
|
64
64
|
}
|
|
65
65
|
function ownerFriend(friend, port) {
|
|
66
66
|
requireOwner(friend?.admissionState === "active" && friend.trustLevel === "family"
|
|
@@ -82,7 +82,7 @@ function currentCoordinates(ctx) {
|
|
|
82
82
|
requireOwner(actor && actor.trustLevel === "family" && actor.friendId === friend.id && session?.friendId === friend.id
|
|
83
83
|
&& session.channel === "telegram" && ctx.context.channel.channel === "telegram");
|
|
84
84
|
requireOwner([friend.id, actor.sessionEventId, relationship.requestId, session.key].every((value) => typeof value === "string" && value.trim().length > 0));
|
|
85
|
-
const sessionPath = (0,
|
|
85
|
+
const sessionPath = (0, session_path_1.getSenseSessionPath)("sanctuary", friend.id, "telegram", session.key, ctx.agentRoot);
|
|
86
86
|
requireOwner(session.sessionPath === sessionPath && sessionPath.startsWith(`${ctx.agentRoot}${path.sep}`));
|
|
87
87
|
const envelope = (0, session_events_1.loadSessionEnvelopeFile)(sessionPath);
|
|
88
88
|
const latest = envelope && (0, session_events_1.selectEffectiveSessionEvents)(envelope.events).findLast((event) => event.role === "user");
|
|
@@ -176,7 +176,11 @@ exports.rootHostToolDefinition = (0, tool_arguments_1.freezeToolValue)({
|
|
|
176
176
|
summaryKeys: ["targetHost", "targetResource"],
|
|
177
177
|
riskProfile: { risk: "high", mutates: "external_side_effect", reason: "owner-approved arbitrary host command" },
|
|
178
178
|
approvalPolicy: () => ({ kind: "required", policyId: "sanctuary.host.owner-approved.v1", actionClass: "owner_approved_arbitrary_host", requiresSoleCall: true }),
|
|
179
|
-
handler: () => { throw new Error((0,
|
|
179
|
+
handler: () => { throw new Error((0, tool_error_code_1.withCode)("Sanctuary host execution requires the root approval continuation; resident execution is forbidden", "resident-execution-forbidden")); },
|
|
180
|
+
// Only a definition selectRootHostTool made for this turn's binding is admitted; the registered one always refuses.
|
|
181
|
+
authorize: (ctx, args) => authorizeRootHostToolInvocation(ctx, exports.rootHostToolDefinition, args),
|
|
182
|
+
// authorizeRootHostContext asks the relationship and checks its receipt itself, bound to the selected copy.
|
|
183
|
+
authorizesRelationship: true,
|
|
180
184
|
});
|
|
181
185
|
function validateRootHostToolArguments(args, targetHost) {
|
|
182
186
|
requireOwner(!Object.hasOwn(args, "ownerObservation"));
|
|
@@ -196,7 +200,7 @@ function selectRootHostTool(ctx, capabilities) {
|
|
|
196
200
|
if (!ctx || !binding || !provenance || provenance.port !== ctx.rootHost.port || !capabilities?.has("approval-continuation")
|
|
197
201
|
|| !(0, node_util_1.isDeepStrictEqual)(binding, currentCoordinates(ctx)) || (!provenance.recovery && !observationAccepted(ctx)))
|
|
198
202
|
return undefined;
|
|
199
|
-
const selected = Object.freeze({ ...exports.rootHostToolDefinition });
|
|
203
|
+
const selected = Object.freeze({ ...exports.rootHostToolDefinition, authorize: (call, args) => authorizeRootHostToolInvocation(call, selected, args) });
|
|
200
204
|
selections.set(selected, { binding, capabilities });
|
|
201
205
|
return selected;
|
|
202
206
|
}
|
|
@@ -208,7 +212,7 @@ async function authorizeRootHostToolInvocation(ctx, definition, args) {
|
|
|
208
212
|
const selected = definition && selections.get(definition);
|
|
209
213
|
requireOwner(ctx && selected && ctx.rootHost?.binding === selected.binding && ctx.toolSelection?.ordinary.includes(definition));
|
|
210
214
|
if (!ctx.rootHost.port.isHealthy() && !await ctx.rootHost.port.refresh())
|
|
211
|
-
throw new Error((0,
|
|
215
|
+
throw new Error((0, tool_error_code_1.withCode)("Sanctuary root host authority is unavailable", "root-host-unavailable"));
|
|
212
216
|
requireOwner(selectRootHostTool(ctx, selected.capabilities));
|
|
213
217
|
const provenance = bindings.get(selected.binding);
|
|
214
218
|
await authorizeRootHostContext(ctx, provenance.recovery ? selected.binding : undefined);
|
|
@@ -34,15 +34,13 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
36
|
exports.sessionToolDefinitions = void 0;
|
|
37
|
-
exports.readButlerOperationalVisibility = readButlerOperationalVisibility;
|
|
38
|
-
exports.formatButlerOperationalVisibility = formatButlerOperationalVisibility;
|
|
39
37
|
exports.renderInnerProgressStatus = renderInnerProgressStatus;
|
|
40
38
|
const fs = __importStar(require("fs"));
|
|
41
39
|
const path = __importStar(require("path"));
|
|
42
40
|
const crypto_1 = require("crypto");
|
|
43
41
|
const config_1 = require("../heart/config");
|
|
44
42
|
const identity_1 = require("../heart/identity");
|
|
45
|
-
const
|
|
43
|
+
const active_1 = require("../heart/product/active");
|
|
46
44
|
const session_events_1 = require("../heart/session-events");
|
|
47
45
|
const runtime_1 = require("../nerves/runtime");
|
|
48
46
|
const socket_client_1 = require("../heart/daemon/socket-client");
|
|
@@ -61,15 +59,6 @@ const tool_error_code_1 = require("./tool-error-code");
|
|
|
61
59
|
const tool_arguments_1 = require("./tool-arguments");
|
|
62
60
|
const mail_import_discovery_1 = require("../heart/mail-import-discovery");
|
|
63
61
|
const outbound_1 = require("../senses/voice/outbound");
|
|
64
|
-
const router_1 = require("../heart/external-events/router");
|
|
65
|
-
const steward_policy_1 = require("../heart/steward-policy");
|
|
66
|
-
const await_parser_1 = require("../heart/awaiting/await-parser");
|
|
67
|
-
const daemon_health_1 = require("../heart/daemon/daemon-health");
|
|
68
|
-
const turn_context_1 = require("../heart/turn-context");
|
|
69
|
-
const telegram_effect_adapter_1 = require("../senses/telegram-effect-adapter");
|
|
70
|
-
const telegram_admission_1 = require("../senses/telegram-admission");
|
|
71
|
-
const sanctuary_health_1 = require("../senses/sanctuary-health");
|
|
72
|
-
const run_ledger_1 = require("../heart/run-ledger");
|
|
73
62
|
const NO_SESSION_FOUND_MESSAGE = "no session found for that friend/channel/key combination.";
|
|
74
63
|
const EMPTY_SESSION_MESSAGE = "session exists but has no non-system messages.";
|
|
75
64
|
const VALID_HABIT_SUMMARY_WHICH = new Set(["latest", "previous", "latest-success", "latest-failure"]);
|
|
@@ -400,202 +389,6 @@ async function buildToolActiveWorkFrame(ctx) {
|
|
|
400
389
|
targetCandidates: [],
|
|
401
390
|
});
|
|
402
391
|
}
|
|
403
|
-
function boundedStatusText(value, max = 180) {
|
|
404
|
-
const normalized = value.replace(/\s+/g, " ").trim();
|
|
405
|
-
return normalized.length <= max ? normalized : `${normalized.slice(0, max - 3)}...`;
|
|
406
|
-
}
|
|
407
|
-
function readButlerOperationalVisibility(agentRoot = (0, identity_1.getAgentRoot)(), agentName = (0, identity_1.getAgentName)()) {
|
|
408
|
-
const sourceErrors = {};
|
|
409
|
-
const read = (source, operation, fallback) => {
|
|
410
|
-
try {
|
|
411
|
-
return operation();
|
|
412
|
-
}
|
|
413
|
-
catch (error) {
|
|
414
|
-
sourceErrors[source] = boundedStatusText(error instanceof Error ? error.message : String(error)) || "unknown read failure";
|
|
415
|
-
return fallback;
|
|
416
|
-
}
|
|
417
|
-
};
|
|
418
|
-
const awaitsDir = path.join(agentRoot, "awaiting");
|
|
419
|
-
const awaits = read("awaits", () => fs.existsSync(awaitsDir) ? fs.readdirSync(awaitsDir, { withFileTypes: true })
|
|
420
|
-
.filter((entry) => entry.isFile() && entry.name.endsWith(".md"))
|
|
421
|
-
.map((entry) => {
|
|
422
|
-
const filePath = path.join(awaitsDir, entry.name);
|
|
423
|
-
return (0, await_parser_1.parseAwaitFile)(fs.readFileSync(filePath, "utf8"), filePath);
|
|
424
|
-
})
|
|
425
|
-
.filter((entry) => entry.status === "pending") : [], []);
|
|
426
|
-
const effectsRoot = path.join(agentRoot, "state", "telegram", "effects");
|
|
427
|
-
const telegramEffects = read("telegram_effects", () => {
|
|
428
|
-
if (!fs.existsSync(effectsRoot))
|
|
429
|
-
throw new Error("Telegram effect journal has not been created yet");
|
|
430
|
-
const journal = new telegram_effect_adapter_1.FileTelegramEffectJournal(effectsRoot);
|
|
431
|
-
try {
|
|
432
|
-
return journal.list().map((artifact) => ({
|
|
433
|
-
id: artifact.id,
|
|
434
|
-
authorClass: artifact.authorClass,
|
|
435
|
-
targetKind: artifact.target.kind,
|
|
436
|
-
state: artifact.parts.some((part) => part.state === "indeterminate") ? "indeterminate"
|
|
437
|
-
: artifact.parts.some((part) => part.state === "attempting") ? "attempting"
|
|
438
|
-
: artifact.parts.every((part) => part.state === "session_recorded") ? "session_recorded"
|
|
439
|
-
: artifact.parts.some((part) => part.state === "accepted") ? "accepted"
|
|
440
|
-
: "prepared",
|
|
441
|
-
acceptedAt: artifact.parts.flatMap((part) => part.acceptedAt ? [part.acceptedAt] : []).sort().at(-1) ?? null,
|
|
442
|
-
sessionRecordedAt: artifact.parts.flatMap((part) => part.sessionRecordedAt ? [part.sessionRecordedAt] : []).sort().at(-1) ?? null,
|
|
443
|
-
messageIds: artifact.parts.flatMap((part) => part.messageId ? [part.messageId] : []),
|
|
444
|
-
sessionEventIds: artifact.parts.flatMap((part) => part.sessionEventId ? [part.sessionEventId] : []),
|
|
445
|
-
updatedAt: artifact.updatedAt,
|
|
446
|
-
}));
|
|
447
|
-
}
|
|
448
|
-
finally {
|
|
449
|
-
journal.close();
|
|
450
|
-
}
|
|
451
|
-
}, []);
|
|
452
|
-
const admissionsRoot = path.join(agentRoot, "state", "senses", "telegram", "admissions");
|
|
453
|
-
const telegramAdmissions = read("telegram_admissions", () => {
|
|
454
|
-
if (!fs.existsSync(admissionsRoot))
|
|
455
|
-
throw new Error("Telegram admission store has not been created yet");
|
|
456
|
-
const store = new telegram_admission_1.FileTelegramAdmissionStore(admissionsRoot);
|
|
457
|
-
try {
|
|
458
|
-
return store.list().map((record) => ({ id: record.id, status: record.status, displayCode: record.displayCode, createdAt: record.createdAt, expiresAt: record.expiresAt }));
|
|
459
|
-
}
|
|
460
|
-
finally {
|
|
461
|
-
store.close();
|
|
462
|
-
}
|
|
463
|
-
}, []);
|
|
464
|
-
return {
|
|
465
|
-
agentName,
|
|
466
|
-
externalEvents: read("external_events", () => (0, router_1.listExternalEventStatus)((0, router_1.getExternalEventRoot)()).filter((event) => event.agent === agentName), []),
|
|
467
|
-
stewardPolicy: read("steward_policy", () => (0, steward_policy_1.readStewardPolicy)(agentRoot), { schemaVersion: 1, version: 0, desiredStates: {}, routineActionGrants: {}, updatedAt: null }),
|
|
468
|
-
awaits,
|
|
469
|
-
telegramEffects,
|
|
470
|
-
telegramAdmissions,
|
|
471
|
-
daemonHealth: read("daemon_health", () => {
|
|
472
|
-
const health = (0, daemon_health_1.readHealth)((0, daemon_health_1.getDefaultHealthPath)());
|
|
473
|
-
if (!health)
|
|
474
|
-
throw new Error("daemon health is missing or invalid");
|
|
475
|
-
return health;
|
|
476
|
-
}, null),
|
|
477
|
-
healthState: read("health_state", () => (0, sanctuary_health_1.readSanctuaryHealthState)(path.join(agentRoot, "state", "health", "sanctuary-health.json")), undefined),
|
|
478
|
-
routineActions: read("routine_actions", () => (0, steward_policy_1.readRoutineActionReceipts)(agentRoot), []),
|
|
479
|
-
providerLanes: read("provider", () => {
|
|
480
|
-
const config = (0, identity_1.loadAgentConfig)();
|
|
481
|
-
if (!config.humanFacing || !config.agentFacing)
|
|
482
|
-
throw new Error("provider lanes are unavailable");
|
|
483
|
-
return { outward: config.humanFacing, inner: config.agentFacing };
|
|
484
|
-
}, null),
|
|
485
|
-
lastAutomatedEventRun: read("run_ledger", () => (0, run_ledger_1.readRunLedger)(agentRoot)
|
|
486
|
-
.filter((row) => row.sourceKind === "private-runtime" && row.senseOrHabit === "external-event" && row.lifecycle === "completed")
|
|
487
|
-
.sort((left, right) => (right.endedAt ?? right.recordedAt).localeCompare(left.endedAt ?? left.recordedAt))[0] ?? null, null),
|
|
488
|
-
senseStatusLines: read("senses", () => (0, turn_context_1.readSenseStatusLines)(), []),
|
|
489
|
-
sourceErrors,
|
|
490
|
-
};
|
|
491
|
-
}
|
|
492
|
-
function formatButlerOperationalVisibility(status, options = {}) {
|
|
493
|
-
const section = options.section ?? "all";
|
|
494
|
-
const offset = Math.max(0, options.offset ?? 0);
|
|
495
|
-
const limit = Math.min(20, Math.max(1, options.limit ?? 10));
|
|
496
|
-
const show = (wanted) => section === "all" || section === wanted;
|
|
497
|
-
const page = (rows) => rows.slice(offset, offset + limit);
|
|
498
|
-
const more = (label, total) => total > offset + limit ? ` - ${total - offset - limit} more ${label}; call query_active_work with section=${label}, offset=${offset + limit}, limit=${limit}` : null;
|
|
499
|
-
const daemon = status.daemonHealth;
|
|
500
|
-
const agentHealth = daemon?.agents[status.agentName];
|
|
501
|
-
const lines = ["## butler operational visibility"];
|
|
502
|
-
const error = (source) => status.sourceErrors[source] ? `unavailable (${status.sourceErrors[source]})` : null;
|
|
503
|
-
if (show("health")) {
|
|
504
|
-
lines.push(`- daemon: ${error("daemon_health") ?? daemon?.status ?? "unavailable"}${daemon ? `; mode ${daemon.mode}; pid ${daemon.pid}` : ""}`);
|
|
505
|
-
lines.push(`- butler: ${agentHealth ? `${agentHealth.status}; pid ${agentHealth.pid ?? "none"}; crashes ${agentHealth.crashes}` : "unavailable"}`);
|
|
506
|
-
lines.push("- senses:");
|
|
507
|
-
lines.push(...(error("senses") ? [` - ${error("senses")}`] : status.senseStatusLines.length > 0 ? status.senseStatusLines.map((line) => ` ${line}`) : [" - unavailable"]));
|
|
508
|
-
const health = status.healthState;
|
|
509
|
-
lines.push(`- health sweeps: ${error("health_state") ?? health?.sweepReceipts.length ?? 0}; delivered ${health?.deliveredReceipts.length ?? 0}; indeterminate ${health?.indeterminateDeliveries.length ?? 0}; outbox ${health?.outbox ? `${health.outbox.status}:${health.outbox.id}` : "clear"}; open incidents ${health ? Object.keys(health.incidents).length : 0}; updated ${health?.updatedAt ?? "unavailable"}`);
|
|
510
|
-
const healthRows = [
|
|
511
|
-
...(health?.sweepReceipts ?? []).map((sweep) => ({ at: sweep.completedAt, text: `sweep ${sweep.sweepId}: opened ${sweep.opened}; recovered ${sweep.recovered}; completed ${sweep.completedAt}${sweep.deliveryId ? `; delivery ${sweep.deliveryId}` : ""}` })),
|
|
512
|
-
...(health?.deliveredReceipts ?? []).map((delivery) => ({ at: delivery.deliveredAt, text: `delivered ${delivery.deliveryId}: ${delivery.kind}; messages ${delivery.messageIds.join(",")}; at ${delivery.deliveredAt}` })),
|
|
513
|
-
...(health?.indeterminateDeliveries ?? []).map((delivery) => ({ at: delivery.createdAt, text: `indeterminate ${delivery.id}: ${delivery.kind}; ${delivery.status}; created ${delivery.createdAt}` })),
|
|
514
|
-
].sort((a, b) => b.at.localeCompare(a.at));
|
|
515
|
-
for (const row of page(healthRows))
|
|
516
|
-
lines.push(` - ${row.text}`);
|
|
517
|
-
const overflow = more("health", healthRows.length);
|
|
518
|
-
if (overflow)
|
|
519
|
-
lines.push(overflow);
|
|
520
|
-
}
|
|
521
|
-
if (show("provider"))
|
|
522
|
-
lines.push(`- provider lanes: ${error("provider") ?? (status.providerLanes ? `outward ${status.providerLanes.outward.provider}/${status.providerLanes.outward.model}; inner ${status.providerLanes.inner.provider}/${status.providerLanes.inner.model}` : "unavailable")}`);
|
|
523
|
-
if (show("policy")) {
|
|
524
|
-
lines.push(`- steward policy: ${error("steward_policy") ?? `version ${status.stewardPolicy.version}; ${Object.keys(status.stewardPolicy.desiredStates).length} desired states; ${Object.keys(status.stewardPolicy.routineActionGrants).length} routine grants`}`);
|
|
525
|
-
const entries = [...Object.entries(status.stewardPolicy.desiredStates).map(([key, value]) => ({ key, kind: "desired", value })), ...Object.entries(status.stewardPolicy.routineActionGrants).map(([key, value]) => ({ key, kind: "grant", value }))];
|
|
526
|
-
for (const entry of page(entries)) {
|
|
527
|
-
const expiry = entry.value.expiresAt;
|
|
528
|
-
const active = !expiry || Date.parse(expiry) > Date.now();
|
|
529
|
-
lines.push(entry.kind === "desired" ? ` - ${entry.key} = ${boundedStatusText(entry.value.value)}; ${active ? "active" : "expired"}; ${entry.value.provenance}; source ${boundedStatusText(entry.value.source)}; v${entry.value.version}${expiry ? `; expires ${expiry}` : ""}` : ` - ${entry.key}: ${entry.value.action} on ${entry.value.targets.join(", ")}; ${active ? "active" : "expired"}; max ${entry.value.maxCount}/${entry.value.windowMs}ms; ${entry.value.verificationRequired ? "verification required" : "no verification"}; v${entry.value.version}${expiry ? `; expires ${expiry}` : ""}`);
|
|
530
|
-
}
|
|
531
|
-
const overflow = more("policy", entries.length);
|
|
532
|
-
if (overflow)
|
|
533
|
-
lines.push(overflow);
|
|
534
|
-
}
|
|
535
|
-
if (show("actions")) {
|
|
536
|
-
const actions = [...(status.routineActions ?? [])].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
|
537
|
-
lines.push(`- routine action receipts: ${error("routine_actions") ?? actions.length}`);
|
|
538
|
-
for (const action of page(actions)) {
|
|
539
|
-
const verification = action.state === "verified" ? `verified ${action.verifiedAfterState ?? "state unavailable"}` : action.state === "failed" ? "failed" : action.state === "indeterminate" ? "indeterminate; manual inspection required" : action.state === "recovered_no_effect" ? "no effect occurred" : "pending";
|
|
540
|
-
lines.push(` - ${action.id}: ${action.action} ${action.target}; ${action.state}; updated ${action.updatedAt}; verification ${verification}`);
|
|
541
|
-
}
|
|
542
|
-
const overflow = more("actions", actions.length);
|
|
543
|
-
if (overflow)
|
|
544
|
-
lines.push(overflow);
|
|
545
|
-
}
|
|
546
|
-
if (show("awaits")) {
|
|
547
|
-
lines.push(`- pending awaits: ${status.awaits.length}`);
|
|
548
|
-
if (error("awaits"))
|
|
549
|
-
lines.push(` - ${error("awaits")}`);
|
|
550
|
-
for (const pending of page(status.awaits))
|
|
551
|
-
lines.push(` - ${pending.name}: ${boundedStatusText(pending.condition ?? (pending.body || "condition unavailable"))}${pending.wake_at ? `; wake ${pending.wake_at}` : ""}`);
|
|
552
|
-
const overflow = more("awaits", status.awaits.length);
|
|
553
|
-
if (overflow)
|
|
554
|
-
lines.push(overflow);
|
|
555
|
-
}
|
|
556
|
-
if (show("telegram")) {
|
|
557
|
-
const acceptedTimes = status.telegramEffects.flatMap((effect) => effect.acceptedAt ? [effect.acceptedAt] : []).sort().reverse();
|
|
558
|
-
const recordedTimes = status.telegramEffects.flatMap((effect) => effect.sessionRecordedAt ? [effect.sessionRecordedAt] : []).sort().reverse();
|
|
559
|
-
const legacyAccepted = status.telegramEffects.some((effect) => !effect.acceptedAt && (effect.state === "accepted" || effect.state === "session_recorded"));
|
|
560
|
-
const legacyRecorded = status.telegramEffects.some((effect) => !effect.sessionRecordedAt && effect.state === "session_recorded");
|
|
561
|
-
lines.push(`- latest Telegram accepted: ${acceptedTimes[0] ?? (legacyAccepted ? "timestamp unavailable (legacy artifacts present)" : "none")}; latest session recorded: ${recordedTimes[0] ?? (legacyRecorded ? "timestamp unavailable (legacy artifacts present)" : "none")}`);
|
|
562
|
-
lines.push(`- Telegram effects: ${error("telegram_effects") ?? status.telegramEffects.length}`);
|
|
563
|
-
lines.push(`- Telegram admissions: ${error("telegram_admissions") ?? status.telegramAdmissions.length}`);
|
|
564
|
-
const telegramRows = [
|
|
565
|
-
...status.telegramEffects.map((effect) => ({ at: effect.updatedAt, effect })),
|
|
566
|
-
...status.telegramAdmissions.map((admission) => ({ at: new Date(admission.createdAt).toISOString(), admission })),
|
|
567
|
-
].sort((a, b) => b.at.localeCompare(a.at));
|
|
568
|
-
for (const row of page(telegramRows)) {
|
|
569
|
-
if ("admission" in row) {
|
|
570
|
-
const admission = row.admission;
|
|
571
|
-
lines.push(` - admission ${admission.id}: ${admission.status}; code ${admission.displayCode}; expires ${new Date(admission.expiresAt).toISOString()}`);
|
|
572
|
-
continue;
|
|
573
|
-
}
|
|
574
|
-
const effect = row.effect;
|
|
575
|
-
const accepted = effect.acceptedAt ?? ((effect.state === "accepted" || effect.state === "session_recorded") ? "timestamp unavailable (legacy)" : "not accepted");
|
|
576
|
-
const recorded = effect.sessionRecordedAt ?? (effect.state === "session_recorded" ? "timestamp unavailable (legacy)" : "not recorded");
|
|
577
|
-
lines.push(` - ${effect.id}: ${effect.state}; ${effect.authorClass}; ${effect.targetKind}; accepted ${accepted}; session recorded ${recorded}; message ids ${effect.messageIds?.join(",") || "none"}; session events ${effect.sessionEventIds?.join(",") || "none"}; updated ${effect.updatedAt}`);
|
|
578
|
-
}
|
|
579
|
-
const overflow = more("telegram", telegramRows.length);
|
|
580
|
-
if (overflow)
|
|
581
|
-
lines.push(overflow);
|
|
582
|
-
}
|
|
583
|
-
if (show("events")) {
|
|
584
|
-
const events = [...status.externalEvents].sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
|
|
585
|
-
const completedRun = status.lastAutomatedEventRun;
|
|
586
|
-
lines.push(`- external issues: ${events.length}; last successful automated event turn ${error("run_ledger") ?? (completedRun ? `${completedRun.endedAt ?? completedRun.recordedAt}; run ${completedRun.runId}; target ${completedRun.targetHash}` : "none")}`);
|
|
587
|
-
if (error("external_events"))
|
|
588
|
-
lines.push(` - ${error("external_events")}`);
|
|
589
|
-
for (const event of page(events)) {
|
|
590
|
-
const policy = event.stewardPolicy?.kind === "current" ? `${event.stewardPolicy.key}@${event.stewardPolicy.version}` : "none";
|
|
591
|
-
lines.push(` - ${event.source}/${event.eventType}/${event.eventId}: ${event.executionState}; disposition ${event.classification ?? "pending"}/${event.decision ?? "pending"}; reason ${boundedStatusText(event.reason ?? event.lastError ?? "not yet recorded")}; silence/wake ${event.nextWake ? JSON.stringify(event.nextWake) : "pending"}; steward ${policy}${event.awaitId ? `; await ${event.awaitId}` : ""}${event.careId ? `; care ${event.careId}` : ""}`);
|
|
592
|
-
}
|
|
593
|
-
const overflow = more("events", events.length);
|
|
594
|
-
if (overflow)
|
|
595
|
-
lines.push(overflow);
|
|
596
|
-
}
|
|
597
|
-
return lines.join("\n");
|
|
598
|
-
}
|
|
599
392
|
function findDelegatingBridgeId(ctx) {
|
|
600
393
|
const currentSession = ctx?.currentSession;
|
|
601
394
|
if (!currentSession)
|
|
@@ -653,9 +446,12 @@ exports.sessionToolDefinitions = [
|
|
|
653
446
|
const frame = await buildToolActiveWorkFrame(ctx);
|
|
654
447
|
const activeWork = `this is my current top-level live world-state.\nanswer whole-self status questions from this before drilling into individual sessions.\n\n${(0, active_work_1.formatActiveWorkFrame)(frame)}`;
|
|
655
448
|
const numeric = (value, fallback, min, max) => value === undefined ? fallback : /^\d+$/u.test(value) ? Math.min(max, Math.max(min, Number(value))) : fallback;
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
:
|
|
449
|
+
// The agent's product adds its own sections, such as the Butler's house and Telegram status.
|
|
450
|
+
const sections = await (0, active_1.productActiveWorkSections)({
|
|
451
|
+
agentName: (0, identity_1.getAgentName)(), section: args.section,
|
|
452
|
+
offset: numeric(args.offset, 0, 0, 10_000), limit: numeric(args.limit, 10, 1, 20),
|
|
453
|
+
});
|
|
454
|
+
return sections === null ? activeWork : `${activeWork}\n\n${sections}`;
|
|
659
455
|
},
|
|
660
456
|
riskProfile: { mutates: "none", risk: "low" },
|
|
661
457
|
ax: { id: "tool:query_active_work", group: "turn-sessions", when: "Pick this first for any whole-self status question, to see every live session, coding lane and owed return at once.", effect: "read", idempotent: true, errors: [
|
package/dist/repertoire/tools.js
CHANGED
|
@@ -32,7 +32,7 @@ const tools_bundle_1 = require("./tools-bundle");
|
|
|
32
32
|
const runtime_1 = require("../nerves/runtime");
|
|
33
33
|
const guardrails_1 = require("./guardrails");
|
|
34
34
|
const identity_1 = require("../heart/identity");
|
|
35
|
-
const
|
|
35
|
+
const active_1 = require("../heart/product/active");
|
|
36
36
|
const store_1 = require("../commerce/store");
|
|
37
37
|
const tools_surface_1 = require("./tools-surface");
|
|
38
38
|
const mcp_tools_1 = require("./mcp-tools");
|
|
@@ -51,7 +51,6 @@ const steward_policy_1 = require("../heart/steward-policy");
|
|
|
51
51
|
const relationship_authorization_1 = require("./relationship-authorization");
|
|
52
52
|
const tool_approval_1 = require("../heart/tool-approval");
|
|
53
53
|
const tools_voice_local_1 = require("./tools-voice-local");
|
|
54
|
-
const tools_sanctuary_host_1 = require("./tools-sanctuary-host");
|
|
55
54
|
const cli_manifest_1 = require("../heart/daemon/cli-manifest");
|
|
56
55
|
const cli_gate_1 = require("../heart/daemon/cli-gate");
|
|
57
56
|
function safeGetAgentRoot() {
|
|
@@ -165,13 +164,13 @@ function applyPreference(tool, pref) {
|
|
|
165
164
|
function selectToolsForChannel(capabilities, toolPreferences, _context, providerCapabilities, mcpManager, _chatModel, context) {
|
|
166
165
|
const relationship = context?.relationshipAuthorization;
|
|
167
166
|
const profileId = relationship?.profileId;
|
|
168
|
-
//
|
|
169
|
-
// any future remote sense)
|
|
170
|
-
//
|
|
171
|
-
// loop and the host-local CLI/MCP) keep the unscoped tool set.
|
|
167
|
+
// A product can scope its agent's turns to relationships: every turn that reaches the agent from outside the host
|
|
168
|
+
// (Telegram, A2A, any future remote sense) then gets no tools at all without a known capability profile. Only its
|
|
169
|
+
// own local channels (the inner loop and the host-local CLI/MCP) keep the unscoped tool set.
|
|
172
170
|
const channel = capabilities?.channel;
|
|
173
171
|
const remote = channel !== undefined && !SANCTUARY_LOCAL_CHANNELS.has(channel);
|
|
174
|
-
const
|
|
172
|
+
const product = (0, active_1.productTools)(context?.agentName);
|
|
173
|
+
const sanctuary = (product?.relationshipScoped === true && (relationship !== undefined || remote))
|
|
175
174
|
|| profileId?.startsWith("sanctuary-") === true;
|
|
176
175
|
const owner = profileId === "sanctuary-owner";
|
|
177
176
|
// A trusted peer agent acting for the owner gets the owner's chat tool menu. Host
|
|
@@ -181,8 +180,9 @@ function selectToolsForChannel(capabilities, toolPreferences, _context, provider
|
|
|
181
180
|
const knownSanctuaryProfile = relationship !== undefined && (ownerLike || profileId === "sanctuary-household" || profileId === "sanctuary-event");
|
|
182
181
|
const mcp = mcpManager ? (0, mcp_tools_1.mcpToolsAsDefinitions)(mcpManager) : [];
|
|
183
182
|
const native = [...tools_base_1.baseToolDefinitions, ...additionalDefinitions];
|
|
183
|
+
const productDefinitions = (0, active_1.productToolDefinitions)();
|
|
184
184
|
assertUniqueToolSchemas([
|
|
185
|
-
...native.map((definition) => definition.tool),
|
|
185
|
+
...native.map((definition) => definition.tool), ...productDefinitions.map((definition) => definition.tool), ...mcp.map((definition) => definition.tool),
|
|
186
186
|
tools_flow_1.ponderTool, tools_flow_1.restTool, tools_flow_1.observeTool, tools_flow_1.settleTool, tools_flow_1.speakTool,
|
|
187
187
|
]);
|
|
188
188
|
let ordinary;
|
|
@@ -224,15 +224,25 @@ function selectToolsForChannel(capabilities, toolPreferences, _context, provider
|
|
|
224
224
|
...integrations, ...mcp,
|
|
225
225
|
];
|
|
226
226
|
}
|
|
227
|
-
const
|
|
228
|
-
|
|
229
|
-
:
|
|
230
|
-
|
|
231
|
-
|
|
227
|
+
const added = (0, active_1.productToolSelection)(context?.agentName, {
|
|
228
|
+
channel, relationshipScoped: sanctuary, providerCapabilities,
|
|
229
|
+
context: { ...context, context: _context ?? context?.context },
|
|
230
|
+
registered: (name) => native.find((definition) => definition.tool.function.name === name),
|
|
231
|
+
});
|
|
232
|
+
for (const definition of added) {
|
|
233
|
+
const own = productDefinitions.find((candidate) => candidate.tool.function.name === definition.tool.function.name);
|
|
234
|
+
if (!native.includes(definition) && own?.handler !== definition.handler) {
|
|
235
|
+
(0, runtime_1.emitNervesEvent)({
|
|
236
|
+
level: "error", component: "tools", event: "tool.product_selection_rejected",
|
|
237
|
+
message: "the product selected a tool that isn't registered", meta: { name: definition.tool.function.name },
|
|
238
|
+
});
|
|
239
|
+
throw new ToolSelectionError(`the product selected a tool that isn't registered: ${definition.tool.function.name}`);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
// A product adds to a turn's menu but never widens one core scoped to nothing: a scoped turn without a known profile gets none.
|
|
243
|
+
if (!sanctuary || knownSanctuaryProfile)
|
|
244
|
+
ordinary.push(...added);
|
|
232
245
|
const inner = capabilities?.channel === "inner";
|
|
233
|
-
// The Butler's own scheduled turns (the daily house-care await) carry no relationship, so they cannot take the owner profile's menu.
|
|
234
|
-
if (inner && !sanctuary && (0, butler_agent_1.isButlerAgent)(context?.agentName))
|
|
235
|
-
ordinary.push(...tools_house_care_1.houseCareToolDefinitions);
|
|
236
246
|
const habit = context?.habitSession;
|
|
237
247
|
if (inner) {
|
|
238
248
|
const canSend = habit?.permissionEnvelope.canMessageOutward === true;
|
|
@@ -258,7 +268,7 @@ function selectToolsForChannel(capabilities, toolPreferences, _context, provider
|
|
|
258
268
|
&& (!relationship || relationship.advertisedToolNames.includes(tool.function.name))
|
|
259
269
|
&& (!context?.allowedEngineTools || context.allowedEngineTools.includes(tool.function.name)));
|
|
260
270
|
return Object.freeze({
|
|
261
|
-
ordinary: Object.freeze(ordinary.map((definition) => definition
|
|
271
|
+
ordinary: Object.freeze(ordinary.map((definition) => definition.authorize && definition.authorizesRelationship ? definition : Object.freeze({
|
|
262
272
|
...definition,
|
|
263
273
|
tool: (0, tool_arguments_1.freezeToolValue)(structuredClone(definition.tool)),
|
|
264
274
|
...(definition.riskProfile && typeof definition.riskProfile !== "function"
|
|
@@ -292,7 +302,7 @@ function resolveToolDefinition(toolName, selection) {
|
|
|
292
302
|
}
|
|
293
303
|
/** Every in-turn tool definition the harness registers, before any channel or relationship narrows it. */
|
|
294
304
|
function registeredToolDefinitions() {
|
|
295
|
-
return [...tools_base_1.baseToolDefinitions, ...additionalDefinitions,
|
|
305
|
+
return [...tools_base_1.baseToolDefinitions, ...additionalDefinitions, ...(0, active_1.productToolDefinitions)(), tools_voice_local_1.voiceLocalAudioToolDefinition];
|
|
296
306
|
}
|
|
297
307
|
/** What an unknown tool answers: the real tools its name could mean, else where the real ones are. */
|
|
298
308
|
function unknownToolText(name, selection) {
|
|
@@ -473,15 +483,15 @@ async function preflightToolCall(name, args, ctx) {
|
|
|
473
483
|
if (!validation.ok)
|
|
474
484
|
return { kind: "rejected_before_handler", text: (0, tools_base_1.withCode)(`invalid tool arguments: ${validation.reason}`, "invalid-arguments") };
|
|
475
485
|
}
|
|
476
|
-
// The schema is public, so a malformed call learns its fix before the
|
|
477
|
-
if (
|
|
478
|
-
await
|
|
486
|
+
// The schema is public, so a malformed call learns its fix before the tool's own authority is asked.
|
|
487
|
+
if (def?.authorize)
|
|
488
|
+
await def.authorize(ctx, args);
|
|
479
489
|
(0, tool_arguments_1.assertRelationshipToolOwner)(ctx);
|
|
480
490
|
if (name === "unraid_restart_container" && ctx?.routineActionSelection?.kind === "denied") {
|
|
481
491
|
return { kind: "rejected_before_handler", text: (0, tools_base_1.routineActionDenied)(ctx.routineActionSelection.reason) };
|
|
482
492
|
}
|
|
483
493
|
const relationship = ctx?.relationshipAuthorization;
|
|
484
|
-
const decision =
|
|
494
|
+
const decision = def?.authorize && def.authorizesRelationship ? undefined : await relationship?.authorizeTool(name, args);
|
|
485
495
|
if (decision && (!decision.allowed || !relationship.advertisedToolNames.includes(name)
|
|
486
496
|
|| (decision.profileId !== undefined && decision.profileId !== relationship.profileId))) {
|
|
487
497
|
const reason = decision.allowed ? "current relationship selection changed" : decision.reason;
|
|
@@ -492,11 +502,12 @@ async function preflightToolCall(name, args, ctx) {
|
|
|
492
502
|
return { kind: "rejected_before_handler", text: (0, tools_base_1.withCode)(`relationship authorization required: ${reason}`, "not-allowed") };
|
|
493
503
|
}
|
|
494
504
|
const currentSelection = ctx?.selectCurrentTools?.()
|
|
495
|
-
?? (
|
|
496
|
-
: relationship?.profileId?.startsWith("sanctuary-") || (relationship && (0,
|
|
505
|
+
?? (def?.authorize && def.authorizesRelationship ? selection
|
|
506
|
+
: relationship?.profileId?.startsWith("sanctuary-") || (relationship && (0, active_1.productTools)(ctx?.agentName)?.relationshipScoped)
|
|
497
507
|
? selectToolsForChannel(undefined, undefined, undefined, undefined, undefined, undefined, ctx)
|
|
498
508
|
: undefined);
|
|
499
|
-
const current = currentSelection ? findDefinition(name, currentSelection) : def?.mcpBinding ? def
|
|
509
|
+
const current = currentSelection ? findDefinition(name, currentSelection) : def?.mcpBinding ? def
|
|
510
|
+
: findDefinition(name) ?? (0, active_1.productToolDefinitions)().find((definition) => definition.tool.function.name === name);
|
|
500
511
|
const currentSchema = current?.tool ?? currentSelection?.engine.find((tool) => tool.function.name === name)
|
|
501
512
|
?? (!currentSelection ? selection?.engine.find((tool) => tool.function.name === name) : undefined);
|
|
502
513
|
if (!currentSchema || !(0, node_util_1.isDeepStrictEqual)(schema, currentSchema)
|
|
@@ -39,10 +39,9 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
39
39
|
};
|
|
40
40
|
})();
|
|
41
41
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
42
|
-
exports.erroredTurnReply = void 0;
|
|
42
|
+
exports.getSenseSessionPath = exports.erroredTurnReply = void 0;
|
|
43
43
|
exports.stripThinkBlocks = stripThinkBlocks;
|
|
44
44
|
exports.extractOutwardSenseDeliveryText = extractOutwardSenseDeliveryText;
|
|
45
|
-
exports.getSenseSessionPath = getSenseSessionPath;
|
|
46
45
|
exports.runSenseTurn = runSenseTurn;
|
|
47
46
|
const os = __importStar(require("os"));
|
|
48
47
|
const path = __importStar(require("path"));
|
|
@@ -50,7 +49,8 @@ const fs = __importStar(require("fs"));
|
|
|
50
49
|
const delegated_command_1 = require("../a2a/delegated-command");
|
|
51
50
|
const core_1 = require("../heart/core");
|
|
52
51
|
const identity_1 = require("../heart/identity");
|
|
53
|
-
const
|
|
52
|
+
const session_path_1 = require("../heart/session-path");
|
|
53
|
+
Object.defineProperty(exports, "getSenseSessionPath", { enumerable: true, get: function () { return session_path_1.getSenseSessionPath; } });
|
|
54
54
|
const session_events_1 = require("../heart/session-events");
|
|
55
55
|
const context_1 = require("../mind/context");
|
|
56
56
|
const prompt_1 = require("../mind/prompt");
|
|
@@ -347,9 +347,6 @@ function currentTurnEventView(events, existingEventIds, userMessage, precommitte
|
|
|
347
347
|
const terminal = coordinates.findLast((coordinate) => coordinate.eventIndex === newestAssistantIndex);
|
|
348
348
|
return { coordinates, ...(terminal ? { terminal } : {}) };
|
|
349
349
|
}
|
|
350
|
-
function getSenseSessionPath(agentName, friendId, channel, sessionKey, agentRootOverride) {
|
|
351
|
-
return path.join(agentRootOverride ?? (0, identity_1.getAgentRoot)(agentName), "state", "sessions", friendId, channel, `${(0, config_1.sanitizeKey)(sessionKey)}.json`);
|
|
352
|
-
}
|
|
353
350
|
/**
|
|
354
351
|
* Run a single agent turn through the inbound pipeline.
|
|
355
352
|
* Caller provides channel, session key, friend, and message;
|
|
@@ -436,7 +433,7 @@ async function runSenseTurnExclusive(options, owner) {
|
|
|
436
433
|
fs.mkdirSync(sessionDir, { recursive: true });
|
|
437
434
|
const sessPath = ephemeralRoot
|
|
438
435
|
? path.join(ephemeralRoot, "session.json")
|
|
439
|
-
: getSenseSessionPath(agentName, friendId, channel, sessionKey, agentRoot);
|
|
436
|
+
: (0, session_path_1.getSenseSessionPath)(agentName, friendId, channel, sessionKey, agentRoot);
|
|
440
437
|
const reportedSessionPath = ephemeralRoot ? undefined : sessPath;
|
|
441
438
|
const runWithLease = options._withSessionTurnLease ?? session_transaction_1.withSessionTurnLease;
|
|
442
439
|
try {
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ouro.bot/cli",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.1704",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@ouro.bot/cli",
|
|
9
|
-
"version": "0.1.0-alpha.
|
|
9
|
+
"version": "0.1.0-alpha.1704",
|
|
10
10
|
"bundleDependencies": [
|
|
11
11
|
"@ouro.bot/friends"
|
|
12
12
|
],
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ouro.bot/cli",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.1704",
|
|
4
4
|
"description": "Ouroboros, the agent harness: agents with durable memory that live where you talk (terminal, Teams, iMessage, mail, voice) and use real tools. Start with npx ouro.bot@latest.",
|
|
5
5
|
"homepage": "https://ouroboros.bot/",
|
|
6
6
|
"engines": {
|