@ouro.bot/cli 0.1.0-alpha.1413 → 0.1.0-alpha.1415
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.ouro/mcp/media-mcp.mjs +15 -15
- package/deploy/unraid/sanctuary.xml +1 -1
- package/dist/a2a/approval-relay-forward.js +8 -4
- package/dist/a2a/approval-request-wire.js +123 -0
- package/dist/a2a/client.js +45 -4
- package/dist/senses/telegram-approval-relay.js +47 -1
- package/dist/senses/telegram-client.js +11 -0
- package/dist/senses/telegram-owner-route.js +18 -8
- package/dist/senses/telegram.js +12 -1
- 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.1415",
|
|
6
|
+
"changes": [
|
|
7
|
+
"The Butler's media tools say what happened or what the tool does, instead of giving the agent rules (\"never\", \"do not\"). A test checks every string in the media server and the MCP write guard for those words.",
|
|
8
|
+
"While the relay switch is on, the Butler hands an approval prompt to Ari's primary agent as a sealed request only its harness can open, so Ari can answer it in iMessage. A peer that hangs is given up on after 15 seconds and Ari gets the Telegram card."
|
|
9
|
+
]
|
|
10
|
+
},
|
|
4
11
|
{
|
|
5
12
|
"version": "0.1.0-alpha.1413",
|
|
6
13
|
"changes": [
|
|
@@ -757,7 +757,7 @@ export function diagnose({ shelf, result, chain, entity, kind }) {
|
|
|
757
757
|
percent_complete: result.download.percent_complete,
|
|
758
758
|
detail: items,
|
|
759
759
|
...(neverStarted.length ? { never_started: { likely_fix: "blocklist_and_research", items: neverStarted } } : {}),
|
|
760
|
-
summary: `${facts.join(". ")}.
|
|
760
|
+
summary: `${facts.join(". ")}. Whether to keep waiting, find another release, or give up is the owner's choice: removing a partial download loses its progress, so this leaves it in place.${neverStarted.length ? ` Separately, ${neverStarted.length} download(s) didn't start (${neverStarted.map((i) => i.title ?? "a release").join("; ")}); those can be blocklisted and searched again (blocklist_and_research) without asking.` : ""} media_fill_missing can look for a seeded alternative without deleting the partial first; it removes the partial only after a seeded replacement is grabbed.` }
|
|
761
761
|
}
|
|
762
762
|
const oldest = Math.max(...items.map((i) => i.age_hours))
|
|
763
763
|
return { stuck_stage: "download", stuck_reason: "stalled_no_progress",
|
|
@@ -779,7 +779,7 @@ export function diagnose({ shelf, result, chain, entity, kind }) {
|
|
|
779
779
|
return { stuck_stage: null, stuck_reason: null, likely_fix: null, human_action_required: false,
|
|
780
780
|
percent_complete: pct,
|
|
781
781
|
...(suspected.length ? { stall_suspected: true, detail: suspected } : {}),
|
|
782
|
-
summary: `Downloading now — ${what}${pct === null ? "" : `, ${pct}% done`}, about ${gb} GB to go.${slow.length ? ` Slow but still moving: ${slow.map((i) => `${i.title ?? "a release"} is ${i.percent_complete}% done after ${i.age_hours} hours with an ETA of ${i.timeleft}`).join("; ")}.` : ""}${suspected.length ? ` It reports no ETA after ${Math.max(...suspected.map((i) => i.age_hours))} hours, so it may be stalled; the next check 30 minutes or more later confirms it.
|
|
782
|
+
summary: `Downloading now — ${what}${pct === null ? "" : `, ${pct}% done`}, about ${gb} GB to go.${slow.length ? ` Slow but still moving: ${slow.map((i) => `${i.title ?? "a release"} is ${i.percent_complete}% done after ${i.age_hours} hours with an ETA of ${i.timeleft}`).join("; ")}.` : ""}${suspected.length ? ` It reports no ETA after ${Math.max(...suspected.map((i) => i.age_hours))} hours, so it may be stalled; the next check 30 minutes or more later confirms it. There is no ETA to give yet.` : ""}` }
|
|
783
783
|
}
|
|
784
784
|
if (result.download.errors.length) {
|
|
785
785
|
return { stuck_stage: "download", stuck_reason: "download_client_error", likely_fix: "retry_or_replace_release",
|
|
@@ -808,7 +808,7 @@ export function diagnose({ shelf, result, chain, entity, kind }) {
|
|
|
808
808
|
}
|
|
809
809
|
return { stuck_stage: "import", stuck_reason: "grabbed_but_not_imported", likely_fix: "force_import_scan",
|
|
810
810
|
human_action_required: false,
|
|
811
|
-
summary: `It was grabbed (${result.search.last_grab_title ?? "unknown release"}) but
|
|
811
|
+
summary: `It was grabbed (${result.search.last_grab_title ?? "unknown release"}) but didn't land on the shelf.` }
|
|
812
812
|
}
|
|
813
813
|
|
|
814
814
|
// -------------------------------------------------- tool: diagnose_and_fix
|
|
@@ -816,7 +816,7 @@ export function diagnose({ shelf, result, chain, entity, kind }) {
|
|
|
816
816
|
async function mediaDiagnoseAndFix(a) {
|
|
817
817
|
const before = await mediaRequestStatus({ request_id: a.request_id, tmdb_id: a.tmdb_id, title: a.title })
|
|
818
818
|
if (!before.found) return { result: "no_such_request", before, after: null, human_action_required: true,
|
|
819
|
-
human_action_reason: "Nothing to fix —
|
|
819
|
+
human_action_reason: "Nothing to fix — nobody requested it." }
|
|
820
820
|
const action = a.action ?? (before.diagnosis?.likely_fix ?? "rescan")
|
|
821
821
|
|
|
822
822
|
if (before.diagnosis?.stuck_reason === "acquisition_chain_down" && action !== "report_only") {
|
|
@@ -1092,7 +1092,7 @@ export async function mediaQueue(a) {
|
|
|
1092
1092
|
...(fakes.failed.length ? { fakes_not_cleared: fakes.failed } : {}),
|
|
1093
1093
|
summary: !total ? "Nothing for this is in the Sonarr/Radarr queue."
|
|
1094
1094
|
: `${total} queue row${total === 1 ? "" : "s"}${total > shown.length ? ` (showing ${shown.length})` : ""}; ${shown.filter((r) => r.stalled).length} stalled${shown.some((r) => r.stall?.state === "suspected") ? `, ${shown.filter((r) => r.stall?.state === "suspected").length} suspected (no ETA, to be confirmed by a check 30 minutes later)` : ""}.`,
|
|
1095
|
-
note: "Sonarr/Radarr
|
|
1095
|
+
note: "Sonarr/Radarr don't report seeders or peers. A row stuck at the same percent with no timeleft is the stall signal; for a release's seeder count use media_indexer_search.",
|
|
1096
1096
|
}
|
|
1097
1097
|
}
|
|
1098
1098
|
|
|
@@ -1991,7 +1991,7 @@ async function fillPass(a, seriesId, seriesTitle, { nowMs = Date.now(), deadline
|
|
|
1991
1991
|
const summary = [
|
|
1992
1992
|
`${have.length} of ${base.on_shelf.of} aired episodes are on the shelf; ${wanted.length} monitored ${wanted.length === 1 ? "episode is" : "episodes are"} missing.`,
|
|
1993
1993
|
grabs ? `Grabbed ${grabs} release${grabs === 1 ? "" : "s"} now.` : "",
|
|
1994
|
-
unseeded.length ? `${unseeded.map((x) => x.title).join("; ")} ${unseeded.length === 1 ? "has no seeders: it waits" : "have no seeders: they wait"} for peers and may
|
|
1994
|
+
unseeded.length ? `${unseeded.map((x) => x.title).join("; ")} ${unseeded.length === 1 ? "has no seeders: it waits" : "have no seeders: they wait"} for peers and may not finish.` : "",
|
|
1995
1995
|
moving ? `${moving} download(s) in progress.` : "",
|
|
1996
1996
|
stuck.length ? `${stuck.length} download(s) stalled with no peers and no other usable release (${stuck.map((s) => `${s.title} at ${s.percent}%`).join("; ")}).` : "",
|
|
1997
1997
|
notFound.length ? `No usable release found for ${notFound.map((e) => e.code).join(", ")}.` : "",
|
|
@@ -2006,7 +2006,7 @@ async function fillPass(a, seriesId, seriesTitle, { nowMs = Date.now(), deadline
|
|
|
2006
2006
|
: stuck.length || notFound.length
|
|
2007
2007
|
? "Everything findable is requested; what is still missing is listed with why. Calling media_fill_missing later retries those."
|
|
2008
2008
|
: unseeded.length
|
|
2009
|
-
? "Everything findable is requested; the unseeded grab waits for peers and may
|
|
2009
|
+
? "Everything findable is requested; the unseeded grab waits for peers and may not finish. An await_condition watch can bring this back to media_fill_missing later."
|
|
2010
2010
|
: "Work is in progress: everything findable is requested and downloading. Calling media_fill_missing later imports and confirms it."
|
|
2011
2011
|
const blockedHint = !blockedReport.length ? ""
|
|
2012
2012
|
: ownerRetry ? " The owner's retry could not take the blocklisted release back (see errors and blocklisted_matches)."
|
|
@@ -2061,7 +2061,7 @@ const OWNER_WORDS_NOTE_AUDIT = "claimed by the caller; not verified"
|
|
|
2061
2061
|
const OWNER_WORDS_REQUIRED = { result: "owner_words_required", message: "Pass owner_words with the owner's own words asking for this change (a verbatim quote), or leave dry_run true. Nothing was changed." }
|
|
2062
2062
|
|
|
2063
2063
|
const itemView = (item) => ({ service_id: item.id, title: item.title ?? null, quality_profile_id: item.qualityProfileId ?? null })
|
|
2064
|
-
const UPGRADE_NEXT_STEP = "The profile now allows the upgrade. Call media_search_now (or media_release_search) for the item so Radarr/Sonarr looks for a better release;
|
|
2064
|
+
const UPGRADE_NEXT_STEP = "The profile now allows the upgrade. Call media_search_now (or media_release_search) for the item so Radarr/Sonarr looks for a better release; there is no settings page left for the owner to open."
|
|
2065
2065
|
|
|
2066
2066
|
// Release profiles are the apps' own rules for which releases to take: a release whose title holds an ignored term is never
|
|
2067
2067
|
// grabbed, and one missing a required term is skipped. Writes follow media_quality_profile: dry run first, owner_words to apply.
|
|
@@ -2195,21 +2195,21 @@ const TOOL_LIST = [
|
|
|
2195
2195
|
{
|
|
2196
2196
|
name: "media_search",
|
|
2197
2197
|
annotations: { readOnlyHint: true },
|
|
2198
|
-
description: "Search or browse the household media catalogue. Use `query` for a title lookup: partial and misspelled titles are matched against the library first (Sonarr, Radarr, Jellyfin) and returned as `library_matches` with their kind and service id, and when nothing in the library matches, `lookup_candidates` (TVDB/TMDB) cover titles not in the library. Whether a title is on the shelf, or
|
|
2198
|
+
description: "Search or browse the household media catalogue. Use `query` for a title lookup: partial and misspelled titles are matched against the library first (Sonarr, Radarr, Jellyfin) and returned as `library_matches` with their kind and service id, and when nothing in the library matches, `lookup_candidates` (TVDB/TMDB) cover titles not in the library. Whether a title is on the shelf, or exists at all, comes from a lookup made this turn, not from memory or an earlier reply; a title is missing only when both library_matches and lookup_candidates are empty. Use `genres`/`keywords`/`year_range` to browse by mood (e.g. keywords ['autumn','thanksgiving'] for cozy fall films). `on_shelf: true` restricts to what is already downloaded, `false` to what is not, omit for both. Every item says whether it is on the shelf and carries its tmdb_id so a follow-up media_request needs no second lookup.",
|
|
2199
2199
|
inputSchema: { type: "object", properties: {
|
|
2200
2200
|
query: { type: "string", description: "Title or free text. Omit to browse by filters." },
|
|
2201
2201
|
kind: { type: "string", enum: ["movie", "series", "any"], description: "Default any." },
|
|
2202
2202
|
year_range: { type: "array", items: { type: "number" }, minItems: 2, maxItems: 2, description: "[minYear, maxYear]" },
|
|
2203
2203
|
genres: { type: "array", items: { type: "string" }, description: "TMDB genre names, e.g. ['Romance','Drama']." },
|
|
2204
2204
|
keywords: { type: "array", items: { type: "string" }, description: "TMDB keywords, e.g. ['autumn','small town']. Best lever for mood/vibe requests." },
|
|
2205
|
-
on_shelf: { type: "boolean", description: "true = only what we already have; false = only what we
|
|
2205
|
+
on_shelf: { type: "boolean", description: "true = only what we already have; false = only what we don't; omit = both." },
|
|
2206
2206
|
limit: { type: "number", description: "1-20, default 12." },
|
|
2207
2207
|
sort: { type: "string", enum: ["relevance", "release_year"] },
|
|
2208
2208
|
} },
|
|
2209
2209
|
},
|
|
2210
2210
|
{
|
|
2211
2211
|
name: "media_request",
|
|
2212
|
-
description: "Request a film or series so it gets downloaded. Give tmdb_id when known (from media_search), otherwise title plus optional year. Idempotent: if it was already requested you get approval_state 'already_requested' and duplicate_of
|
|
2212
|
+
description: "Request a film or series so it gets downloaded. Give tmdb_id when known (from media_search), otherwise title plus optional year. Idempotent: if it was already requested you get approval_state 'already_requested' and duplicate_of instead of a second request. Returns the downstream sonarr_id/radarr_id so media_request_status needs no re-resolution. Someone asking is the request: this call makes it, and the reply says what happened, so nobody needs Jellyseerr or another screen to ask for it themselves.",
|
|
2213
2213
|
inputSchema: { type: "object", properties: {
|
|
2214
2214
|
tmdb_id: { type: "number" },
|
|
2215
2215
|
title: { type: "string" },
|
|
@@ -2221,7 +2221,7 @@ const TOOL_LIST = [
|
|
|
2221
2221
|
{
|
|
2222
2222
|
name: "media_request_status",
|
|
2223
2223
|
annotations: { readOnlyHint: true },
|
|
2224
|
-
description: "One call, every stage: request, indexer search, download, file on disk, plus acquisition-chain health and a deterministic `diagnosis` block naming what is stuck, why, and the fix. Use this for any 'is it here yet?' or 'why hasn't X downloaded?' question. A queue row is not proof of progress: a release sitting at zero bytes comes back as stalled, not as downloading.
|
|
2224
|
+
description: "One call, every stage: request, indexer search, download, file on disk, plus acquisition-chain health and a deterministic `diagnosis` block naming what is stuck, why, and the fix. Use this for any 'is it here yet?' or 'why hasn't X downloaded?' question. A queue row is not proof of progress: a release sitting at zero bytes comes back as stalled, not as downloading. diagnosis.summary names the cause from what each stage reports.",
|
|
2225
2225
|
inputSchema: { type: "object", properties: {
|
|
2226
2226
|
request_id: { type: "string", description: "e.g. jellyseerr:42" },
|
|
2227
2227
|
tmdb_id: { type: "number" },
|
|
@@ -2285,7 +2285,7 @@ const TOOL_LIST = [
|
|
|
2285
2285
|
{
|
|
2286
2286
|
name: "media_fill_missing",
|
|
2287
2287
|
_meta: { [TIMEOUT_META_KEY]: 240_000 },
|
|
2288
|
-
description: "Gets a series' missing episodes in one call: it re-reads Sonarr, searches the indexers, grabs the best seeded release for each monitored aired episode (matched by episode title and air year as well as Sonarr's numbering), imports finished downloads, and replaces a stalled download it keeps by itself once a seeded alternative exists, over up to 3 passes in 3 minutes. It
|
|
2288
|
+
description: "Gets a series' missing episodes in one call: it re-reads Sonarr, searches the indexers, grabs the best seeded release for each monitored aired episode (matched by episode title and air year as well as Sonarr's numbering), imports finished downloads, and replaces a stalled download it keeps by itself once a seeded alternative exists, over up to 3 passes in 3 minutes. It leaves what is already in flight alone. Returns on_shelf, in_flight, not_found, actions, indexer_evidence, summary and next_step; goal_met is true when nothing is left to get, and blocklisted_matches lists episodes whose only release is blocklisted.",
|
|
2289
2289
|
inputSchema: { type: "object", properties: {
|
|
2290
2290
|
series: { type: "string", description: "Series title as the owner said it." },
|
|
2291
2291
|
service_id: { type: "number", description: "Sonarr series id, when known." },
|
|
@@ -2373,7 +2373,7 @@ const TOOL_LIST = [
|
|
|
2373
2373
|
},
|
|
2374
2374
|
{
|
|
2375
2375
|
name: "media_quality_profile",
|
|
2376
|
-
description: "Read and change the Radarr/Sonarr quality profiles that decide whether a better release may replace a file ('Quality Profile does not allow upgrades').
|
|
2376
|
+
description: "Read and change the Radarr/Sonarr quality profiles that decide whether a better release may replace a file ('Quality Profile does not allow upgrades'). It works through the apps' API, with no settings screen for the owner to click through. action read (default) lists the profiles for the kind with their cutoff, upgrade flag and ordered qualities, or one profile with profile_id; add service_id to also see which profile a movie or series is on. action set_upgrade changes upgrade_allowed and/or the cutoff (a quality id from the profile, or cutoff_name) of profile_id. action assign puts the movie or series service_id on profile_id. Both writes are a dry run that shows before and after and changes nothing until dry_run is false; a change to a shared profile affects every title on it, so prefer assign to move one title when the owner asked about one title. When the owner's words ask for the change, apply it, then report the before and after in one line. Applying takes owner_words, the owner's words asking for the change. After an applied change, call media_search_now so the upgrade is searched for.",
|
|
2377
2377
|
inputSchema: { type: "object", properties: {
|
|
2378
2378
|
kind: { type: "string", enum: ["movie", "series"], description: "movie = Radarr, series = Sonarr." },
|
|
2379
2379
|
action: { type: "string", enum: ["read", "set_upgrade", "assign"], description: "Default read." },
|
|
@@ -2389,7 +2389,7 @@ const TOOL_LIST = [
|
|
|
2389
2389
|
},
|
|
2390
2390
|
{
|
|
2391
2391
|
name: "media_release_profile",
|
|
2392
|
-
description: "Read and set the Radarr/Sonarr release profiles: the apps' own standing rules for which releases to take. A release whose title holds an ignored term
|
|
2392
|
+
description: "Read and set the Radarr/Sonarr release profiles: the apps' own standing rules for which releases to take. A release whose title holds an ignored term isn't grabbed; one missing a required term is skipped. Use it for household rules such as turning down fake releases that are programs (ignored: a regex like /\\.(exe|scr|bat|msi)$/i, end-anchored so titles like Scream or Batman stay fine). action read (default) lists them. action set creates or changes the profile called name; ignored and required replace that list when given. A set is a dry run showing before and after until dry_run is false; applying takes owner_words, the owner's words asking for it. The fake-release rule in media_queue runs regardless; this keeps such releases from being grabbed at all.",
|
|
2393
2393
|
inputSchema: { type: "object", properties: {
|
|
2394
2394
|
kind: { type: "string", enum: ["movie", "series"], description: "movie = Radarr, series = Sonarr." },
|
|
2395
2395
|
action: { type: "string", enum: ["read", "set"], description: "Default read." },
|
|
@@ -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.1415</Repository>
|
|
5
5
|
<Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
|
|
6
6
|
<Network>host</Network>
|
|
7
7
|
<Shell>sh</Shell>
|
|
@@ -53,8 +53,10 @@ function approvalRelaySocketPath(agentRoot) {
|
|
|
53
53
|
exports.RELAY_REPLY = /^(denied|already_decided|expired|not_pending|refused:[a-z0-9_]{1,64})$/;
|
|
54
54
|
exports.RELAY_UNAVAILABLE = "refused:relay_unavailable";
|
|
55
55
|
/**
|
|
56
|
-
* The
|
|
57
|
-
*
|
|
56
|
+
* The answer reached the Telegram process, which didn't reply: it took too long (usually a tap holds the approval's lock)
|
|
57
|
+
* or closed without a word (say the card edit failed after the deny was written). The deny may have landed or may still
|
|
58
|
+
* land, so this is not a refusal: the sender should tell Ari to check the card. A door at its connection limit also
|
|
59
|
+
* closes without a word; "check the card" is still true then.
|
|
58
60
|
*/
|
|
59
61
|
exports.RELAY_TIMED_OUT = "timed_out";
|
|
60
62
|
/** The one reply for a sender that isn't the owner route's peer, so nobody else learns how the relay is set up. */
|
|
@@ -97,8 +99,10 @@ async function forwardApprovalAnswer(input) {
|
|
|
97
99
|
}
|
|
98
100
|
finish(typeof parsed === "string" && exports.RELAY_REPLY.test(parsed) ? parsed : exports.RELAY_UNAVAILABLE);
|
|
99
101
|
});
|
|
100
|
-
|
|
101
|
-
|
|
102
|
+
// Once the answer is sent, a connection that ends without a reply leaves its outcome unknown, not refused.
|
|
103
|
+
const ended = () => finish(sent ? exports.RELAY_TIMED_OUT : exports.RELAY_UNAVAILABLE);
|
|
104
|
+
socket.on("close", ended);
|
|
105
|
+
socket.on("error", ended);
|
|
102
106
|
});
|
|
103
107
|
// The level is worked out first: the nerves source scanner reads a call's object only up to its first "})".
|
|
104
108
|
const level = reply === exports.RELAY_UNAVAILABLE || reply === exports.RELAY_TIMED_OUT ? "warn" : "info";
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MAX_ACTION_LINE_CHARS = exports.RELAY_CODE_ALPHABET = exports.APPROVAL_REQUEST_ACCEPTED = exports.APPROVAL_REQUEST_KIND = void 0;
|
|
4
|
+
exports.isApprovalRequestPayload = isApprovalRequestPayload;
|
|
5
|
+
exports.approvalActionLine = approvalActionLine;
|
|
6
|
+
exports.newRelayCode = newRelayCode;
|
|
7
|
+
exports.sealApprovalRequest = sealApprovalRequest;
|
|
8
|
+
exports.isApprovalRequestMessage = isApprovalRequestMessage;
|
|
9
|
+
exports.openApprovalRequest = openApprovalRequest;
|
|
10
|
+
/**
|
|
11
|
+
* The approval relay's request: what the Butler's harness hands Ari's primary agent's harness when it routes an
|
|
12
|
+
* approval prompt with the relay switch on (design v3, flow step 1). It carries the relay token, so no model may ever
|
|
13
|
+
* read it (security review C1c).
|
|
14
|
+
*
|
|
15
|
+
* - The payload is sealed and signed as a friends `message`, so it is confidential and tamper-evident over any
|
|
16
|
+
* transport, and the receiver opens it with `openChatMessage`, pinned to the Butler's DID.
|
|
17
|
+
* - It travels in a harness-owned DataPart tagged `ouroKind: "approval_request"`. The sealed blob sits under `request`,
|
|
18
|
+
* not at the top of the part, so a receiver that doesn't know the tag finds no friends part there and refuses the
|
|
19
|
+
* message as malformed. It never opens it as a chat and shows the token to its model.
|
|
20
|
+
*/
|
|
21
|
+
const a2a_client_1 = require("@ouro.bot/friends/a2a-client");
|
|
22
|
+
const friends_1 = require("@ouro.bot/friends");
|
|
23
|
+
const runtime_1 = require("../nerves/runtime");
|
|
24
|
+
const sealed_chat_1 = require("./sealed-chat");
|
|
25
|
+
exports.APPROVAL_REQUEST_KIND = "approval_request";
|
|
26
|
+
/** The sealed text the peer's harness answers with once it holds the request. */
|
|
27
|
+
exports.APPROVAL_REQUEST_ACCEPTED = "approval_request: accepted";
|
|
28
|
+
const PAYLOAD_TAG = "ouro.approval-request.v1";
|
|
29
|
+
/** Four characters from an alphabet without look-alikes (no 0, O, 1, I or L), so Ari can read and type it. */
|
|
30
|
+
exports.RELAY_CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";
|
|
31
|
+
const CODE = new RegExp(`^[${exports.RELAY_CODE_ALPHABET}]{4}$`);
|
|
32
|
+
const RELAY_TOKEN = /^[A-Za-z0-9_-]{16,128}$/;
|
|
33
|
+
const ISO = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?Z$/;
|
|
34
|
+
/** Shown to Ari as plain text: one line, capped, with no control or bidi characters. */
|
|
35
|
+
exports.MAX_ACTION_LINE_CHARS = 300;
|
|
36
|
+
// eslint-disable-next-line no-control-regex -- the point is to find control characters
|
|
37
|
+
const UNSAFE_CHARS = /[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u;
|
|
38
|
+
/** True only for exactly the v1 payload's fields, each well formed. */
|
|
39
|
+
function isApprovalRequestPayload(value) {
|
|
40
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
41
|
+
return false;
|
|
42
|
+
const v = value;
|
|
43
|
+
return Object.keys(v).sort().join(",") === "actionLine,code,decisions,expiresAt,relayToken"
|
|
44
|
+
&& typeof v.relayToken === "string" && RELAY_TOKEN.test(v.relayToken)
|
|
45
|
+
&& typeof v.code === "string" && CODE.test(v.code)
|
|
46
|
+
&& typeof v.actionLine === "string" && v.actionLine.trim().length > 0 && v.actionLine.length <= exports.MAX_ACTION_LINE_CHARS && !UNSAFE_CHARS.test(v.actionLine)
|
|
47
|
+
&& Array.isArray(v.decisions) && v.decisions.length === 1 && v.decisions[0] === "deny"
|
|
48
|
+
&& typeof v.expiresAt === "string" && ISO.test(v.expiresAt) && Number.isFinite(Date.parse(v.expiresAt));
|
|
49
|
+
}
|
|
50
|
+
/** The Butler's prompt as one safe line: control and bidi characters become spaces, then it's trimmed and capped. */
|
|
51
|
+
function approvalActionLine(prompt) {
|
|
52
|
+
const flat = prompt.replace(new RegExp(UNSAFE_CHARS.source, "gu"), " ").replace(/\s+/gu, " ").trim();
|
|
53
|
+
const line = flat.length > 0 ? flat : "Approval request";
|
|
54
|
+
return line.length > exports.MAX_ACTION_LINE_CHARS ? `${line.slice(0, exports.MAX_ACTION_LINE_CHARS - 1)}…` : line;
|
|
55
|
+
}
|
|
56
|
+
/** A fresh code for one routed item. */
|
|
57
|
+
function newRelayCode(randomBytes) {
|
|
58
|
+
// 31 symbols: rejection sampling keeps every symbol equally likely.
|
|
59
|
+
let code = "";
|
|
60
|
+
while (code.length < 4) {
|
|
61
|
+
for (const byte of randomBytes(8)) {
|
|
62
|
+
if (code.length === 4)
|
|
63
|
+
break;
|
|
64
|
+
if (byte < 248)
|
|
65
|
+
code += exports.RELAY_CODE_ALPHABET[byte % exports.RELAY_CODE_ALPHABET.length];
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return code;
|
|
69
|
+
}
|
|
70
|
+
/** Seal a request to the recipient and wrap it in the tagged part. Throws on a malformed payload. */
|
|
71
|
+
function sealApprovalRequest(input) {
|
|
72
|
+
if (!isApprovalRequestPayload(input.payload))
|
|
73
|
+
throw new Error("approval request payload is malformed");
|
|
74
|
+
const prepared = (0, friends_1.prepareMessage)({ fromAgentId: input.from.did, text: JSON.stringify({ [PAYLOAD_TAG]: input.payload }) });
|
|
75
|
+
/* v8 ignore next -- the text is a short JSON object and the sender DID comes from a real identity @preserve */
|
|
76
|
+
if (!prepared.ok)
|
|
77
|
+
throw new Error(`cannot prepare approval request: ${prepared.status}`);
|
|
78
|
+
const sealed = (0, a2a_client_1.sealEnvelope)({
|
|
79
|
+
sodium: input.sodium,
|
|
80
|
+
envelope: prepared.envelope,
|
|
81
|
+
friendsKind: "message",
|
|
82
|
+
fromIdentity: input.from,
|
|
83
|
+
recipientDid: input.recipientDid,
|
|
84
|
+
recipientX25519Pub: (0, a2a_client_1.keyAgreementFromDidKey)({ sodium: input.sodium, ed25519Pub: input.recipientEd25519Pub }),
|
|
85
|
+
});
|
|
86
|
+
(0, runtime_1.emitNervesEvent)({ component: "channels", event: "channel.a2a_approval_request_sealed", message: "sealed an approval request for the owner route", meta: { recipientDid: input.recipientDid } });
|
|
87
|
+
return { parts: [{ kind: "data", data: { ouroKind: exports.APPROVAL_REQUEST_KIND, recipientDid: input.recipientDid, request: { v: sealed.v, sealed: sealed.sealed } } }] };
|
|
88
|
+
}
|
|
89
|
+
/** Whether a message is exactly one tagged approval-request part. */
|
|
90
|
+
function isApprovalRequestMessage(message) {
|
|
91
|
+
if (!Array.isArray(message.parts) || message.parts.length !== 1)
|
|
92
|
+
return false;
|
|
93
|
+
const part = message.parts[0];
|
|
94
|
+
return !!part && part.kind === "data" && typeof part.data === "object" && part.data !== null
|
|
95
|
+
&& part.data.ouroKind === exports.APPROVAL_REQUEST_KIND;
|
|
96
|
+
}
|
|
97
|
+
/** Open a tagged request from the expected sender: the same `openChatMessage` path, then a strict payload check. */
|
|
98
|
+
async function openApprovalRequest(input) {
|
|
99
|
+
const refuse = (reason) => {
|
|
100
|
+
(0, runtime_1.emitNervesEvent)({ level: "warn", component: "channels", event: "channel.a2a_approval_request_refused", message: "refused an approval request", meta: { senderDid: input.senderDid, reason } });
|
|
101
|
+
return { ok: false, reason };
|
|
102
|
+
};
|
|
103
|
+
if (!isApprovalRequestMessage(input.message))
|
|
104
|
+
return refuse("not_an_approval_request");
|
|
105
|
+
const data = input.message.parts[0].data;
|
|
106
|
+
if (typeof data.recipientDid !== "string" || !data.request || typeof data.request !== "object" || typeof data.request.v !== "number")
|
|
107
|
+
return refuse("malformed_request");
|
|
108
|
+
const friendsMessage = { ...input.message, parts: [{ kind: "data", data: { v: data.request.v, sealed: data.request.sealed, recipientDid: data.recipientDid } }] };
|
|
109
|
+
const opened = await (0, sealed_chat_1.openChatMessage)({ ...input, message: friendsMessage });
|
|
110
|
+
if (!opened.ok)
|
|
111
|
+
return refuse(opened.reason);
|
|
112
|
+
let payload;
|
|
113
|
+
try {
|
|
114
|
+
payload = JSON.parse(opened.text)[PAYLOAD_TAG];
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
payload = undefined;
|
|
118
|
+
}
|
|
119
|
+
if (!isApprovalRequestPayload(payload))
|
|
120
|
+
return refuse("malformed_request");
|
|
121
|
+
(0, runtime_1.emitNervesEvent)({ component: "channels", event: "channel.a2a_approval_request_opened", message: "opened a verified approval request", meta: { senderDid: input.senderDid } });
|
|
122
|
+
return { ok: true, payload, issuedAt: opened.issuedAt };
|
|
123
|
+
}
|
package/dist/a2a/client.js
CHANGED
|
@@ -10,9 +10,11 @@ exports.sendA2AMessage = sendA2AMessage;
|
|
|
10
10
|
exports.postA2AMessageEnvelope = postA2AMessageEnvelope;
|
|
11
11
|
exports.getA2ATask = getA2ATask;
|
|
12
12
|
exports.sendSealedA2AChat = sendSealedA2AChat;
|
|
13
|
+
exports.sendSealedApprovalRequest = sendSealedApprovalRequest;
|
|
13
14
|
const node_crypto_1 = require("node:crypto");
|
|
14
15
|
const a2a_client_1 = require("@ouro.bot/friends/a2a-client");
|
|
15
16
|
const runtime_1 = require("../nerves/runtime");
|
|
17
|
+
const approval_request_wire_1 = require("./approval-request-wire");
|
|
16
18
|
const sealed_chat_1 = require("./sealed-chat");
|
|
17
19
|
/** The trimmed `did:key` a card serves, or undefined when the card is did-less. */
|
|
18
20
|
function cardDid(card) {
|
|
@@ -28,14 +30,14 @@ function endpointForCard(card) {
|
|
|
28
30
|
const legacyJsonRpc = card.additionalInterfaces?.find((entry) => entry.transport.toUpperCase() === "JSONRPC");
|
|
29
31
|
return legacyJsonRpc?.url ?? card.url;
|
|
30
32
|
}
|
|
31
|
-
async function fetchA2AAgentCard(cardUrl, fetchImpl = fetch) {
|
|
33
|
+
async function fetchA2AAgentCard(cardUrl, fetchImpl = fetch, signal) {
|
|
32
34
|
(0, runtime_1.emitNervesEvent)({
|
|
33
35
|
component: "channels",
|
|
34
36
|
event: "channel.a2a_card_fetch_start",
|
|
35
37
|
message: "fetching A2A agent card",
|
|
36
38
|
meta: { cardUrl },
|
|
37
39
|
});
|
|
38
|
-
const response = await fetchImpl(cardUrl);
|
|
40
|
+
const response = await (signal ? fetchImpl(cardUrl, { signal }) : fetchImpl(cardUrl));
|
|
39
41
|
if (!response.ok) {
|
|
40
42
|
throw new Error(`A2A card fetch failed (${response.status} ${response.statusText})`);
|
|
41
43
|
}
|
|
@@ -80,6 +82,7 @@ async function postJsonRpc(endpointUrl, request, fetchImpl, protocolVersion = "1
|
|
|
80
82
|
method: "POST",
|
|
81
83
|
headers: { "content-type": "application/json", "A2A-Version": protocolVersion },
|
|
82
84
|
body: JSON.stringify(request),
|
|
85
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
83
86
|
});
|
|
84
87
|
if (!response.ok) {
|
|
85
88
|
// A JSON-RPC body on a non-2xx status is still the peer's answer (the server sends 400 and 413 that way).
|
|
@@ -249,7 +252,7 @@ async function getA2ATask(input) {
|
|
|
249
252
|
async function sendSealedA2AChat(input) {
|
|
250
253
|
const fetchImpl = input.fetchImpl ?? fetch;
|
|
251
254
|
const sodium = input.sodium ?? await (0, a2a_client_1.ready)();
|
|
252
|
-
const card = await fetchA2AAgentCard(input.cardUrl, fetchImpl);
|
|
255
|
+
const card = await fetchA2AAgentCard(input.cardUrl, fetchImpl, input.signal);
|
|
253
256
|
const peerDid = cardDid(card);
|
|
254
257
|
if (!peerDid)
|
|
255
258
|
throw new Error(`A2A card ${input.cardUrl} serves no DID; sealed chat needs one`);
|
|
@@ -275,7 +278,7 @@ async function sendSealedA2AChat(input) {
|
|
|
275
278
|
params: { message: { kind: "message", role: "ROLE_USER", messageId: (0, node_crypto_1.randomUUID)(), contextId: conversationId, parts: sealed.parts } },
|
|
276
279
|
};
|
|
277
280
|
(0, runtime_1.emitNervesEvent)({ component: "channels", event: "channel.a2a_chat_send_start", message: "sending sealed A2A chat message", meta: { endpointUrl, peerDid } });
|
|
278
|
-
const rpc = await postJsonRpc(endpointUrl, request, fetchImpl);
|
|
281
|
+
const rpc = await postJsonRpc(endpointUrl, request, fetchImpl, "1.0", input.signal ? { signal: input.signal } : {});
|
|
279
282
|
if ("error" in rpc)
|
|
280
283
|
throw new A2ARpcError(rpc.error);
|
|
281
284
|
const task = rpc.result;
|
|
@@ -288,3 +291,41 @@ async function sendSealedA2AChat(input) {
|
|
|
288
291
|
(0, runtime_1.emitNervesEvent)({ component: "channels", event: "channel.a2a_chat_send_end", message: "received sealed A2A chat reply", meta: { endpointUrl, peerDid, taskId: task.id } });
|
|
289
292
|
return { text: opened.text, conversationId, taskId: task.id, peerDid, peerName: card.name };
|
|
290
293
|
}
|
|
294
|
+
/**
|
|
295
|
+
* Hand one approval request to the owner route's peer (the approval relay, design v3 step 1). The request is a single
|
|
296
|
+
* sealed `approval_request` part with no text, so no model reads it on the way. The peer's harness answers with a sealed
|
|
297
|
+
* `APPROVAL_REQUEST_ACCEPTED`; any other answer throws, so the caller treats the peer as unreachable and Ari gets the
|
|
298
|
+
* card with a sound.
|
|
299
|
+
*/
|
|
300
|
+
async function sendSealedApprovalRequest(input) {
|
|
301
|
+
const fetchImpl = input.fetchImpl ?? fetch;
|
|
302
|
+
const sodium = input.sodium ?? await (0, a2a_client_1.ready)();
|
|
303
|
+
const card = await fetchA2AAgentCard(input.cardUrl, fetchImpl, input.signal);
|
|
304
|
+
const served = cardDid(card);
|
|
305
|
+
const parsed = served === input.peerDid ? (0, a2a_client_1.parseDidKey)(served) : null;
|
|
306
|
+
if (!parsed || !(0, a2a_client_1.verifyCardDidBinding)({ card: { did: input.peerDid, url: input.cardUrl }, did: input.peerDid, didDoc: null })) {
|
|
307
|
+
throw new Error(`A2A card ${input.cardUrl} doesn't serve the pinned ${input.peerDid}`);
|
|
308
|
+
}
|
|
309
|
+
const endpointUrl = endpointForCard(card);
|
|
310
|
+
const sealed = (0, approval_request_wire_1.sealApprovalRequest)({ sodium, from: input.identity, recipientDid: input.peerDid, recipientEd25519Pub: parsed.ed25519Pub, payload: input.payload });
|
|
311
|
+
const request = {
|
|
312
|
+
jsonrpc: "2.0",
|
|
313
|
+
id: (0, node_crypto_1.randomUUID)(),
|
|
314
|
+
method: "SendMessage",
|
|
315
|
+
params: { message: { kind: "message", role: "ROLE_USER", messageId: (0, node_crypto_1.randomUUID)(), contextId: (0, node_crypto_1.randomUUID)(), parts: sealed.parts } },
|
|
316
|
+
};
|
|
317
|
+
(0, runtime_1.emitNervesEvent)({ component: "channels", event: "channel.a2a_approval_request_send_start", message: "handing an approval request to the owner route's peer", meta: { endpointUrl, peerDid: input.peerDid } });
|
|
318
|
+
const rpc = await postJsonRpc(endpointUrl, request, fetchImpl, "1.0", input.signal ? { signal: input.signal } : {});
|
|
319
|
+
if ("error" in rpc)
|
|
320
|
+
throw new A2ARpcError(rpc.error);
|
|
321
|
+
const replyMessage = rpc.result?.status?.message;
|
|
322
|
+
if (!replyMessage)
|
|
323
|
+
throw new Error("A2A approval request returned no reply message");
|
|
324
|
+
const opened = await (0, sealed_chat_1.openChatMessage)({ sodium, self: input.identity, message: replyMessage, senderDid: input.peerDid, senderEd25519Pub: parsed.ed25519Pub });
|
|
325
|
+
if (!opened.ok)
|
|
326
|
+
throw replyRefusedError("approval request", opened.reason);
|
|
327
|
+
// The peer's words are not logged: only how long they were.
|
|
328
|
+
if (opened.text !== approval_request_wire_1.APPROVAL_REQUEST_ACCEPTED)
|
|
329
|
+
throw new Error(`the peer didn't take the approval request (it answered ${opened.text.length} characters)`);
|
|
330
|
+
(0, runtime_1.emitNervesEvent)({ component: "channels", event: "channel.a2a_approval_request_send_end", message: "the owner route's peer took the approval request", meta: { endpointUrl, peerDid: input.peerDid } });
|
|
331
|
+
}
|
|
@@ -38,6 +38,8 @@ exports.relayAnswerSeenLedger = relayAnswerSeenLedger;
|
|
|
38
38
|
exports.handleRelayedApprovalAnswer = handleRelayedApprovalAnswer;
|
|
39
39
|
exports.startApprovalRelaySocket = startApprovalRelaySocket;
|
|
40
40
|
exports.createApprovalRelayDoor = createApprovalRelayDoor;
|
|
41
|
+
exports.ownerRouteDid = ownerRouteDid;
|
|
42
|
+
exports.approvalRelayRequestFor = approvalRelayRequestFor;
|
|
41
43
|
/**
|
|
42
44
|
* The Telegram sense's door for a relayed approval answer. The A2A process forwards the raw sealed message here,
|
|
43
45
|
* over `state/approvals/relay/sock`, without opening it. This process opens it and checks it, then decides it under
|
|
@@ -56,9 +58,11 @@ exports.createApprovalRelayDoor = createApprovalRelayDoor;
|
|
|
56
58
|
const fs = __importStar(require("node:fs"));
|
|
57
59
|
const net = __importStar(require("node:net"));
|
|
58
60
|
const path = __importStar(require("node:path"));
|
|
61
|
+
const node_crypto_1 = require("node:crypto");
|
|
59
62
|
const a2a_client_1 = require("@ouro.bot/friends/a2a-client");
|
|
60
63
|
const approval_relay_1 = require("../a2a/approval-relay");
|
|
61
64
|
const approval_relay_forward_1 = require("../a2a/approval-relay-forward");
|
|
65
|
+
const approval_request_wire_1 = require("../a2a/approval-request-wire");
|
|
62
66
|
const identity_1 = require("../a2a/identity");
|
|
63
67
|
const operator_trust_1 = require("../a2a/operator-trust");
|
|
64
68
|
const identity_2 = require("../heart/identity");
|
|
@@ -225,7 +229,7 @@ function createApprovalRelayDoor(input) {
|
|
|
225
229
|
sodium,
|
|
226
230
|
// A failed load is forgotten, so the next answer tries again instead of failing forever.
|
|
227
231
|
self: () => (identity ??= loadIdentity().catch((error) => { identity = undefined; throw error; })),
|
|
228
|
-
routeDid: () => (
|
|
232
|
+
routeDid: () => ownerRouteDid(input.agentName, input.agentRoot),
|
|
229
233
|
runtime: input.runtime,
|
|
230
234
|
seen: relayAnswerSeenLedger(input.agentRoot),
|
|
231
235
|
};
|
|
@@ -245,3 +249,45 @@ function createApprovalRelayDoor(input) {
|
|
|
245
249
|
},
|
|
246
250
|
};
|
|
247
251
|
}
|
|
252
|
+
/** The owner route's pinned DID from `agent.json` (`senses.telegram.ownerNoticesTo.did`), if it has one. */
|
|
253
|
+
function ownerRouteDid(agentName, agentRoot) {
|
|
254
|
+
return (0, identity_2.loadAgentConfig)({ agentName, agentRoot }).senses?.telegram.ownerNoticesTo?.did;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* The request the owner route hands the peer's harness for a tool approval's card that is being sent now (design v3,
|
|
258
|
+
* step 1), or none. None unless the trust-folder switch is on and names the route's own DID, and the transport still
|
|
259
|
+
* holds the card's decision token. Admission cards never get one: v1 relays tool approvals only.
|
|
260
|
+
*/
|
|
261
|
+
function approvalRelayRequestFor(input) {
|
|
262
|
+
const now = (input.now ?? (() => new Date()))();
|
|
263
|
+
const relaySwitch = (0, approval_relay_1.readApprovalRelaySwitch)(input.agentRoot, now);
|
|
264
|
+
if (!relaySwitch.on)
|
|
265
|
+
return undefined;
|
|
266
|
+
const skip = (reason) => {
|
|
267
|
+
(0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.telegram_relay_request_skipped", message: "sent the approval without a relay request; Ari can still tap", meta: { reason } });
|
|
268
|
+
return undefined;
|
|
269
|
+
};
|
|
270
|
+
// A config that can't be read leaves the card as it would be without the relay; it never stops the card.
|
|
271
|
+
let routeDid;
|
|
272
|
+
try {
|
|
273
|
+
routeDid = input.routeDid();
|
|
274
|
+
}
|
|
275
|
+
catch {
|
|
276
|
+
return skip("route_unreadable");
|
|
277
|
+
}
|
|
278
|
+
if (routeDid !== relaySwitch.did)
|
|
279
|
+
return skip(routeDid === undefined ? "no_owner_route" : "route_mismatch");
|
|
280
|
+
const held = input.transport?.approvalRelayRequest?.({ approvalId: input.approvalId, routeDid });
|
|
281
|
+
if (!held)
|
|
282
|
+
return skip("no_decision_token");
|
|
283
|
+
if (held.expiresAt <= now.getTime())
|
|
284
|
+
return skip("expired");
|
|
285
|
+
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.telegram_relay_request_prepared", message: "prepared an approval relay request for the owner route", meta: { routeDid } });
|
|
286
|
+
return {
|
|
287
|
+
relayToken: held.relayToken,
|
|
288
|
+
code: (0, approval_request_wire_1.newRelayCode)(input.randomBytes ?? ((size) => (0, node_crypto_1.randomBytes)(size))),
|
|
289
|
+
actionLine: (0, approval_request_wire_1.approvalActionLine)(held.prompt),
|
|
290
|
+
decisions: ["deny"],
|
|
291
|
+
expiresAt: new Date(held.expiresAt).toISOString(),
|
|
292
|
+
};
|
|
293
|
+
}
|
|
@@ -1466,6 +1466,17 @@ function createTelegramApprovalTransport(options) {
|
|
|
1466
1466
|
return handleUpdateUnlocked(update, observedAt);
|
|
1467
1467
|
},
|
|
1468
1468
|
reconcileExpired,
|
|
1469
|
+
approvalRelayRequest(input) {
|
|
1470
|
+
const pending = uniquePending().find((record) => record.approvalId === input.approvalId);
|
|
1471
|
+
if (!pending || pending.deliveryState !== "send_attempting" || !pending.decisionToken || pending.decisionToken.length < approval_relay_1.MIN_RELAY_KEY_LENGTH)
|
|
1472
|
+
return undefined;
|
|
1473
|
+
return {
|
|
1474
|
+
relayToken: (0, approval_relay_1.approvalRelayToken)({ decisionToken: pending.decisionToken, approvalId: pending.approvalId, routeDid: input.routeDid }),
|
|
1475
|
+
// The decision token is held only in memory, set by sendApproval together with the prompt, so the prompt is there.
|
|
1476
|
+
prompt: pending.prompt,
|
|
1477
|
+
expiresAt: pending.expiresAt,
|
|
1478
|
+
};
|
|
1479
|
+
},
|
|
1469
1480
|
async relayDeny(input) {
|
|
1470
1481
|
const receivedAt = now();
|
|
1471
1482
|
const matches = async (candidate) => {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.OWNER_ROUTE_FALLBACK_PREFIX = exports.OWNER_ROUTE_BACK_TEXT = exports.OWNER_ROUTE_DOWN_TEXT = exports.OWNER_ROUTE_WATCH_FAILURES = exports.OWNER_ROUTE_WATCH_INTERVAL_MS = void 0;
|
|
3
|
+
exports.OWNER_ROUTE_FALLBACK_PREFIX = exports.OWNER_ROUTE_BACK_TEXT = exports.OWNER_ROUTE_DOWN_TEXT = exports.OWNER_ROUTE_WATCH_FAILURES = exports.OWNER_ROUTE_WATCH_INTERVAL_MS = exports.OWNER_ROUTE_SEND_TIMEOUT_MS = void 0;
|
|
4
4
|
exports.ownerRouteUrgency = ownerRouteUrgency;
|
|
5
5
|
exports.ownerRouteDedupeKey = ownerRouteDedupeKey;
|
|
6
6
|
exports.ownerRouteItem = ownerRouteItem;
|
|
@@ -12,6 +12,8 @@ const client_1 = require("../a2a/client");
|
|
|
12
12
|
const identity_1 = require("../a2a/identity");
|
|
13
13
|
const identity_2 = require("../heart/identity");
|
|
14
14
|
const runtime_1 = require("../nerves/runtime");
|
|
15
|
+
/** A route send that takes longer than this is abandoned, so Ari gets the card well inside its 5-minute window. */
|
|
16
|
+
exports.OWNER_ROUTE_SEND_TIMEOUT_MS = 15_000;
|
|
15
17
|
/** How often the Butler checks the peer, and how many failed checks in a row (15 minutes) count as down. */
|
|
16
18
|
exports.OWNER_ROUTE_WATCH_INTERVAL_MS = 5 * 60_000;
|
|
17
19
|
exports.OWNER_ROUTE_WATCH_FAILURES = 3;
|
|
@@ -76,9 +78,10 @@ const reason = (error) => error instanceof Error ? error.message : String(error)
|
|
|
76
78
|
function createA2AOwnerRoute(options) {
|
|
77
79
|
const fetchCard = options.fetchCard ?? client_1.fetchA2AAgentCard;
|
|
78
80
|
const send = options.send ?? client_1.sendSealedA2AChat;
|
|
81
|
+
const sendRequest = options.sendRequest ?? client_1.sendSealedApprovalRequest;
|
|
79
82
|
/** null when the card at the address serves the pinned DID; otherwise why not. */
|
|
80
|
-
const pinned = async () => {
|
|
81
|
-
const served = (0, client_1.cardDid)(await fetchCard(options.cardUrl));
|
|
83
|
+
const pinned = async (signal) => {
|
|
84
|
+
const served = (0, client_1.cardDid)(await fetchCard(options.cardUrl, undefined, signal));
|
|
82
85
|
if (served === options.did)
|
|
83
86
|
return null;
|
|
84
87
|
(0, runtime_1.emitNervesEvent)({ level: "error", component: "senses", event: "senses.telegram_owner_route_pin_mismatch", message: "the owner route's peer card serves another DID", meta: { cardUrl: options.cardUrl, served: served ?? null, pinned: options.did } });
|
|
@@ -86,7 +89,7 @@ function createA2AOwnerRoute(options) {
|
|
|
86
89
|
};
|
|
87
90
|
const probe = async () => {
|
|
88
91
|
try {
|
|
89
|
-
const detail = await pinned();
|
|
92
|
+
const detail = await pinned(AbortSignal.timeout(options.timeoutMs ?? exports.OWNER_ROUTE_SEND_TIMEOUT_MS));
|
|
90
93
|
return detail ? { status: "unreachable", detail } : { status: "delivered" };
|
|
91
94
|
}
|
|
92
95
|
catch (error) {
|
|
@@ -94,12 +97,19 @@ function createA2AOwnerRoute(options) {
|
|
|
94
97
|
}
|
|
95
98
|
};
|
|
96
99
|
const route = async (item) => {
|
|
100
|
+
// One deadline covers the card check and the send, so a peer that hangs can't hold the card.
|
|
101
|
+
const signal = AbortSignal.timeout(options.timeoutMs ?? exports.OWNER_ROUTE_SEND_TIMEOUT_MS);
|
|
97
102
|
try {
|
|
98
|
-
const detail = await pinned();
|
|
103
|
+
const detail = await pinned(signal);
|
|
99
104
|
if (detail)
|
|
100
105
|
return { status: "unreachable", detail };
|
|
101
|
-
|
|
102
|
-
|
|
106
|
+
if (item.approvalRequest) {
|
|
107
|
+
await sendRequest({ cardUrl: options.cardUrl, peerDid: options.did, payload: item.approvalRequest, identity: await options.loadIdentity(), signal });
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
await send({ cardUrl: options.cardUrl, text: formatOwnerRouteMessage(item), identity: await options.loadIdentity(), signal });
|
|
111
|
+
}
|
|
112
|
+
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.telegram_owner_route_delivered", message: "sent a self-started Butler message to the owner's primary agent", meta: { urgency: item.urgency, dedupeKey: item.dedupeKey, relayed: item.approvalRequest !== undefined } });
|
|
103
113
|
return { status: "delivered" };
|
|
104
114
|
}
|
|
105
115
|
catch (error) {
|
|
@@ -107,7 +117,7 @@ function createA2AOwnerRoute(options) {
|
|
|
107
117
|
return { status: "unreachable", detail: reason(error) };
|
|
108
118
|
}
|
|
109
119
|
};
|
|
110
|
-
return Object.assign(route, { probe });
|
|
120
|
+
return Object.assign(route, { probe, peerDid: options.did });
|
|
111
121
|
}
|
|
112
122
|
/** The owner route `agent.json` names (`senses.telegram.ownerNoticesTo`), signing as this agent's A2A identity; none when unset. */
|
|
113
123
|
function ownerRouteForAgent(agentName, agentRoot) {
|
package/dist/senses/telegram.js
CHANGED
|
@@ -853,7 +853,18 @@ function createTelegramSenseApp(options) {
|
|
|
853
853
|
}
|
|
854
854
|
const effect = input.effect;
|
|
855
855
|
const choices = effect.buttons.flat().map((button) => button.text).join(", ");
|
|
856
|
-
const
|
|
856
|
+
const item = (0, telegram_owner_route_1.ownerRouteItem)(input.idempotencyKey, `${effect.text}\n\nOptions: ${choices}. The buttons are on the card in the Butler's Telegram chat.`, true);
|
|
857
|
+
const approvalId = /^approval:(.+):prompt$/u.exec(input.idempotencyKey)?.[1];
|
|
858
|
+
let approvalRequest;
|
|
859
|
+
// Building the relay request never stops the card: any error builds none, and the card goes as before.
|
|
860
|
+
try {
|
|
861
|
+
approvalRequest = approvalId === undefined ? undefined : (0, telegram_approval_relay_1.approvalRelayRequestFor)({ agentRoot, routeDid: () => route.peerDid, approvalId, transport: approvalTransport });
|
|
862
|
+
}
|
|
863
|
+
catch (error) {
|
|
864
|
+
(0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.telegram_relay_request_failed", message: "sent the approval card without a relay request after building one failed", meta: { error: String(error) } });
|
|
865
|
+
approvalRequest = undefined;
|
|
866
|
+
}
|
|
867
|
+
const outcome = await route(approvalRequest ? { ...item, approvalRequest } : item);
|
|
857
868
|
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.telegram_owner_route_approval", message: "offered an approval card to the owner's primary agent", meta: { agentName: options.agentName, outcome: outcome.status } });
|
|
858
869
|
return executeOnTelegram({
|
|
859
870
|
...input,
|
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.1415",
|
|
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.1415",
|
|
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.1415",
|
|
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": {
|