Skip to main content

tilo_actions/
remote.rs

1//! Using another peer's actions: a transport-neutral vocabulary.
2//!
3//! A peer that serves live apps (a desktop session, a headless app server)
4//! can let an authenticated remote caller list the actions it
5//! publishes, invoke one, follow its progress, and cancel it. This module is
6//! the whole contract between the two sides:
7//!
8//! - [`RemoteActionMessage`] — requests and their answers, wrapped in a
9//!   versioned [`RemoteActionFrame`] that any transport carries as opaque
10//!   bytes.
11//! - [`ActionProvider`] — what a peer implements to answer them, and [`serve`],
12//!   which maps one request frame onto a provider. Answers that need an
13//!   application's help arrive later as a [`Pending`], so no caller blocks.
14//! - [`CatalogueQuery`] — paged, filtered browsing of what a provider offers.
15//! - [`InvocationLog`] — the idempotency rule every provider shares: an
16//!   invocation is keyed by its caller-chosen [`InvocationId`], so a retry
17//!   after a lost reply observes the original invocation instead of running
18//!   the action twice.
19//!
20//! Who is calling is never read from a payload. The transport that
21//! authenticated the connection constructs the [`Caller`] and hands it to the
22//! provider beside the message; nothing in a frame can name or change it.
23//!
24//! Descriptors, addresses, arguments, outputs and lifecycle updates are the
25//! same types the local action surface already uses ([`ActionDescriptor`](crate::api::ActionDescriptor),
26//! [`ActionAddress`], [`InvocationUpdate`], [`ActionOutput`],
27//! [`ActionFailure`]), so a remote caller sees exactly what a local one does.
28
29use std::collections::{HashMap, VecDeque};
30
31use serde::{Deserialize, Serialize};
32
33pub use window_actions::{activation_requested, link_scheme, render_anchor};
34
35pub mod admitted;
36pub use admitted::{Admits, Admitted, LiveRead, LiveView, Outcome, ReportsProgress, Serving};
37mod application;
38pub mod asked;
39/// An app's sound output on the device, on the connection its launcher handed it.
40pub mod audio_output;
41/// An outside service's call carried into a workspace's call, on an app's connection.
42pub mod call;
43mod caller;
44/// An app's own place in a workspace's call, on the connection its launcher handed it.
45pub mod native_media;
46/// A shell the device's shell runtime runs, carried on an app's connection.
47pub mod shell;
48pub use caller::{Caller, Invited, KeptCaller, KeyCall, PlacedCaller, device_agent_id};
49pub mod signed_invocation;
50pub use signed_invocation::{CallAllowed, SignedCall, SignedInvocation};
51mod catalogue;
52mod changes;
53mod confirmation;
54mod content_get;
55mod content_link;
56mod content_put;
57/// Adding a computer to the person's devices with a one-use ticket: the computer's own daemon
58/// issues it, prints the one string, and the new computer logs in with it.
59pub mod device_tickets;
60mod pending;
61pub mod session_actions;
62mod vault;
63pub use vault::{
64    ItemRef, KEEP_SEALED, KEEP_USES, REMOVE_SEALED, VAULT_DEVICE_KEY, VAULT_FIND,
65    VAULT_FORGET_PAGE_LOGIN, VAULT_ITEM_KIND, VAULT_KEEP, VAULT_KEEP_PAGE_LOGIN, VAULT_KIND,
66    VAULT_LIST, VAULT_PAGE_FILL, VAULT_PAGE_LOGINS, VAULT_PROVIDER, VAULT_RECORD, VAULT_RELEASE,
67    VAULT_RESOURCE, VAULT_SECRET_ANSWERS, answers_secret, calls_answering_a_secret,
68    calls_by_address, item_param, takes_item, vault_target,
69};
70pub mod press_points;
71mod providers;
72mod resource_read;
73pub mod secret_arguments;
74mod session_state;
75mod shared_provider;
76mod store_commands;
77mod surfaces;
78#[cfg(any(test, feature = "test-support"))]
79mod test_provider;
80pub use session_state::{SessionState, SyncState, WorkspaceState};
81mod wait;
82mod watch;
83pub use watch::{CHANGED_UNAVAILABLE, Here, HereWindow, KEY_GRANTS, PRESENCE, WatchScope};
84mod window_actions;
85mod within;
86pub mod workspace_activity;
87
88pub use application::{
89    APPLICATION_PROVIDER, application_action_target, application_open_target, application_provider,
90    application_provider_resource, application_provider_token, application_resource_target,
91    valid_file_name,
92};
93pub use confirmation::{
94    ASK, ASK_PROVIDER, ASK_RESOURCE, ASK_WITH_CHOICES, Confirmation, ConfirmationQuestion,
95    ConfirmationReply, MAX_ASK_CHARS, MAX_ASK_CHOICES, MAX_CHOICE_CHARS, PersonAnswer, PersonAsk,
96    argument_digest, ask_target, is_ask,
97};
98pub use providers::{
99    APPLICATION_OPEN_ACTION, APPLICATION_RESOURCE_KIND, APPLICATION_RESOURCE_PREFIX,
100    APPLICATION_START_ACTION, DEVICE_FILES_FOLDER, DEVICE_FILES_PROVIDER, OWN_PROVIDER,
101    RESOURCE_PROVIDER, SHARE_LINK_ACTION, WORKSPACE_PROVIDER, is_resource_provider, resource_parts,
102};
103
104pub use catalogue::{
105    CanonicalActionRoute, CatalogueLimits, CataloguePage, CatalogueProvider, CatalogueQuery,
106    CatalogueResource, CatalogueRow, MAX_BY_RESOURCE_PAGE, MAX_CATALOGUE_PAGE,
107    MAX_CATALOGUE_PAGE_BYTES, Offered, ProvidedPackage, ProvidedResource, ResourceViewLocator,
108    RowVisibility, ViewResourceQuery, compact, expand, rows_weight, stem_word, truncate_bytes,
109    truncate_resources, truncate_rows,
110};
111pub use changes::{CHANGE_FEED_UNAVAILABLE, ChangeFeed, ChangePage, ResourceChanged, What};
112pub use content_get::{CONTENT_GETS_UNAVAILABLE, ContentGetAnswer, ContentGets, ContentPiece};
113pub use content_link::{
114    CONTENT_LINK_TTL_SECS, CONTENT_LINKS_UNAVAILABLE, ContentLink, ContentLinkAsk, ContentLinkFile,
115    MAX_CONTENT_LINK_FILES, viewable,
116};
117pub use content_put::{
118    CONTENT_PUTS_UNAVAILABLE, CONTENT_REFERENCE, ContentPut, ContentPutAnswer, ContentPutStep,
119    ContentPuts, HostedContentPuts, MAX_CONTENT_PUT_AHEAD, MAX_CONTENT_PUT_CHUNK, MAX_HAVE_HASHES,
120    MAX_HOSTED_CONTENT_PUTS, MAX_OPEN_CONTENT_PUTS, MAX_PUT_MANY_BYTES, MAX_PUT_MANY_FILES,
121    content_hash,
122};
123pub use store_commands::{STORE_COMMANDS_UNAVAILABLE, StoreCommands};
124mod execution_lease;
125pub use execution_lease::ExecutionLease;
126pub use pending::{Abandoned, Completer, Pending, PendingPoll, pending};
127pub use resource_read::{
128    DEVICE_JOBS, DEVICE_SETTINGS, DEVICE_SETTINGS_REFUSED, Decided, HeldCopies, ListedResource,
129    RESOURCE_READ_REFUSED, RESOURCE_READS_FOR_AGENTS, RESOURCE_READS_UNAVAILABLE,
130    RESOURCE_WRITE_REFUSED, ReadingAnswer, ReadsAnswer, ResourceAddress, ResourceAsk, ResourceCopy,
131    ResourceReadings, ResourceReads, ResourceWake, answer_read, answered, device_job_address,
132    device_job_path, device_record_address, device_record_space, parse_device_record_space,
133    parse_job_path, read_resources, readings_from, readings_of, reads_answer,
134};
135#[cfg(any(test, feature = "test-support"))]
136pub use test_provider::TestProvider;
137pub use wait::{MAX_REMOTE_WAIT, MAX_REMOTE_WAIT_MS, UpdateMark, settle_with};
138
139use crate::api::ActionAddress;
140use crate::context::ActionContext;
141use crate::outcome::{ActionFailure, ActionOutput, InvocationId, InvocationUpdate};
142use crate::params::ARGUMENTS_JSON_PREFIX;
143
144/// Version of the [`RemoteActionFrame`] schema this build speaks.
145///
146/// Additive changes keep the version; a change an older peer would misread
147/// bumps it, and [`RemoteActionFrame::decode`] refuses a version it does not know.
148pub const REMOTE_ACTIONS_VERSION: u16 = 5;
149
150/// Upper bound on one encoded frame: a provider pages its catalogue rather than raise this.
151pub const MAX_REMOTE_ACTION_FRAME_BYTES: usize = 1024 * 1024;
152
153/// The most raw bytes one piece of content carries, into a workspace's store
154/// ([`ContentPutStep::Append`]) or out of it ([`ContentGetAnswer`]): hex doubles
155/// them, and a caller splits anything larger.
156pub const MAX_CONTENT_FRAME_BYTES: usize = 384 * 1024;
157
158/// Default number of invocations an [`InvocationLog`] remembers.
159pub const DEFAULT_LOG_CAPACITY: usize = 1024;
160
161/// Which published action an invocation names on the provider.
162///
163/// `provider` is an opaque token the provider issued in a [`CataloguePage`]
164/// (which live app published the action); `address` is the app's own stable
165/// resource/action pair. A caller copies both from a catalogue entry and
166/// never constructs a provider itself.
167#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
168pub struct RemoteActionTarget {
169    pub provider: String,
170    pub address: ActionAddress,
171}
172
173/// The provider a workspace's own governance actions (membership, roles, grants,
174/// bans) are answered under. It is the provider's, not an app's, so it is the
175/// one provider a caller names without reading it from a catalogue page.
176pub const WORKSPACE_GOVERNANCE_PROVIDER: &str = tilo_action_policy::agent_answers::WORKSPACE_APP;
177/// The resource kind of a workspace's governance resource.
178pub const WORKSPACE_GOVERNANCE_KIND: &str = "workspace.permissions";
179
180impl RemoteActionTarget {
181    /// The governance action granted as `verb` (one of
182    /// `tilo_action_policy::roles::governance`, `server.add` and the like) on
183    /// the workspace `workspace`, at the address its tree publishes it
184    /// ([`workspace_governance_address`]).
185    #[must_use]
186    pub fn workspace_governance(workspace: &str, verb: &str) -> Self {
187        Self {
188            provider: WORKSPACE_GOVERNANCE_PROVIDER.to_owned(),
189            address: workspace_governance_address(workspace, verb),
190        }
191    }
192}
193
194/// The root of a workspace's governance tree: the workspace itself, the
195/// resource an agent's path `workspace` names.
196#[must_use]
197pub fn workspace_governance_resource(workspace: &str) -> String {
198    format!("{WORKSPACE_GOVERNANCE_KIND}:{workspace}")
199}
200
201/// The servers keeping a workspace, under its governance root
202/// (`workspace/servers`).
203pub const WORKSPACE_SERVERS: &str = "servers";
204/// The apps and bots a workspace uses, under its governance root
205/// (`workspace/apps`).
206pub const WORKSPACE_APPS: &str = "apps";
207/// The attestors a workspace trusts and the publisher keys it refuses, under
208/// its governance root (`workspace/trust`).
209pub const WORKSPACE_TRUST: &str = "trust";
210/// The registries a workspace fetches apps from, under its governance root
211/// (`workspace/registries`).
212pub const WORKSPACE_REGISTRIES: &str = "registries";
213/// The limits a workspace's owners set on what members post there, under its
214/// governance root (`workspace/content`): the largest file a host keeps and
215/// what one member's files may take, now and in any hour. Read by every
216/// member as the Workspace package's `content` root.
217pub const WORKSPACE_CONTENT: &str = "content";
218/// One app a workspace runs (`workspace/apps/<app>`, its id): what updates, pins and uninstalls
219/// it is published on it.
220pub const WORKSPACE_APP: &str = "apps/*";
221/// The mail accounts a workspace keeps on its server, under its governance
222/// root (`workspace/mail-accounts`): `tilo.accounts`'s, reached by path.
223pub const WORKSPACE_MAIL_ACCOUNTS: &str = "mail-accounts";
224/// The items of a workspace's vault, under its governance root
225/// (`workspace/vault`): `tilo.vault`'s, reached by path.
226pub const WORKSPACE_VAULT: &str = "vault";
227/// The model providers a workspace keeps on its server, under its governance
228/// root (`workspace/models`): `tilo.models`'s, reached by path.
229pub const WORKSPACE_MODELS: &str = "models";
230/// The people in a workspace, under its governance root (`workspace/members`).
231pub const WORKSPACE_MEMBERS: &str = "members";
232/// One person among a workspace's people (`workspace/members/<person>`, their user public key
233/// in hex): what changes their role and removes them is published on them.
234pub const WORKSPACE_MEMBER: &str = "members/*";
235/// The workspace's action that issues an invitation: letting someone in put off until they
236/// redeem it, so the workspace's `add-member` grants decide it for the role it hands out, as they
237/// decide redeeming it.
238pub const WORKSPACE_INVITE: &str = "invite";
239/// The action `workspace/members#admit` publishes: admit a person to the workspace at a place,
240/// whether or not they held one, as [`WORKSPACE_MEMBER_PLACED`] would a member's. The change that
241/// admits them keeps their membership record with it.
242pub const WORKSPACE_MEMBER_ADMITTED: &str = "admit";
243/// The action `workspace/members/<person>#role` publishes: change the place of a person the
244/// workspace holds. A person it does not hold is added by [`WORKSPACE_MEMBER_ADMITTED`], never
245/// given a place here.
246pub const WORKSPACE_MEMBER_PLACED: &str = "role";
247/// The action `workspace/members/<person>#remove` publishes: remove the person, as the
248/// workspace's grants on removing let whoever asks, or themselves.
249pub const WORKSPACE_MEMBER_REMOVED: &str = "remove";
250/// The invitations a workspace has open, under its governance root
251/// (`workspace/invitations`).
252pub const WORKSPACE_INVITATIONS: &str = "invitations";
253/// The addresses left at a workspace's entry while it takes people by
254/// invitation, under its governance root (`workspace/waiting`).
255pub const WORKSPACE_WAITING: &str = "waiting";
256/// The grants of a workspace's policy, under its governance root (`workspace/permissions`).
257pub const WORKSPACE_PERMISSIONS: &str = "permissions";
258/// One grant of a workspace's policy (`workspace/permissions/<grant>`, by its id): what takes
259/// it back is published on it.
260pub const WORKSPACE_PERMISSION: &str = "permissions/*";
261/// The operation a workspace's grant is taken back by, published as
262/// `workspace/permissions/<grant>#revoke`: by the person who gave it, or by whoever the
263/// workspace's policy lets revoke grants.
264pub const WORKSPACE_GRANT_REVOKE: &str = "grant.revoke";
265/// The operation that lets a person or a role read one resource (`workspace/members#grant-read`):
266/// a grant on the resource's own node, admitted by the workspace's grant on granting. Who belongs
267/// to a channel, a shared folder or any resource is who reads it, so this is how one is let in
268/// (`tilo_action_policy::reading`).
269pub const WORKSPACE_READ_GRANT: &str = "reading.grant";
270/// The operation that keeps a person or a role from reading one resource
271/// (`workspace/members#revoke-read`), admitted by the workspace's grant on revoking.
272pub const WORKSPACE_READ_REVOKE: &str = "reading.revoke";
273/// The workspace's record of its agents, under its governance root (`workspace/agents`): who
274/// works in the workspace, changed only by the three actions published there.
275pub const WORKSPACE_AGENTS: &str = "agents";
276/// Make an agent of the workspace (`workspace/agents#create`): the record's `create_agent`, its
277/// arguments as that action takes them. Answers `{agent}`, the agent's id.
278pub const WORKSPACE_AGENT_CREATE: &str = "agent.create";
279/// Change one of the workspace's agents (`workspace/agents#update`): `{action, arguments}`, any
280/// action of the record but making and retiring one, by its id and with its arguments.
281pub const WORKSPACE_AGENT_UPDATE: &str = "agent.update";
282/// Retire one of the workspace's agents (`workspace/agents#delete`): `{agent}`, its id. What it
283/// did stays readable under its name.
284pub const WORKSPACE_AGENT_DELETE: &str = "agent.delete";
285/// The app that keeps a workspace's record of its agents: the workspace's own service.
286pub const WORKSPACE_AGENTS_APP: &str = "tilo.workspace";
287/// The kind of the workspace's record of its agents: what [`WORKSPACE_AGENT_CREATE`],
288/// [`WORKSPACE_AGENT_UPDATE`] and [`WORKSPACE_AGENT_DELETE`] write.
289pub const WORKSPACE_AGENTS_KIND: &str = "tilo.workspace.agent";
290/// The steps of the record of agents [`WORKSPACE_AGENT_UPDATE`] takes: every one but making and
291/// retiring an agent, and where an agent waits or runs, which the device that runs it writes.
292pub const WORKSPACE_AGENT_CHANGES: [&str; 15] = [
293    "set-agent-spend-limit",
294    "record-agent-spend",
295    "rename-agent",
296    "set-agent-avatar",
297    "set-agent-model",
298    "set-agent-instruction",
299    "pause-agent",
300    "resume-agent",
301    "start-sub-agent",
302    "note-sub-agent",
303    "stop-sub-agent",
304    "sub-agent-stands",
305    "sub-agent-produced",
306    "sub-agent-coding",
307    "set-sub-agent-limits",
308];
309
310/// What the agents' action `operation` (one of [`WORKSPACE_AGENT_CREATE`],
311/// [`WORKSPACE_AGENT_UPDATE`] and [`WORKSPACE_AGENT_DELETE`]) writes: the steps the workspace's
312/// host takes in its record of its agents when it answers the call. Nothing for any other
313/// operation.
314#[must_use]
315pub fn workspace_agent_effects(operation: &str) -> Vec<crate::ActionEffect> {
316    let step =
317        |verb: &str| crate::ActionEffect::new(WORKSPACE_AGENTS_APP, WORKSPACE_AGENTS_KIND, verb);
318    match operation {
319        WORKSPACE_AGENT_CREATE => vec![step("create-agent")],
320        WORKSPACE_AGENT_UPDATE => WORKSPACE_AGENT_CHANGES
321            .iter()
322            .map(|verb| step(verb))
323            .collect(),
324        WORKSPACE_AGENT_DELETE => vec![step("retire-agent")],
325        _ => Vec::new(),
326    }
327}
328/// Where a workspace's governance tree publishes the actions it grants by
329/// another name: the operation a grant and a policy name it by, the resource
330/// under the root it is on (none for the root itself) and its id there, as a
331/// person names it. An operation not listed is published on the root under its
332/// own name; one listed on [`WORKSPACE_MEMBER`] is published on each person, who
333/// is its `person`, and one listed on [`WORKSPACE_APP`] on each app the workspace runs, which
334/// is its `app`. One listed on [`WORKSPACE_PERMISSION`] is published on each of the
335/// workspace's grants.
336pub const WORKSPACE_MEMBER_LIST_PUBLISHED: [(&str, Option<&str>, &str); 47] = [
337    ("member.list", Some(WORKSPACE_MEMBERS), "list"),
338    (
339        "member.add",
340        Some(WORKSPACE_MEMBERS),
341        WORKSPACE_MEMBER_ADMITTED,
342    ),
343    (
344        "member.add",
345        Some(WORKSPACE_MEMBER),
346        WORKSPACE_MEMBER_PLACED,
347    ),
348    (
349        "remove-member",
350        Some(WORKSPACE_MEMBER),
351        WORKSPACE_MEMBER_REMOVED,
352    ),
353    ("member.name", Some(WORKSPACE_MEMBERS), "name"),
354    // Banning and lifting a ban name a person who need not be a member any more (a ban
355    // removes them), so both are the members' verbs, taking the person, not one member's.
356    ("ban", Some(WORKSPACE_MEMBERS), "ban"),
357    ("unban", Some(WORKSPACE_MEMBERS), "unban"),
358    ("invite", Some(WORKSPACE_INVITATIONS), "invite"),
359    ("invitation.list", Some(WORKSPACE_INVITATIONS), "list"),
360    ("invitation.cancel", Some(WORKSPACE_INVITATIONS), "cancel"),
361    ("wait-list.list", Some(WORKSPACE_WAITING), "list"),
362    ("wait-list.remove", Some(WORKSPACE_WAITING), "unlist"),
363    ("wait-list.mail", Some(WORKSPACE_WAITING), "mail"),
364    ("server.list", Some(WORKSPACE_SERVERS), "list"),
365    ("server.add", Some(WORKSPACE_SERVERS), "add"),
366    ("server.remove", Some(WORKSPACE_SERVERS), "remove"),
367    ("server.move", Some(WORKSPACE_SERVERS), "move"),
368    ("copies.set", Some(WORKSPACE_SERVERS), "copies"),
369    ("copies.read", Some(WORKSPACE_SERVERS), "keeps"),
370    ("content.held", Some(WORKSPACE_SERVERS), "content"),
371    ("content.policy", Some(WORKSPACE_CONTENT), "policy"),
372    ("content.set-policy", Some(WORKSPACE_CONTENT), "set-policy"),
373    ("trust.list", Some(WORKSPACE_TRUST), "list"),
374    ("trust.revoked", Some(WORKSPACE_TRUST), "revoked"),
375    ("trust.add", Some(WORKSPACE_TRUST), "add"),
376    ("trust.remove", Some(WORKSPACE_TRUST), "remove"),
377    ("trust.revoke", Some(WORKSPACE_TRUST), "revoke"),
378    ("registry.list", Some(WORKSPACE_REGISTRIES), "list"),
379    ("registry.add", Some(WORKSPACE_REGISTRIES), "add"),
380    ("registry.remove", Some(WORKSPACE_REGISTRIES), "remove"),
381    ("registry.enable", Some(WORKSPACE_REGISTRIES), "enable"),
382    ("registry.disable", Some(WORKSPACE_REGISTRIES), "disable"),
383    ("registry.channel", Some(WORKSPACE_REGISTRIES), "channel"),
384    ("install-app", Some(WORKSPACE_APPS), "install"),
385    ("upload-app-file", Some(WORKSPACE_APPS), "upload"),
386    ("app.offers", Some(WORKSPACE_APPS), "offers"),
387    ("install-app", Some(WORKSPACE_APP), "update"),
388    ("app.pin", Some(WORKSPACE_APP), "pin"),
389    ("app.unpin", Some(WORKSPACE_APP), "unpin"),
390    ("uninstall-app", Some(WORKSPACE_APP), "uninstall"),
391    ("app.earlier", Some(WORKSPACE_APP), "earlier"),
392    (WORKSPACE_GRANT_REVOKE, Some(WORKSPACE_PERMISSION), "revoke"),
393    (WORKSPACE_READ_GRANT, Some(WORKSPACE_MEMBERS), "grant-read"),
394    (
395        WORKSPACE_READ_REVOKE,
396        Some(WORKSPACE_MEMBERS),
397        "revoke-read",
398    ),
399    (WORKSPACE_AGENT_CREATE, Some(WORKSPACE_AGENTS), "create"),
400    (WORKSPACE_AGENT_UPDATE, Some(WORKSPACE_AGENTS), "update"),
401    (WORKSPACE_AGENT_DELETE, Some(WORKSPACE_AGENTS), "delete"),
402];
403
404/// The provider a workspace's invocations answer under: the record of what was invoked
405/// there, and the asked records a call waits in.
406pub const WORKSPACE_INVOCATIONS_PROVIDER: &str = "tilo.invocations";
407
408/// The provider that answers a person's install machines.
409pub const MACHINES_PROVIDER: &str = "tilo.machines";
410
411/// The provider a server answers its accounts under.
412pub const SERVER_ACCOUNT_PROVIDER: &str = "tilo.server";
413
414/// The provider that answers a workspace's events under.
415pub const WORKSPACE_EVENTS_PROVIDER: &str = "tilo.events";
416
417/// The provider a moderation turn reaches a person's recorded changes under.
418pub const MODERATION_PROVIDER: &str = "tilo.moderation";
419/// The resource its read and its undo are actions of.
420pub const MODERATION_HISTORY: &str = "moderation.history";
421/// Its action that takes a person's changes back.
422pub const MODERATION_UNDO: &str = "undo";
423/// The app whose record a moderation turn reads and takes changes back in: the workspace's chat.
424pub const MODERATED_APP: &str = "so.tilo.chat";
425
426/// The provider a workspace's model providers answer under. Their provider declares their
427/// actions (`tilo_workspace_records::models`); what this crate knows of them is that a
428/// workspace's host keeps them (`tilo_action_services::WORKSPACE_KEPT_PROVIDERS`) and what each writes in the
429/// workspace's vault (`tilo_workspace_records::models::MODEL_VAULT_STEPS`).
430pub const MODELS_PROVIDER: &str = "tilo.models";
431
432/// The provider a person's log of what they were told answers under. Its provider declares its
433/// actions (`tilo_person_services::person_telling`); what this crate knows of it is that a
434/// workspace's host keeps it (`tilo_action_services::WORKSPACE_KEPT_PROVIDERS`).
435pub const TELLING_PROVIDER: &str = "tilo.telling";
436
437/// The provider a workspace's connected accounts answer under. Their provider declares their
438/// actions (`tilo_workspace_records::accounts`); what this crate knows of them is that
439/// a workspace's host keeps them (`tilo_action_services::WORKSPACE_KEPT_PROVIDERS`), what each writes
440/// (`tilo_workspace_records::accounts::ACCOUNT_STEPS`) and which answer a secret
441/// (`tilo_workspace_records::accounts::ACCOUNT_SECRET_ANSWERS`).
442pub const ACCOUNTS_PROVIDER: &str = "tilo.accounts";
443
444/// The provider a person's connected services answer under. Their provider declares their
445/// actions (`tilo_workspace_records::connections`); what this crate knows of them is
446/// that a workspace's host keeps them (`tilo_action_services::WORKSPACE_KEPT_PROVIDERS`), what each writes in the
447/// workspace's vault and whose answers carry the service's own words
448/// (`tilo_workspace_records::connections`).
449pub const CONNECTIONS_PROVIDER: &str = "tilo.connections";
450
451/// The resource `child` of `workspace`'s governance tree: the root for `None`.
452#[must_use]
453pub fn workspace_governance_child(workspace: &str, child: Option<&str>) -> String {
454    let root = workspace_governance_resource(workspace);
455    match child {
456        Some(child) => format!("{root}/{child}"),
457        None => root,
458    }
459}
460
461/// The resource of the grant `grant` (its id) among `workspace`'s permissions.
462#[must_use]
463pub fn workspace_permission(workspace: &str, grant: &str) -> String {
464    format!(
465        "{}/{grant}",
466        workspace_governance_child(workspace, Some(WORKSPACE_PERMISSIONS))
467    )
468}
469
470/// The resource of the person `person` (their user public key in hex) among `workspace`'s people.
471#[must_use]
472pub fn workspace_member(workspace: &str, person: &str) -> String {
473    format!(
474        "{}/{person}",
475        workspace_governance_child(workspace, Some(WORKSPACE_MEMBERS))
476    )
477}
478
479/// The app `app` (its id) among the apps `workspace` runs.
480#[must_use]
481pub fn workspace_app(workspace: &str, app: &str) -> String {
482    format!(
483        "{}/{app}",
484        workspace_governance_child(workspace, Some(WORKSPACE_APPS))
485    )
486}
487
488/// The address `workspace`'s governance tree publishes the operation
489/// `operation` at, where it is not one person's or one app's.
490#[must_use]
491pub fn workspace_governance_address(workspace: &str, operation: &str) -> ActionAddress {
492    match WORKSPACE_MEMBER_LIST_PUBLISHED
493        .iter()
494        .find(|(granted, child, _)| {
495            *granted == operation
496                && *child != Some(WORKSPACE_MEMBER)
497                && *child != Some(WORKSPACE_APP)
498                && *child != Some(WORKSPACE_PERMISSION)
499        }) {
500        Some((_, child, action)) => {
501            ActionAddress::new(workspace_governance_child(workspace, *child), *action)
502        }
503        None => ActionAddress::new(workspace_governance_resource(workspace), operation),
504    }
505}
506
507/// The workspace and the operation `address` asks of that workspace's
508/// governance, when its tree publishes one there: what
509/// [`workspace_governance_address`] maps back. An operation published
510/// elsewhere, asked by its grant's name, is none.
511#[must_use]
512pub fn workspace_governance_operation(address: &ActionAddress) -> Option<(&str, &str)> {
513    let named = address
514        .resource
515        .strip_prefix(workspace_governance_resource("").as_str())?;
516    let (workspace, child) = match named.split_once('/') {
517        Some((workspace, child)) => (workspace, Some(child)),
518        None => (named, None),
519    };
520    if workspace.is_empty() {
521        return None;
522    }
523    let action = address.action.as_str();
524    let child = if workspace_person(address).is_some() {
525        Some(WORKSPACE_MEMBER)
526    } else if workspace_app_named(address).is_some() {
527        Some(WORKSPACE_APP)
528    } else if workspace_grant(address).is_some() {
529        Some(WORKSPACE_PERMISSION)
530    } else {
531        child
532    };
533    let published = WORKSPACE_MEMBER_LIST_PUBLISHED
534        .iter()
535        .find(|(_, at, published)| *at == child && *published == action);
536    match published {
537        Some((granted, _, _)) => Some((workspace, granted)),
538        None if child.is_none()
539            && !WORKSPACE_MEMBER_LIST_PUBLISHED
540                .iter()
541                .any(|(granted, _, _)| *granted == action) =>
542        {
543            Some((workspace, action))
544        }
545        None => None,
546    }
547}
548
549/// The person (their user public key in hex) `address` names among its workspace's people
550/// (`workspace/members/<person>`), when it names one.
551#[must_use]
552pub fn workspace_person(address: &ActionAddress) -> Option<&str> {
553    let named = address
554        .resource
555        .strip_prefix(workspace_governance_resource("").as_str())?;
556    let (members, person) = named.split_once('/')?.1.split_once('/')?;
557    (members == WORKSPACE_MEMBERS
558        && person.len() == 64
559        && person.bytes().all(|byte| byte.is_ascii_hexdigit()))
560    .then_some(person)
561}
562
563/// The app (its id) `address` names among the apps its workspace runs
564/// (`workspace/apps/<app>`), when it names one.
565#[must_use]
566pub fn workspace_app_named(address: &ActionAddress) -> Option<&str> {
567    let named = address
568        .resource
569        .strip_prefix(workspace_governance_resource("").as_str())?;
570    let (apps, app) = named.split_once('/')?.1.split_once('/')?;
571    (apps == WORKSPACE_APPS
572        && !app.is_empty()
573        && app
574            .bytes()
575            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_')))
576    .then_some(app)
577}
578
579/// The grant `address` is on, by its id, when it is one of a workspace's permissions
580/// (`workspace/permissions/<grant>`).
581#[must_use]
582pub fn workspace_grant(address: &ActionAddress) -> Option<&str> {
583    let named = address
584        .resource
585        .strip_prefix(workspace_governance_resource("").as_str())?;
586    let (permissions, grant) = named.split_once('/')?.1.split_once('/')?;
587    (permissions == WORKSPACE_PERMISSIONS && !grant.is_empty()).then_some(grant)
588}
589
590/// The person's settings, kept by the provider whether or not the app that shows
591/// them is open: each section a record published with its field edits and
592/// verbs (`settings:<kind>`), changed through them as that app's window
593/// changes them. It is answered under the settings provider.
594pub mod settings_resources {
595    /// The provider that answers the person's settings.
596    pub const PROVIDER: &str = "tilo.settings";
597    /// The surface every section is typed by, whichever app shows it.
598    pub const SURFACE_APP: &str = "so.tilo.settings.sections";
599
600    /// Whether `path` (a resource, or an action of one) is a section of the person's settings
601    /// (`settings/<section>`) or a device's (`devices/<id>/settings/<section>`).
602    #[must_use]
603    pub fn is_section(path: &str) -> bool {
604        let resource = path.split('#').next().unwrap_or_default();
605        let parts: Vec<&str> = resource.split('/').collect();
606        matches!(parts.as_slice(), ["settings", section] if !section.is_empty())
607            || matches!(parts.as_slice(), ["devices", device, "settings", section]
608                if !device.is_empty() && !section.is_empty())
609    }
610}
611
612/// Why a provider refuses a directory action that asks for confirmation when
613/// the request names no revision: the confirmation covers the action as the
614/// person was shown it, which only that revision identifies. A caller that
615/// confirms on its own policy rather than a person's reads the current
616/// revision and retries.
617pub const CONFIRMED_ACTION_NEEDS_REVISION: &str =
618    "a confirmed action needs the revision it was shown at";
619
620/// What an invocation carries for the action's declared input.
621#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
622pub enum InvokeArgument {
623    /// The action takes nothing.
624    #[default]
625    None,
626    /// The single text input a prompted action collects.
627    Text(String),
628    /// The typed argument object checked against the action's parameters.
629    Json(serde_json::Map<String, serde_json::Value>),
630}
631
632impl InvokeArgument {
633    /// The single-slot form the local invocation path accepts: text as is,
634    /// a typed object behind [`ARGUMENTS_JSON_PREFIX`].
635    #[must_use]
636    pub fn to_slot(&self) -> Option<String> {
637        match self {
638            Self::None => None,
639            Self::Text(text) => Some(text.clone()),
640            Self::Json(object) => Some(format!(
641                "{ARGUMENTS_JSON_PREFIX}{}",
642                serde_json::Value::Object(object.clone())
643            )),
644        }
645    }
646
647    /// What [`Self::to_slot`] carries, as the wire field it came from. A
648    /// slot no typed object is written behind is text, which is what an
649    /// action taking a prompt collects.
650    #[must_use]
651    pub fn from_slot(slot: Option<&str>) -> Self {
652        match slot {
653            None => Self::None,
654            Some(text) => match text
655                .strip_prefix(ARGUMENTS_JSON_PREFIX)
656                .and_then(|json| serde_json::from_str(json).ok())
657            {
658                Some(object) => Self::Json(object),
659                None => Self::Text(text.to_owned()),
660            },
661        }
662    }
663}
664
665/// A request to run one published action.
666#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
667pub struct InvokeRequest {
668    /// Chosen by the caller and reused verbatim on retry; the provider runs the
669    /// action at most once per id.
670    pub invocation: InvocationId,
671    pub target: RemoteActionTarget,
672    #[serde(default)]
673    pub argument: InvokeArgument,
674    /// Human provenance carried into history. It never grants authority.
675    #[serde(default, skip_serializing_if = "Option::is_none")]
676    pub context: Option<ActionContext>,
677    /// The caller's explicit confirmation, for an action whose contract
678    /// requires one. The provider checks it against the contract; it is
679    /// evidence, not authority.
680    #[serde(default, skip_serializing_if = "Option::is_none")]
681    pub confirmation: Option<Confirmation>,
682    /// The catalogue revision the caller chose the target from, for a
683    /// provider whose actions are resolved live at that revision. A provider
684    /// refuses a target that no longer exists at it rather than guessing.
685    ///
686    /// Omitted, a directory target resolves against the directory as it is
687    /// now, and the admission is bound to the revision the provider
688    /// resolved it at: an executing provider still refuses the action once the
689    /// directory moved on before it ran. An action whose contract asks for
690    /// confirmation needs the revision it was shown at; without one the
691    /// provider refuses with [`CONFIRMED_ACTION_NEEDS_REVISION`].
692    #[serde(default, skip_serializing_if = "Option::is_none")]
693    pub revision: Option<String>,
694    /// The live invocation this request continues: an edit an effect
695    /// submits while running for someone else. The provider admits it as that
696    /// invocation's original caller, with their grants, never as the app.
697    #[serde(default, skip_serializing_if = "Option::is_none")]
698    pub on_behalf_of: Option<InvocationId>,
699    /// Hold the receipt until the invocation settles or this many
700    /// milliseconds pass (at most [`MAX_REMOTE_WAIT`]), so a quick action
701    /// answers in one round trip. How the answer travels, not what runs:
702    /// [`serve`] takes it off the request before the provider sees it, and
703    /// [`InvocationLog`] ignores it. A provider that predates it answers at
704    /// admission, as before.
705    #[serde(default, skip_serializing_if = "Option::is_none")]
706    pub wait_ms: Option<u32>,
707    /// The name and avatar a bot asks to show for this action. Only an API
708    /// that can check the caller is a bot allowed it admits one
709    /// (the workspace-action API a bot drives); every other API refuses the request
710    /// ([`crate::appearance::refuse_here`]) rather than dropping the field.
711    #[serde(default, skip_serializing_if = "Option::is_none")]
712    pub appearance: Option<crate::Appearance>,
713    /// The caller's own signature over who asks for which action on which
714    /// resource with which arguments ([`SignedInvocation`]). A host that runs
715    /// an invocation for a caller on another device requires it and acts as
716    /// its verified signer; a request that never leaves its device (an app
717    /// asking its own session) carries none.
718    ///
719    /// A call an app makes while it runs someone's invocation carries that invocation here
720    /// instead, the one its [`Self::on_behalf_of`] names ([`SignedInvocation::serves`]): the
721    /// original caller's signature is its proof, and the device running the app signs the
722    /// request that brings it.
723    #[serde(default, skip_serializing_if = "Option::is_none")]
724    pub signed: Option<Box<SignedInvocation>>,
725}
726
727impl InvokeRequest {
728    /// The resource this call is made from, as its caller named it in its arguments
729    /// ([`crate::params::FROM_ARGUMENT`]): what the resources it makes are made from, and what
730    /// a turn it starts answers. The dispatch admits a call made from a resource only for a
731    /// caller who may read that resource.
732    #[must_use]
733    pub fn made_from(&self) -> Option<crate::params::MadeFrom> {
734        let InvokeArgument::Json(arguments) = &self.argument else {
735            return None;
736        };
737        crate::params::MadeFrom::from_json(arguments.get(crate::params::FROM_ARGUMENT)?)
738    }
739
740    /// The person's approve of the asked record this call was kept as, when
741    /// the dispatch admitted it again on their answer: what a provider that
742    /// waits for their yes reads instead of asking.
743    #[must_use]
744    pub fn approval(&self) -> Option<&asked::Approval> {
745        match &self.confirmation {
746            Some(Confirmation::Asked(approval)) => Some(approval),
747            _ => None,
748        }
749    }
750
751    /// What the agent's harness calls the session this request was sent in ("Release prep"), as
752    /// the client's agent-session group says it: display only, the name people see the agent by
753    /// ([`Caller::in_named_session`]). `None` when the client named no session.
754    #[must_use]
755    pub fn said_session_name(&self) -> Option<String> {
756        let group = self
757            .context
758            .as_ref()?
759            .group
760            .as_ref()
761            .filter(|group| group.kind == crate::context::AGENT_SESSION_GROUP)?;
762        crate::context::one_line(group.session.as_deref()?, crate::context::MAX_LABEL_CHARS)
763    }
764
765    /// Whether `other` asks for the same invocation: every field but the
766    /// transport-only [`wait_ms`](Self::wait_ms), so a retry that waits
767    /// differently is still a retry.
768    #[must_use]
769    pub fn same_invocation(&self, other: &Self) -> bool {
770        let Self {
771            invocation,
772            target,
773            argument,
774            context,
775            confirmation,
776            revision,
777            on_behalf_of,
778            wait_ms: _,
779            appearance,
780            // Evidence of who asked, checked on its own: a retry the caller
781            // signed again is still a retry.
782            signed: _,
783        } = self;
784        *invocation == other.invocation
785            && *target == other.target
786            && *argument == other.argument
787            && *context == other.context
788            && *confirmation == other.confirmation
789            && *revision == other.revision
790            && *on_behalf_of == other.on_behalf_of
791            && *appearance == other.appearance
792    }
793
794    /// An invocation of `target` with `arguments` and nothing else: no context, revision or
795    /// signature, answered once it is admitted.
796    #[must_use]
797    pub fn plain(
798        target: RemoteActionTarget,
799        arguments: serde_json::Map<String, serde_json::Value>,
800    ) -> Self {
801        Self {
802            invocation: InvocationId::new(),
803            target,
804            argument: if arguments.is_empty() {
805                InvokeArgument::None
806            } else {
807                InvokeArgument::Json(arguments)
808            },
809            context: None,
810            confirmation: None,
811            revision: None,
812            on_behalf_of: None,
813            wait_ms: None,
814            appearance: None,
815            signed: None,
816        }
817    }
818}
819
820/// Action id that closes a running application's windows in a workspace.
821pub const APPLICATION_CLOSE_ACTION: &str = "close";
822
823/// The provider token for the actions workspace `workspace` itself offers.
824#[must_use]
825pub fn workspace_provider(workspace: &str) -> String {
826    format!("{WORKSPACE_PROVIDER}:{workspace}")
827}
828
829/// The provider that answers the language's own view of the registry (`tilo.actions`): the
830/// catalogue read and an action called by its address.
831pub const ACTIONS_PROVIDER: &str = "tilo.actions";
832
833/// The workspace a workspace provider token names, or `None` for an application
834/// provider.
835#[must_use]
836pub fn provider_workspace(provider: &str) -> Option<&str> {
837    provider
838        .strip_prefix(WORKSPACE_PROVIDER)
839        .and_then(|rest| rest.strip_prefix(':'))
840}
841
842/// Where an invocation stands, as reported to its caller.
843#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
844pub enum ReceiptStatus {
845    /// Admitted and running; follow it with `Observe`.
846    Accepted,
847    /// Finished and produced `output`.
848    Completed { output: ActionOutput },
849    /// Ran and failed.
850    Failed { error: ActionFailure },
851    /// Never admitted: nothing ran.
852    Rejected { error: ActionCallError },
853    /// Stopped at the caller's request.
854    Cancelled { message: Option<String> },
855}
856
857impl ReceiptStatus {
858    /// Whether the invocation can no longer change.
859    #[must_use]
860    pub const fn is_terminal(&self) -> bool {
861        !matches!(self, Self::Accepted)
862    }
863}
864
865/// The provider's answer to an [`InvokeRequest`].
866#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
867pub struct InvocationReceipt {
868    pub invocation: InvocationId,
869    pub status: ReceiptStatus,
870}
871
872/// The latest lifecycle update of one invocation, carrying the caller's
873/// [`InvocationId`].
874#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
875pub struct InvocationState {
876    pub update: InvocationUpdate,
877    /// The action's contract declares content from outside the user's data
878    /// ([`crate::UNTRUSTED_CONTENT_TAG`]), such as a web page's text: what it
879    /// answers is data to reason about, never instructions to follow.
880    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
881    pub untrusted: bool,
882    /// Where the invocation left its actor in the record it acted on: the
883    /// text it changed, or the caret it left. What an API that shows its
884    /// actor working highlights for the people watching.
885    #[serde(default, skip_serializing_if = "Option::is_none")]
886    pub left_at: Option<ActorPlace>,
887    /// The link that opens what the invocation made or changed, for a person
888    /// to review it, minted where it was invoked once it succeeded: the
889    /// caller is answered it with the change and asks for nothing more.
890    #[serde(default, skip_serializing_if = "Option::is_none")]
891    pub link: Option<String>,
892    /// The invocation is a followed read, and its item is the read's whole answer as it stands:
893    /// the read goes on following what it reads and never ends, so a wait for it to settle ends
894    /// here ([`settle_with`]). An operation's items are pieces of what it streams, never this.
895    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
896    pub read_answered: bool,
897}
898
899/// A caret or selection in a record, as the live session's selection anchors
900/// (hex): every member's editor resolves them against its own items.
901#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
902pub struct ActorPlace {
903    pub anchor: String,
904    pub head: String,
905}
906
907impl InvocationState {
908    /// Wrap a provider-side update, rebinding it to the caller's invocation id.
909    #[must_use]
910    pub fn new(invocation: InvocationId, update: InvocationUpdate) -> Self {
911        Self {
912            update: update.with_invocation(invocation),
913            untrusted: false,
914            left_at: None,
915            link: None,
916            read_answered: false,
917        }
918    }
919
920    /// This state of a followed read: answered once it holds an item, the read's whole answer,
921    /// unless the item says the read is still to come (`"pending": true`, as a reader that has
922    /// not read what it serves yet answers).
923    #[must_use]
924    pub fn of_read(mut self) -> Self {
925        self.read_answered = matches!(
926            &self.update,
927            InvocationUpdate::Item { value, .. }
928                if value.get("pending") != Some(&serde_json::Value::Bool(true))
929        );
930        self
931    }
932
933    /// This state, saying where the invocation left its actor.
934    #[must_use]
935    pub fn left_at(mut self, place: Option<ActorPlace>) -> Self {
936        self.left_at = place;
937        self
938    }
939
940    /// This state, naming the link that opens what it made or changed.
941    #[must_use]
942    pub fn linked(mut self, link: Option<String>) -> Self {
943        self.link = link;
944        self
945    }
946
947    /// This state, saying whether what it answers is untrusted content.
948    #[must_use]
949    pub fn with_untrusted(mut self, untrusted: bool) -> Self {
950        self.untrusted = untrusted;
951        self
952    }
953
954    #[must_use]
955    pub fn invocation(&self) -> InvocationId {
956        self.update.invocation()
957    }
958
959    #[must_use]
960    pub fn is_terminal(&self) -> bool {
961        self.update.is_terminal()
962    }
963
964    /// The receipt this state amounts to: accepted while running, the
965    /// outcome once terminal.
966    #[must_use]
967    pub fn receipt(&self) -> InvocationReceipt {
968        let status = match &self.update {
969            InvocationUpdate::Accepted { .. }
970            | InvocationUpdate::Progress { .. }
971            | InvocationUpdate::Item { .. } => ReceiptStatus::Accepted,
972            InvocationUpdate::Succeeded { output, .. } => ReceiptStatus::Completed {
973                output: output.clone(),
974            },
975            // An action that reached something only the person may allow
976            // stopped before it ran: their answer is what it waits on, which
977            // is a refusal to the caller, not a failure of the action.
978            InvocationUpdate::Failed { error, .. } if error.code == CONFIRMATION_REQUIRED_CODE => {
979                ReceiptStatus::Rejected {
980                    error: ActionCallError::asks(asked::AskedFacts::from_details(
981                        error.details.as_ref(),
982                    )),
983                }
984            }
985            InvocationUpdate::Failed { error, .. } => ReceiptStatus::Failed {
986                error: error.clone(),
987            },
988            InvocationUpdate::Cancelled { message, .. } => ReceiptStatus::Cancelled {
989                message: message.clone(),
990            },
991        };
992        InvocationReceipt {
993            invocation: self.invocation(),
994            status,
995        }
996    }
997}
998
999/// The failure code an action answers while it runs when what it reached
1000/// waits for the person's word ([`ApiError::ConfirmationRequired`]): the
1001/// caller's invocation is refused for want of their answer, and their
1002/// answer runs it again.
1003///
1004/// [`ApiError::ConfirmationRequired`]: crate::api::ApiError::ConfirmationRequired
1005pub const CONFIRMATION_REQUIRED_CODE: &str = "action_confirmation_required";
1006
1007/// The code a caller reads for a call that waits for its person to approve it on a device that
1008/// holds their identity, which its state says ([`asked::ASKED_PHASE`]): it goes on once they
1009/// allow it.
1010pub const AWAITING_APPROVAL: &str = "awaiting_approval";
1011
1012/// The code a server refuses a person it does not know yet with: its operator has not declared
1013/// them an owner, and no invitation of a workspace there brought them in.
1014pub const NOT_ON_THIS_SERVER: &str = "not_on_this_server";
1015
1016/// The code a host that keeps no workspaces of people's own refuses making, deleting or
1017/// branching one with: the operations are the same on every host, and this one says why it does
1018/// not carry them out, in a code a page reads.
1019pub const HOSTS_NONE_FOR_PEOPLE: &str = "hosts_none_for_people";
1020
1021/// The code a workspace refuses a key its person revoked with: nothing it asks is answered
1022/// until they approve another.
1023pub const KEY_REVOKED: &str = "key_revoked";
1024
1025/// What a key that no longer acts (revoked, expired, or no longer granted in its workspace) is
1026/// told to do: the one command that approves a key again.
1027pub const APPROVE_AGAIN: &str = "approve a new key: the person types `tilo do account/keys#create name=\"<name>\"` \
1028     and approves it in their Tilo tab (on their own computer, `tilo login` again)";
1029
1030/// The refusal of a server that does not know `person` (their root key) yet, saying what to do:
1031/// its operator declares them an owner, or they join with an invitation link.
1032#[must_use]
1033pub fn not_on_this_server(person: &[u8; 32]) -> ActionCallError {
1034    let key = hex::encode(person);
1035    ActionCallError::Refused {
1036        reason: format!(
1037            "{NOT_ON_THIS_SERVER}: This server doesn't know you yet: its operator hasn't made you \
1038             an owner, and no invitation brought you into a workspace here. Ask the operator to \
1039             declare your key {key} an owner (on a local stack: `stack.sh owner {key}`), or join \
1040             with an invitation link someone here sends you."
1041        ),
1042    }
1043}
1044
1045/// Why a provider would not do what was asked. Every variant but [`Self::Unanswered`] means
1046/// nothing ran.
1047///
1048/// On the wire it keeps the shape peers decoded before
1049/// [`Self::StaleRevision`] existed: that variant travels as the
1050/// [`Self::InvalidRequest`] those peers sent and understand, and such a
1051/// refusal from them reads back as it. A variant an older peer cannot
1052/// decode would fail its whole frame.
1053#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
1054#[serde(from = "WireActionCallError", into = "WireActionCallError")]
1055pub enum ActionCallError {
1056    /// The provider serves no actions right now (no live apps, service off).
1057    #[error("remote actions are unavailable: {reason}")]
1058    Unavailable { reason: String },
1059    /// The target is not offered to this caller — unknown and forbidden are
1060    /// deliberately the same answer.
1061    #[error("no such action is offered")]
1062    UnknownAction,
1063    /// The caller's authority does not cover the action.
1064    #[error("the caller may not invoke this action")]
1065    NotPermitted,
1066    /// The action waits for a person's yes this request did not carry: what
1067    /// they are shown ([`asked::AskedFacts`]). The dispatch keeps the call as
1068    /// an asked invocation record, and their approve admits it again.
1069    #[error("the action requires confirmation")]
1070    ConfirmationRequired(Box<asked::AskedFacts>),
1071    /// The request is malformed for this action (arguments, input).
1072    #[error("invalid request: {reason}")]
1073    InvalidRequest { reason: String },
1074    /// The target changed since the revision the request named, or the one
1075    /// its provider resolved it against: list it again and invoke what is
1076    /// offered now.
1077    #[error("invalid request: {}", STALE_REVISION_REASON)]
1078    StaleRevision,
1079    /// The invocation id is unknown to this caller.
1080    #[error("no such invocation")]
1081    UnknownInvocation,
1082    /// The invocation id was already used for a different request.
1083    #[error("the invocation id was already used for a different request")]
1084    InvocationConflict,
1085    /// The invocation cannot be cancelled (finished, or never cancellable).
1086    #[error("the invocation cannot be cancelled: {reason}")]
1087    NotCancellable { reason: String },
1088    /// The provider refused for a reason of its own.
1089    #[error("refused: {reason}")]
1090    Refused { reason: String },
1091    /// The workspace is not serving this caller here yet: the same call
1092    /// works once it is (its `serving` state).
1093    #[error("the workspace is not ready for this call yet")]
1094    NotReady,
1095    /// The device or provider that runs the call did not answer in time. Unlike
1096    /// every other variant this one does not say that nothing ran: the same
1097    /// call under the same invocation id is answered by what it did, and runs
1098    /// it once if it never arrived.
1099    #[error("the action's provider did not answer in time")]
1100    Unanswered,
1101}
1102
1103impl ActionCallError {
1104    /// A refusal of the action API ([`crate::api`]) as the action wire says it: the API's own
1105    /// code, so a caller tells "no such action" apart from "not now" and "not shaped like that"
1106    /// without reading prose. An API that refused for a reason of its own says it in words, its
1107    /// code leading them.
1108    #[must_use]
1109    pub fn from_api(error: &crate::ApiError) -> Self {
1110        use crate::ApiError;
1111        match error {
1112            ApiError::Unknown(_) | ApiError::UnregisteredType(_) => Self::UnknownAction,
1113            ApiError::MissingArgument(_)
1114            | ApiError::UnexpectedArgument(_)
1115            | ApiError::InvalidArguments(_)
1116            | ApiError::ArgumentOutOfRange { .. } => Self::InvalidRequest {
1117                reason: error.to_string(),
1118            },
1119            ApiError::ConfirmationRequired => Self::confirmation_required(),
1120            ApiError::Unavailable { .. } | ApiError::Refused { .. } | ApiError::Failed(_) => {
1121                Self::Refused {
1122                    reason: error.to_string(),
1123                }
1124            }
1125        }
1126    }
1127
1128    /// The refusal for want of the person's answer, for an action whose
1129    /// name says all the person is shown.
1130    #[must_use]
1131    pub fn confirmation_required() -> Self {
1132        Self::asks(asked::AskedFacts::default())
1133    }
1134
1135    /// The refusal for want of the person's answer, showing them `facts`.
1136    #[must_use]
1137    pub fn asks(facts: asked::AskedFacts) -> Self {
1138        Self::ConfirmationRequired(Box::new(facts))
1139    }
1140
1141    /// The provider refused for a reason of its own.
1142    #[must_use]
1143    pub fn refused(reason: impl Into<String>) -> Self {
1144        Self::Refused {
1145            reason: reason.into(),
1146        }
1147    }
1148
1149    /// What the provider said in its own words, for the person reading it: the reason a refusal
1150    /// of its own carries, without the code a caller matches on, else the sentence of its variant.
1151    #[must_use]
1152    pub fn own_words(&self) -> String {
1153        match self {
1154            Self::Refused { reason } => reason.clone(),
1155            other => other.to_string(),
1156        }
1157    }
1158
1159    /// The request is malformed for this action.
1160    #[must_use]
1161    pub fn invalid_request(reason: impl Into<String>) -> Self {
1162        Self::InvalidRequest {
1163            reason: reason.into(),
1164        }
1165    }
1166
1167    /// The provider serves no actions right now.
1168    #[must_use]
1169    pub fn unavailable(reason: impl Into<String>) -> Self {
1170        Self::Unavailable {
1171            reason: reason.into(),
1172        }
1173    }
1174
1175    /// Stable machine-readable code.
1176    #[must_use]
1177    pub const fn code(&self) -> &'static str {
1178        match self {
1179            Self::Unavailable { .. } => "remote_actions_unavailable",
1180            Self::UnknownAction => "unknown_action",
1181            Self::NotPermitted => "not_permitted",
1182            Self::ConfirmationRequired(_) => "action_confirmation_required",
1183            Self::InvalidRequest { .. } => "invalid_arguments",
1184            Self::StaleRevision => "stale_revision",
1185            Self::UnknownInvocation => "unknown_invocation",
1186            Self::InvocationConflict => "invocation_conflict",
1187            Self::NotCancellable { .. } => "not_cancellable",
1188            Self::Refused { .. } => "refused",
1189            Self::NotReady => "not_ready",
1190            Self::Unanswered => "unanswered",
1191        }
1192    }
1193
1194    /// This refusal as a caller is told it: the code the API documents
1195    /// (`docs/tilo-sh/errors.md`), then what happened, so a caller reading the
1196    /// typed answer gets the code and one reading the text still reads a
1197    /// sentence that says what to do.
1198    #[must_use]
1199    pub fn said(&self) -> String {
1200        match self {
1201            // A caller that retries the same stale revision fails the same way:
1202            // what to do instead is said.
1203            Self::StaleRevision => "stale_revision: the resource changed since you read it. \
1204                Call the action again with tilo_do, which runs it against the resource as it \
1205                is now, or tilo_read the resource first to see what changed"
1206                .to_owned(),
1207            // Refused by the workspace's permissions: said as that, with where it is
1208            // changed, never as an action the caller cannot name.
1209            Self::NotPermitted => {
1210                format!("not_permitted: {}", crate::Availability::NOT_ALLOWED_HERE)
1211            }
1212            // What the host could not run now is `unavailable`, the code the API
1213            // documents; the host's own words follow rather than a restatement.
1214            Self::Unavailable { reason } => format!("unavailable: {reason}"),
1215            // No answer is not an answer that nothing is there: a workspace that just
1216            // started may still be opening its documents, and answers when asked again.
1217            Self::Unanswered => "unanswered: the workspace did not answer in time; it may \
1218                still be opening its documents after it started, so ask again"
1219                .to_owned(),
1220            Self::InvalidRequest { reason } | Self::Refused { reason } => {
1221                format!("{}: {reason}", self.code())
1222            }
1223            other => format!("{}: {other}", other.code()),
1224        }
1225    }
1226
1227    /// Whether the same call, under the same invocation id, is worth making
1228    /// again: once the workspace serves the caller ([`Self::NotReady`]), or at
1229    /// once ([`Self::Unanswered`]).
1230    #[must_use]
1231    pub const fn ask_again(&self) -> bool {
1232        matches!(self, Self::NotReady | Self::Unanswered)
1233    }
1234
1235    /// Whether `code` is the [`code`](Self::code) of a refusal the same call is asked again
1236    /// for ([`Self::ask_again`]), as a failed invocation carries it.
1237    #[must_use]
1238    pub fn ask_again_code(code: &str) -> bool {
1239        code == Self::NotReady.code() || code == Self::Unanswered.code()
1240    }
1241
1242    /// Whether the provider refused a directory action that asks for
1243    /// confirmation because the request named no revision
1244    /// ([`CONFIRMED_ACTION_NEEDS_REVISION`]).
1245    #[must_use]
1246    pub fn needs_revision(&self) -> bool {
1247        matches!(self, Self::InvalidRequest { reason } if reason == CONFIRMED_ACTION_NEEDS_REVISION)
1248    }
1249}
1250
1251/// What [`ActionCallError::StaleRevision`] says, and the reason it carries
1252/// on the wire as an [`ActionCallError::InvalidRequest`].
1253pub const STALE_REVISION_REASON: &str = "the target changed since that revision; list it again";
1254
1255/// [`ActionCallError`] as it travels: only variants every peer decodes.
1256#[derive(Serialize, Deserialize)]
1257#[serde(rename = "ActionCallError")]
1258enum WireActionCallError {
1259    Unavailable { reason: String },
1260    UnknownAction,
1261    NotPermitted,
1262    ConfirmationRequired(Box<asked::AskedFacts>),
1263    InvalidRequest { reason: String },
1264    UnknownInvocation,
1265    InvocationConflict,
1266    NotCancellable { reason: String },
1267    Refused { reason: String },
1268    NotReady,
1269    Unanswered,
1270}
1271
1272impl From<ActionCallError> for WireActionCallError {
1273    fn from(error: ActionCallError) -> Self {
1274        match error {
1275            ActionCallError::Unavailable { reason } => Self::Unavailable { reason },
1276            ActionCallError::UnknownAction => Self::UnknownAction,
1277            ActionCallError::NotPermitted => Self::NotPermitted,
1278            ActionCallError::ConfirmationRequired(facts) => Self::ConfirmationRequired(facts),
1279            ActionCallError::InvalidRequest { reason } => Self::InvalidRequest { reason },
1280            ActionCallError::StaleRevision => Self::InvalidRequest {
1281                reason: STALE_REVISION_REASON.to_owned(),
1282            },
1283            ActionCallError::UnknownInvocation => Self::UnknownInvocation,
1284            ActionCallError::InvocationConflict => Self::InvocationConflict,
1285            ActionCallError::NotCancellable { reason } => Self::NotCancellable { reason },
1286            ActionCallError::Refused { reason } => Self::Refused { reason },
1287            ActionCallError::NotReady => Self::NotReady,
1288            ActionCallError::Unanswered => Self::Unanswered,
1289        }
1290    }
1291}
1292
1293impl From<WireActionCallError> for ActionCallError {
1294    fn from(error: WireActionCallError) -> Self {
1295        match error {
1296            WireActionCallError::InvalidRequest { reason } if reason == STALE_REVISION_REASON => {
1297                Self::StaleRevision
1298            }
1299            WireActionCallError::Unavailable { reason } => Self::Unavailable { reason },
1300            WireActionCallError::UnknownAction => Self::UnknownAction,
1301            WireActionCallError::NotPermitted => Self::NotPermitted,
1302            WireActionCallError::ConfirmationRequired(facts) => Self::ConfirmationRequired(facts),
1303            WireActionCallError::InvalidRequest { reason } => Self::InvalidRequest { reason },
1304            WireActionCallError::UnknownInvocation => Self::UnknownInvocation,
1305            WireActionCallError::InvocationConflict => Self::InvocationConflict,
1306            WireActionCallError::NotCancellable { reason } => Self::NotCancellable { reason },
1307            WireActionCallError::Refused { reason } => Self::Refused { reason },
1308            WireActionCallError::NotReady => Self::NotReady,
1309            WireActionCallError::Unanswered => Self::Unanswered,
1310        }
1311    }
1312}
1313
1314/// What `provider` says of `invocation`, read off the runtime's worker when one drives the
1315/// caller. A provider that asks a device waits for the runtime to carry its answer, and a wait on
1316/// a worker stops that task: enough callers waiting at once deadlock until each deadline.
1317#[cfg_attr(
1318    any(target_arch = "wasm32", not(feature = "off-worker")),
1319    expect(
1320        clippy::unused_async,
1321        reason = "only a host with `off-worker` runs a runtime whose worker there is to leave"
1322    )
1323)]
1324pub async fn observed_off_the_worker<P>(
1325    provider: P,
1326    caller: Caller,
1327    invocation: InvocationId,
1328) -> Option<InvocationState>
1329where
1330    P: ActionProvider + Send + 'static,
1331{
1332    #[cfg(all(not(target_arch = "wasm32"), feature = "off-worker"))]
1333    if tokio::runtime::Handle::try_current().is_ok() {
1334        return tokio::task::spawn_blocking(move || provider.observe(&caller, &invocation))
1335            .await
1336            .ok()
1337            .flatten();
1338    }
1339    provider.observe(&caller, &invocation)
1340}
1341
1342/// A tool call an agent's session runs, as the host keeps it
1343/// ([`ActionProvider::tool_started`]): the invocation its person reads while the
1344/// call runs and may stop. The session holds it around the tool's own work and
1345/// tells the host how that ended.
1346pub struct RunningTool {
1347    /// Resolves when the person stops the call.
1348    pub stopped: Pending<Result<(), ActionCallError>>,
1349    /// The stop their record noted, read by a session whose call answered before it saw
1350    /// `stopped`: a call the person stopped ends cancelled all the same.
1351    stop_noted: std::sync::Arc<std::sync::atomic::AtomicBool>,
1352    end: Option<Box<dyn FnOnce(bool) + Send + Sync>>,
1353}
1354
1355impl RunningTool {
1356    /// A tool call whose `stopped` resolves when its person stops it, `stop_noted` says
1357    /// whether the stop reached its record, and `end` the host runs once the call ended,
1358    /// `true` where it was stopped.
1359    #[must_use]
1360    pub fn new(
1361        stopped: Pending<Result<(), ActionCallError>>,
1362        stop_noted: std::sync::Arc<std::sync::atomic::AtomicBool>,
1363        end: impl FnOnce(bool) + Send + Sync + 'static,
1364    ) -> Self {
1365        Self {
1366            stopped,
1367            stop_noted,
1368            end: Some(Box::new(end)),
1369        }
1370    }
1371
1372    /// Whether its person's stop reached its record.
1373    #[must_use]
1374    pub fn was_stopped(&self) -> bool {
1375        self.stop_noted.load(std::sync::atomic::Ordering::Acquire)
1376    }
1377
1378    /// Note that the call ended: run to its end, or stopped by its person.
1379    pub fn ended(mut self, stopped: bool) {
1380        if let Some(end) = self.end.take() {
1381            end(stopped);
1382        }
1383    }
1384}
1385
1386impl Drop for RunningTool {
1387    /// A call nobody waited for any more (its client disconnected) ended unwatched: its record
1388    /// says so rather than staying running forever.
1389    fn drop(&mut self) {
1390        if let Some(end) = self.end.take() {
1391            end(false);
1392        }
1393    }
1394}
1395
1396/// A peer that runs actions on behalf of authenticated remote callers.
1397///
1398/// Implementations resolve authority from `caller` alone and must be
1399/// idempotent per [`InvocationId`]: invoking an id again with the same
1400/// request reports the original invocation, with a different request fails
1401/// with [`ActionCallError::InvocationConflict`]. [`InvocationLog`]
1402/// implements that rule.
1403pub trait ActionProvider {
1404    /// End this admitted transport run without cancelling its app jobs.
1405    fn retire_execution(&self, caller: &Caller) {
1406        caller.retire_execution();
1407    }
1408
1409    /// Whether this provider answers the actions published under `provider`, the name a request
1410    /// targets. A device's dispatcher answers its workspace's own, and a provider a device's
1411    /// action service serves beside it (`ActionService::add_provider`) answers the one it names,
1412    /// so one request reaches the provider it was meant for.
1413    fn serves(&self, provider: &str) -> bool {
1414        let _ = provider;
1415        false
1416    }
1417
1418    /// The resources this provider publishes under fixed addresses, with every action it
1419    /// answers on them: what a device registers with it, so a call naming one of those
1420    /// addresses reaches it whichever app the caller named, and what another language compiles
1421    /// its calls against ([`ProvidedPackage`]). Empty for a provider whose resources are
1422    /// found only by querying it.
1423    fn published(&self) -> Vec<crate::ResourceSpec> {
1424        Vec::new()
1425    }
1426
1427    /// One page of what `caller` is offered. An action the caller may not
1428    /// invoke is absent, not flagged.
1429    fn query(
1430        &self,
1431        caller: &Caller,
1432        query: CatalogueQuery,
1433    ) -> Pending<Result<CataloguePage, ActionCallError>>;
1434
1435    /// Admit and start one invocation, or report the one already admitted
1436    /// under the same id. Never blocks: the answer is the admission (an
1437    /// accepted receipt, an immediate outcome, or a refusal) once the provider
1438    /// has it; completion is followed with [`Self::observe`].
1439    fn invoke(
1440        &self,
1441        caller: &Caller,
1442        request: InvokeRequest,
1443    ) -> Pending<Result<InvocationReceipt, ActionCallError>>;
1444
1445    /// `caller`'s session starts the tool call `tool` under `id`: what a host that
1446    /// records its invocations keeps as one of the agent's, so the person reads it
1447    /// while it runs and may stop it. The session holds the answer around the
1448    /// tool's own work. `None` for a host that keeps no such record, or none for
1449    /// this caller.
1450    fn tool_started(&self, caller: &Caller, id: &InvocationId, tool: &str) -> Option<RunningTool> {
1451        let _ = (caller, id, tool);
1452        None
1453    }
1454
1455    /// The latest state of an invocation `caller` started, or `None` for an
1456    /// id this caller does not own.
1457    fn observe(&self, caller: &Caller, id: &InvocationId) -> Option<InvocationState>;
1458
1459    /// The state [`Self::observe`] answered for `id` was read for `caller`'s call, on the
1460    /// caller's own thread: what a provider that counts the looks a tool makes of it keeps here.
1461    fn observed(&self, caller: &Caller, id: &InvocationId, state: Option<&InvocationState>) {
1462        let _ = (caller, id, state);
1463    }
1464
1465    /// Resolves the next time invocation `id` (owned by `caller`) may have
1466    /// changed state, so a waiter observes it again then instead of on a
1467    /// timer. `None` when this provider cannot tell; the caller then observes on
1468    /// its own schedule.
1469    ///
1470    /// Wakeups may be spurious: the waiter must [`observe`](Self::observe)
1471    /// again and tolerate finding nothing new. A provider that answers `Some`
1472    /// must resolve it within a bounded interval even when nothing changes
1473    /// (the broker's is a second), so a change it failed to signal costs
1474    /// latency, never a stalled waiter: a waiting answer ([`settle_with`])
1475    /// checks its deadline only when woken.
1476    fn next_change(&self, caller: &Caller, id: &InvocationId) -> Option<Pending<()>> {
1477        let _ = (caller, id);
1478        None
1479    }
1480
1481    /// Where `caller`'s workspace and this device's writes stand on the session that serves
1482    /// it; `None` for a provider that serves from no session.
1483    fn session_state(&self, caller: &Caller) -> Option<SessionState> {
1484        let _ = caller;
1485        None
1486    }
1487
1488    /// Resolves the next time [`Self::session_state`] changed, so a waiter reads it again then
1489    /// instead of on a timer; `None` when this provider cannot tell. It may never resolve when
1490    /// nothing changes: a waiter bounds its own wait.
1491    fn session_state_changed(&self, caller: &Caller) -> Option<Pending<()>> {
1492        let _ = caller;
1493        None
1494    }
1495
1496    /// Resolves the next time what a watch of the workspace follows under `scope` may have
1497    /// changed, so a waiter reads it again then instead of on a timer; `None` when this provider
1498    /// cannot tell, and the waiter then waits until its own deadline.
1499    ///
1500    /// Wakeups may be spurious: the waiter reads again and tolerates finding nothing new. A provider
1501    /// that answers `Some` must resolve it within a bounded interval even when nothing changes,
1502    /// so a change it failed to signal costs latency rather than a stalled waiter. A wait the
1503    /// provider finds it cannot follow after all (the device it asks refuses it, or cannot be
1504    /// asked) resolves at once with why: the waiter is told, never left to its deadline.
1505    fn changed(
1506        &self,
1507        caller: &Caller,
1508        scope: WatchScope,
1509    ) -> Option<Pending<Result<(), ActionCallError>>> {
1510        let _ = (caller, scope);
1511        None
1512    }
1513
1514    /// Ask a running invocation to stop, answered once the provider has kept
1515    /// the request as durably as it keeps the invocation.
1516    ///
1517    /// # Errors
1518    ///
1519    /// Returns [`ActionCallError::UnknownInvocation`] for an id this caller
1520    /// does not own, or [`ActionCallError::NotCancellable`].
1521    fn cancel(&self, caller: &Caller, id: &InvocationId) -> Pending<Result<(), ActionCallError>>;
1522
1523    /// Where this provider's callers put content into their workspace's content
1524    /// store ([`ContentPuts`]); `None` for a provider without one.
1525    fn content_puts(&self) -> Option<std::sync::Arc<dyn ContentPuts>> {
1526        None
1527    }
1528
1529    /// Where this provider's callers put content the action `target` names reads: an action of
1530    /// the caller's own device keeps what it reads there, and its provider says so with a store
1531    /// of its own. Everything else a put is for reads the store [`Self::content_puts`] names,
1532    /// which is what a provider that keeps no store of its own answers.
1533    fn content_puts_for(
1534        &self,
1535        target: Option<&RemoteActionTarget>,
1536    ) -> Option<std::sync::Arc<dyn ContentPuts>> {
1537        let _ = target;
1538        self.content_puts()
1539    }
1540
1541    /// Where this provider's callers read content back out of their workspace's
1542    /// content store ([`ContentGets`]); `None` for a provider without one.
1543    fn content_gets(&self) -> Option<std::sync::Arc<dyn ContentGets>> {
1544        None
1545    }
1546
1547    /// The client of a connection this provider admits named itself `client` in its
1548    /// `initialize` (its product's name, `Claude Code`): a host that keeps the workspace's agents
1549    /// answers what that names from then on, and a host that names its own connections has
1550    /// nothing to do here.
1551    fn introduced(&self, caller: &Caller, client: &str) {
1552        let _ = (caller, client);
1553    }
1554
1555    /// Who is in the workspace now, as this provider's collaboration knows it:
1556    /// its people and the agents its roster names. `None` for a provider that
1557    /// keeps no roster, which reports no presence rather than an empty one.
1558    fn here(&self, caller: &Caller) -> Option<Vec<Here>> {
1559        let _ = caller;
1560        None
1561    }
1562
1563    /// Where an agent task reads its workspace's records outside their apps ([`ResourceReads`]);
1564    /// `None` for a provider without them. The resources a provider publishes itself (a desktop's
1565    /// device, its windows, its styles, Settings' sections) are read on the same API, as a
1566    /// [`ResourceCopy::Reading`], so a program and the shell's parts read one resource one way.
1567    fn resource_reads(&self) -> Option<std::sync::Arc<dyn ResourceReads>> {
1568        None
1569    }
1570
1571    /// Where the process this provider serves reads and writes its app's records
1572    /// ([`StoreCommands`]): an app's own connection to its device. `None` for every other
1573    /// provider.
1574    fn store_commands(&self) -> Option<std::sync::Arc<dyn StoreCommands>> {
1575        None
1576    }
1577
1578    /// Every change to the records of a caller's workspace, as this provider
1579    /// keeps them ([`ChangeFeed`]): what a watch of the whole workspace
1580    /// reads. `None` for a provider that keeps no records.
1581    fn change_feed(&self) -> Option<std::sync::Arc<dyn ChangeFeed>> {
1582        None
1583    }
1584
1585    /// The surface the signed package `app_id` the workspace installed
1586    /// publishes, running or not: what an agent reads its types from, and a
1587    /// change of its records is decided against, before the app opens.
1588    fn installed_surface(&self, app_id: &str) -> Pending<Option<Vec<u8>>> {
1589        let _ = app_id;
1590        Pending::ready(None)
1591    }
1592
1593    /// The action at `address` as one invocation with `argument` (its slot form) is: `None` for the
1594    /// action as this provider's catalogue describes it. A provider whose action is riskier for
1595    /// some values than others (a setting that weakens the person's security) answers it as that
1596    /// value makes it, so the dispatch asks the person first.
1597    fn invocation(
1598        &self,
1599        address: &crate::ActionAddress,
1600        argument: Option<&str>,
1601    ) -> Option<crate::api::ActionDescriptor> {
1602        let _ = (address, argument);
1603        None
1604    }
1605
1606    /// Carry out `request`, which this device's dispatch admitted for `caller`, with what the
1607    /// dispatch knows of the call ([`Admitted`]). By default it is [`Self::invoke`]d.
1608    fn run(
1609        &self,
1610        caller: &Caller,
1611        request: InvokeRequest,
1612        admitted: Admitted,
1613    ) -> Pending<Result<InvocationReceipt, ActionCallError>> {
1614        let _ = admitted;
1615        self.invoke(caller, request)
1616    }
1617
1618    /// Before the dispatch takes `request`, a call nobody approved yet: whether it waits for its
1619    /// person's yes ([`asked::approved_or_asks`]), where this provider knows that only by looking
1620    /// at the call itself (a program, by running it provisionally). The dispatch takes the call
1621    /// once this answers `Ok`, and keeps one refused for want of the yes as its asked record, which
1622    /// an approve sends here again, carrying [`InvokeRequest::approval`]. `admitted` is what the
1623    /// dispatch knows of the call. `None` for a provider that decides nothing before it runs.
1624    fn asks_first(
1625        &self,
1626        caller: &Caller,
1627        request: &InvokeRequest,
1628        admitted: &Admitted,
1629    ) -> Option<Pending<Result<(), ActionCallError>>> {
1630        let _ = (caller, request, admitted);
1631        None
1632    }
1633
1634    /// Follow `request`, an admitted call of an action whose contract is
1635    /// [`ExecutionMode::Live`](crate::ExecutionMode::Live): how to read its result as it is now,
1636    /// and when that may have changed.
1637    ///
1638    /// # Errors
1639    ///
1640    /// The action has no live result here, or `caller` may not follow it.
1641    fn watch(&self, caller: &Caller, request: &InvokeRequest) -> Result<LiveView, String> {
1642        let _ = (caller, request);
1643        Err("this action has no live result".into())
1644    }
1645}
1646
1647/// Whether `value` is the zero an asker that names no ask uses: left out of
1648/// the bytes, as it always was.
1649#[allow(
1650    clippy::trivially_copy_pass_by_ref,
1651    reason = "serde hands a skipped field to it by reference"
1652)]
1653const fn is_zero(value: &u64) -> bool {
1654    *value == 0
1655}
1656
1657/// An answer to an [`RemoteActionMessage::Observe`], naming the ask it answers.
1658fn updated(
1659    correlation: u64,
1660    invocation: InvocationId,
1661    state: Option<InvocationState>,
1662) -> RemoteActionMessage {
1663    RemoteActionMessage::Update {
1664        invocation,
1665        state,
1666        correlation: Some(correlation),
1667    }
1668}
1669
1670/// Everything that crosses the wire for remote action use.
1671#[allow(
1672    clippy::large_enum_variant,
1673    reason = "a message is built, encoded once and dropped; boxing would only add noise to every constructor and match"
1674)]
1675#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1676pub enum RemoteActionMessage {
1677    /// A retired ask for a feedback report's receipt: nothing answers it but
1678    /// [`Self::RetiredFeedbackResponse`]. A report is filed as Chat's
1679    /// `report`, answered as any action is.
1680    RetiredFeedbackRequest { correlation: u64 },
1681    /// The answer to a [`Self::RetiredFeedbackRequest`], refusing it.
1682    RetiredFeedbackResponse { correlation: u64 },
1683    /// Ask for one page of the actions offered to the caller.
1684    CatalogueRequest {
1685        correlation: u64,
1686        #[serde(default)]
1687        query: CatalogueQuery,
1688    },
1689    /// Answer to a [`Self::CatalogueRequest`] with the same correlation.
1690    CatalogueResponse {
1691        correlation: u64,
1692        result: Result<CataloguePage, ActionCallError>,
1693    },
1694    /// Invocation one action.
1695    Invoke(InvokeRequest),
1696    /// Answer to [`Self::Invoke`]; a refusal is [`ReceiptStatus::Rejected`].
1697    Receipt(InvocationReceipt),
1698    /// Ask for an invocation's latest state.
1699    Observe {
1700        /// Names this ask, so its [`Self::Update`] answers it and no other: a
1701        /// caller that gave up on one ask and sent another must not mistake
1702        /// the first one's late answer — which may carry the state it already
1703        /// saw — for its own. An asker that names none keeps the bytes it
1704        /// always sent.
1705        #[serde(default, skip_serializing_if = "is_zero")]
1706        correlation: u64,
1707        invocation: InvocationId,
1708        /// Hold the answer until the invocation moves past `seen` (or, with
1709        /// no `seen`, settles) or this many milliseconds pass, at most
1710        /// [`MAX_REMOTE_WAIT`]; then answer with the state as it is. A provider
1711        /// that predates it answers at once, as before.
1712        #[serde(default, skip_serializing_if = "Option::is_none")]
1713        wait_ms: Option<u32>,
1714        /// How far the caller has already seen the invocation get.
1715        #[serde(default, skip_serializing_if = "Option::is_none")]
1716        seen: Option<UpdateMark>,
1717    },
1718    /// Answer to [`Self::Observe`]; `None` for an id the caller does not own.
1719    /// A provider may also push this unprompted as an invocation progresses.
1720    Update {
1721        invocation: InvocationId,
1722        state: Option<InvocationState>,
1723        /// The ask this answers, as it named itself; absent for a push, and
1724        /// for a provider that predates named asks.
1725        #[serde(default, skip_serializing_if = "Option::is_none")]
1726        correlation: Option<u64>,
1727    },
1728    /// Ask a running invocation to stop.
1729    Cancel { invocation: InvocationId },
1730    /// Answer to [`Self::Cancel`].
1731    CancelResponse {
1732        invocation: InvocationId,
1733        result: Result<(), ActionCallError>,
1734    },
1735    /// Ask the person, on one of their own devices ([`ConfirmationQuestion`]).
1736    ConfirmationRequest {
1737        correlation: u64,
1738        question: ConfirmationQuestion,
1739    },
1740    /// Answer to [`Self::ConfirmationRequest`], same correlation.
1741    ConfirmationResponse {
1742        correlation: u64,
1743        result: Result<ConfirmationReply, ActionCallError>,
1744    },
1745    /// What the surface offers changed: the page it lists now, sent without
1746    /// being asked, so the provider that placed it reads what the surface can do
1747    /// as it is rather than as it was when it first joined.
1748    CatalogueChanged { page: CataloguePage },
1749    /// One step of putting bytes into the content store of the device's
1750    /// workspace ([`ContentPutStep`]): how a client of another device's
1751    /// actions (an agent's MCP session through its own device) hands it a
1752    /// file an action then names by `tilo.content:<hash>`.
1753    ContentPutRequest {
1754        correlation: u64,
1755        step: ContentPutStep,
1756    },
1757    /// Answer to [`Self::ContentPutRequest`] with the same correlation.
1758    ContentPutResponse {
1759        correlation: u64,
1760        result: Result<ContentPutAnswer, ActionCallError>,
1761    },
1762    /// Ask the device for a piece of content in its workspace's store: what a
1763    /// client of another device's actions (an agent's MCP session through its
1764    /// own device) downloads a file by, having the file's
1765    /// `tilo.content:<hash>` reference.
1766    ContentGetRequest {
1767        correlation: u64,
1768        /// The content's reference, `tilo.content:<hash>`.
1769        content: String,
1770        /// Where in the content the piece starts.
1771        offset: u64,
1772        /// How many bytes the piece may carry; zero asks for one piece's
1773        /// worth ([`MAX_CONTENT_FRAME_BYTES`]).
1774        length: u64,
1775    },
1776    /// Answer to [`Self::ContentGetRequest`] with the same correlation.
1777    ContentGetResponse {
1778        correlation: u64,
1779        result: Result<ContentGetAnswer, ActionCallError>,
1780    },
1781    /// Read a record of the workspace `read` names through the one record API
1782    /// ([`ResourceReads`]), decided there as every reader of it is; continuing
1783    /// `on_behalf_of`, an invocation the provider delivered to the caller, it is
1784    /// that invocation's caller's read. Where its answer is a decision
1785    /// ([`ReadAnswer::Decision`], [`ReadAnswer::WriteDecision`]), it asks only whether the caller
1786    /// may read or change the record.
1787    ResourceRead {
1788        correlation: u64,
1789        #[serde(default, skip_serializing_if = "Option::is_none")]
1790        on_behalf_of: Option<InvocationId>,
1791        read: ResourceReadRequest,
1792    },
1793    /// Answer to [`Self::ResourceRead`], same correlation: the readings as
1794    /// JSON text (`ResourceReadings::readable`).
1795    ResourceReading {
1796        correlation: u64,
1797        result: Result<String, ActionCallError>,
1798    },
1799    /// Ask for the changes to the caller's workspace's records after
1800    /// `after`, a cursor an earlier answer gave ([`ActionProvider::change_feed`]).
1801    ChangesRequest {
1802        correlation: u64,
1803        #[serde(default, skip_serializing_if = "Option::is_none")]
1804        after: Option<String>,
1805    },
1806    /// Answer to [`Self::ChangesRequest`], same correlation.
1807    ChangesResponse {
1808        correlation: u64,
1809        result: Result<ChangePage, ActionCallError>,
1810    },
1811    /// Ask for the surface `app`'s signed package publishes, as its text.
1812    SurfaceRequest { correlation: u64, app: String },
1813    /// Answer to [`Self::SurfaceRequest`]: the text, when the workspace has it.
1814    SurfaceResponse {
1815        correlation: u64,
1816        result: Result<Option<String>, ActionCallError>,
1817    },
1818    /// Ask the device for a link its web origin serves the content of
1819    /// `link.files` at, for a little while ([`ContentLink`]): what a page
1820    /// drags a file out by, and saves a large one through.
1821    ContentLinkRequest {
1822        correlation: u64,
1823        link: ContentLinkAsk,
1824    },
1825    /// Answer to [`Self::ContentLinkRequest`] with the same correlation.
1826    ContentLinkResponse {
1827        correlation: u64,
1828        result: Result<ContentLink, ActionCallError>,
1829    },
1830    /// Ask the device to answer when what a watch follows under `scope` may have
1831    /// changed ([`ActionProvider::changed`]): a write landed in the workspace's records,
1832    /// or who is in it moved.
1833    ChangedRequest { correlation: u64, scope: WatchScope },
1834    /// Answer to [`Self::ChangedRequest`], same correlation: it may have changed, or
1835    /// why this provider cannot tell when it does.
1836    ChangedResponse {
1837        correlation: u64,
1838        result: Result<(), ActionCallError>,
1839    },
1840    /// Ask the device to carry an outside service's call into a workspace call from now on, or,
1841    /// with no pair, to let go of the one it carries ([`call`]). Decided by the app's grants and
1842    /// held to the call's rule; a device that carries no call for this app refuses.
1843    CallCarryRequest {
1844        correlation: u64,
1845        #[serde(default, skip_serializing_if = "Option::is_none")]
1846        pair: Option<call::BridgedCall>,
1847    },
1848    /// Answer to [`Self::CallCarryRequest`], same correlation.
1849    CallCarryResponse {
1850        correlation: u64,
1851        result: Result<(), ActionCallError>,
1852    },
1853    /// What the app's service says of its calls: who is in each, where the bridge stands, and
1854    /// the line its people see.
1855    CallReport {
1856        correlation: u64,
1857        report: call::CallReport,
1858    },
1859    /// Answer to [`Self::CallReport`], same correlation.
1860    CallReportResponse {
1861        correlation: u64,
1862        result: Result<(), ActionCallError>,
1863    },
1864    /// One Opus frame an outside person said, for the workspace call.
1865    CallHeard(call::CallAudio),
1866    /// One Opus frame a workspace participant said, for the outside call. Sent by the device,
1867    /// never asked for.
1868    CallSaid(call::CallAudio),
1869    /// What the device says the outside call should show of who is on the workspace's side.
1870    /// Sent by the device, never asked for.
1871    CallStatus(call::CallStatus),
1872    /// One command for the device's sound output, on the line an app's launcher handed it. A
1873    /// write's PCM follows the frame as its binary body ([`audio_output::Request::body_len`]).
1874    AudioOutputRequest {
1875        correlation: u64,
1876        command: audio_output::Request,
1877    },
1878    /// Answer to [`Self::AudioOutputRequest`], same correlation.
1879    AudioOutputResponse {
1880        correlation: u64,
1881        result: Result<audio_output::Snapshot, ActionCallError>,
1882    },
1883    /// One command to the records of the app the connection is, in the device's one store
1884    /// ([`StoreCommands`]): `collab_types::store::wire::Command` as JSON. What an app's process
1885    /// reads and writes its records by. The app is the one the device started the connection's
1886    /// process as, never one the frame names, and the workspace is the frame's
1887    /// ([`RemoteActionFrame::workspace`]).
1888    StoreRequest {
1889        correlation: u64,
1890        command: serde_json::Value,
1891        /// The kind a record the command founds is of, as the app names it; a record of a kind
1892        /// its manifest does not declare is not founded.
1893        #[serde(default, skip_serializing_if = "Option::is_none")]
1894        kind: Option<String>,
1895    },
1896    /// Answer to [`Self::StoreRequest`], same correlation: the store's
1897    /// `collab_types::store::wire::Reply` as JSON.
1898    StoreResponse {
1899        correlation: u64,
1900        result: Result<serde_json::Value, ActionCallError>,
1901    },
1902    /// One command of the call the app takes part in itself, on the line its launcher handed it
1903    /// ([`native_media::Request`]): joining a workspace's call, muting, the camera and screen it
1904    /// sends, which pictures its view draws, and the status it shows.
1905    CallMediaRequest {
1906        correlation: u64,
1907        request: native_media::Request,
1908    },
1909    /// Answer to [`Self::CallMediaRequest`], same correlation.
1910    CallMediaResult {
1911        correlation: u64,
1912        result: Result<native_media::Snapshot, ActionCallError>,
1913    },
1914    /// What an app says of its person in its workspace, on the line its launcher handed it: one
1915    /// word under the key it is said under, as `collab_types::presence::Said` JSON. The device
1916    /// says it for the connection's app, workspace and member in the workspace's live session,
1917    /// where the shell's own words go, so every other device of the workspace hears it.
1918    PresenceSaid { correlation: u64, said: String },
1919    /// Answer to [`Self::PresenceSaid`], same correlation: whether the device's live presence
1920    /// said the word, and why it refused it when it did not.
1921    PresenceSaidResult {
1922        correlation: u64,
1923        result: Result<(), ActionCallError>,
1924    },
1925    /// What another member said in the app's workspace, as the workspace's live session heard
1926    /// it from another device: one `collab_types::presence::Heard` as JSON, pushed, never asked.
1927    PresenceHeard { heard: String },
1928    /// Ask the device to open a shell its shell runtime runs, carried on this connection from
1929    /// now on ([`shell`]). Decided by the app's signed manifest; a connection that is no app's
1930    /// own carries no shell.
1931    ShellOpenRequest {
1932        correlation: u64,
1933        open: shell::ShellOpen,
1934    },
1935    /// Answer to [`Self::ShellOpenRequest`], same correlation.
1936    ShellOpenResponse {
1937        correlation: u64,
1938        result: Result<shell::ShellOpened, ActionCallError>,
1939    },
1940    /// What the app typed into one of its shells.
1941    ShellInput(shell::ShellBytes),
1942    /// One of the app's shells' windows is now this size, in cells.
1943    ShellResize { shell: u64, cols: u16, rows: u16 },
1944    /// The app lets one of its shells go.
1945    ShellClose { shell: u64 },
1946    /// What one of the app's shells printed. Sent by the device, never asked for.
1947    ShellOutput(shell::ShellBytes),
1948    /// How one of the app's shells ended: the last the device says of it. Sent by the device,
1949    /// never asked for.
1950    ShellEnded(shell::ShellEnded),
1951}
1952
1953/// One record a reader asks for over the action API: alone, or `joined`
1954/// as the chain of parts whose base it is, once it differs from the revision
1955/// `after` or `wait_ms` passed.
1956#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1957pub struct ResourceReadRequest {
1958    /// The workspace the record is in: part of its address, so a read is decided at that
1959    /// workspace's record node, never by which workspace the connection was admitted to.
1960    pub workspace: String,
1961    /// The app whose record it is.
1962    pub app: String,
1963    /// Its id there; empty for the app's record of the workspace.
1964    pub record: String,
1965    #[serde(default)]
1966    pub joined: bool,
1967    #[serde(default, skip_serializing_if = "Option::is_none")]
1968    pub after: Option<String>,
1969    /// How long to wait for a write past `after`, at most [`MAX_REMOTE_WAIT`].
1970    #[serde(default, skip_serializing_if = "Option::is_none")]
1971    pub wait_ms: Option<u32>,
1972    /// What the read answers: the record as every reader reads it, or one of the other answers
1973    /// [`ReadAnswer`] names.
1974    #[serde(default, skip_serializing_if = "ReadAnswer::is_reading")]
1975    pub answer: ReadAnswer,
1976}
1977
1978/// What a [`ResourceReadRequest`] is answered with.
1979#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1980#[serde(rename_all = "snake_case")]
1981pub enum ReadAnswer {
1982    /// Each resource as every reader reads it (`ResourceReadings::readable`).
1983    #[default]
1984    Reading,
1985    /// Each resource as its document, whole: what a reader that merges or hydrates the resource
1986    /// itself reads ([`ResourceReadings::documents`]).
1987    Document,
1988    /// The resources of the request's workspace the caller may read rather than one: its app's,
1989    /// or every app's where the app is empty ([`ResourceReads::list`]). Its record is not read.
1990    Listing,
1991    /// Only whether the caller may read the record now, decided as its read is, without the copy
1992    /// ([`ResourceReads::may_read`]): what a reader that keeps the record another way asks.
1993    Decision,
1994    /// Only whether the caller may change the record now, decided as its write is, without the
1995    /// change ([`ResourceReads::may_write`]): what a route asks before it changes the record.
1996    WriteDecision,
1997}
1998
1999impl ReadAnswer {
2000    /// Whether this is the default answer, which the wire leaves out.
2001    #[must_use]
2002    pub const fn is_reading(&self) -> bool {
2003        matches!(self, Self::Reading)
2004    }
2005}
2006
2007impl RemoteActionMessage {
2008    /// Ask for `invocation`'s state as it is now.
2009    #[must_use]
2010    pub const fn observe(invocation: InvocationId) -> Self {
2011        Self::Observe {
2012            correlation: 0,
2013            invocation,
2014            wait_ms: None,
2015            seen: None,
2016        }
2017    }
2018
2019    /// Whether this request asks its provider to hold the answer until the
2020    /// invocation moves, a person answers, or a record is written past what its reader saw, so
2021    /// whatever carries it must not wait behind it, and nothing that watches for stuck calls
2022    /// takes the wait it asked for as one.
2023    #[must_use]
2024    pub const fn waits(&self) -> bool {
2025        matches!(
2026            self,
2027            Self::Observe {
2028                wait_ms: Some(_),
2029                ..
2030            } | Self::Invoke(InvokeRequest {
2031                wait_ms: Some(_),
2032                ..
2033            }) | Self::ChangedRequest { .. }
2034                | Self::ResourceRead {
2035                    read: ResourceReadRequest {
2036                        wait_ms: Some(_),
2037                        ..
2038                    },
2039                    ..
2040                }
2041        )
2042    }
2043
2044    /// Whether a provider answers this message (as opposed to a caller
2045    /// receiving it).
2046    #[must_use]
2047    pub const fn is_request(&self) -> bool {
2048        matches!(
2049            self,
2050            Self::CatalogueRequest { .. }
2051                | Self::Invoke(_)
2052                | Self::Observe { .. }
2053                | Self::Cancel { .. }
2054                | Self::ResourceRead { .. }
2055                | Self::RetiredFeedbackRequest { .. }
2056                | Self::ConfirmationRequest { .. }
2057                | Self::ContentPutRequest { .. }
2058                | Self::ContentGetRequest { .. }
2059                | Self::ContentLinkRequest { .. }
2060                | Self::ChangesRequest { .. }
2061                | Self::ChangedRequest { .. }
2062                | Self::SurfaceRequest { .. }
2063                | Self::AudioOutputRequest { .. }
2064                | Self::StoreRequest { .. }
2065                | Self::CallMediaRequest { .. }
2066                | Self::PresenceSaid { .. }
2067        )
2068    }
2069}
2070
2071/// The refusal of a request [`serve`] keeps nothing for: a retired feedback
2072/// ask; uploads over a session, kept by a
2073/// provider that keeps them open between steps ([`HostedContentPuts`]); and
2074/// content, read from a store a device keeps. `None` for any other message.
2075fn not_kept(message: &RemoteActionMessage) -> Option<RemoteActionMessage> {
2076    let reason = match message {
2077        RemoteActionMessage::RetiredFeedbackRequest { .. } => "feedback receipts are retired",
2078        RemoteActionMessage::ContentPutRequest { .. } => CONTENT_PUTS_UNAVAILABLE,
2079        RemoteActionMessage::ContentGetRequest { .. } => CONTENT_GETS_UNAVAILABLE,
2080        RemoteActionMessage::ContentLinkRequest { .. } => CONTENT_LINKS_UNAVAILABLE,
2081        _ => return None,
2082    };
2083    refuse(
2084        message,
2085        ActionCallError::Unavailable {
2086            reason: reason.into(),
2087        },
2088    )
2089}
2090
2091/// `command` to the records of `caller`'s app, answered by `provider`'s store
2092/// ([`ActionProvider::store_commands`]) for `correlation`.
2093fn store_answered<H: ActionProvider>(
2094    provider: &H,
2095    caller: &Caller,
2096    correlation: u64,
2097    (command, kind): (serde_json::Value, Option<String>),
2098) -> Pending<RemoteActionMessage> {
2099    let result = match provider.store_commands() {
2100        Some(store) => store.command(caller, command, kind),
2101        None => Pending::ready(Err(ActionCallError::Unavailable {
2102            reason: STORE_COMMANDS_UNAVAILABLE.into(),
2103        })),
2104    };
2105    result.map(move |result| RemoteActionMessage::StoreResponse {
2106        correlation,
2107        result,
2108    })
2109}
2110
2111/// The changes to `caller`'s workspace's records after `after`, from
2112/// `provider`'s feed, answered for `correlation` ([`ActionProvider::change_feed`]).
2113fn changed<H: ActionProvider>(
2114    provider: &H,
2115    caller: &Caller,
2116    correlation: u64,
2117    after: Option<&str>,
2118) -> Pending<RemoteActionMessage> {
2119    let result = match provider.change_feed() {
2120        Some(feed) => feed.since(caller, after),
2121        None => Pending::ready(Err(ActionCallError::Unavailable {
2122            reason: CHANGE_FEED_UNAVAILABLE.into(),
2123        })),
2124    };
2125    result.map(move |result| RemoteActionMessage::ChangesResponse {
2126        correlation,
2127        result,
2128    })
2129}
2130
2131/// A versioned [`RemoteActionMessage`], the unit a transport carries.
2132///
2133/// The encoding is self-describing JSON: action arguments and outputs are
2134/// open JSON values, and a server forwarding the bytes need not understand
2135/// them.
2136#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
2137pub struct RemoteActionFrame {
2138    pub version: u16,
2139    pub message: RemoteActionMessage,
2140    /// The workspace the request is asked in, on a transport that serves every workspace its
2141    /// device holds (the daemon's native endpoint), as a shell link's call names its own: none
2142    /// asks in the device's own. A read names its workspace in its address instead
2143    /// ([`Self::workspace`]).
2144    #[serde(default, skip_serializing_if = "Option::is_none")]
2145    pub workspace: Option<String>,
2146    /// The input serial the person's press that ran this request travelled with, as the
2147    /// compositor issued it to the window the app's connection is: what a host checks to admit
2148    /// the request as the person, once. Only an app whose window received the press can name
2149    /// it: a synthetic or replayed serial proves nothing, and a request naming none followed no
2150    /// press. It is transport, never part of the invocation's identity.
2151    #[serde(default, skip_serializing_if = "Option::is_none")]
2152    pub press: Option<u32>,
2153    /// Where in the window the control that press answered stands, as the window says of a key
2154    /// press ([`press_points`]): what the person's question stands at when the compositor's
2155    /// record of the press has no point. Like `press`, transport only.
2156    #[serde(default, skip_serializing_if = "Option::is_none")]
2157    pub press_at: Option<asked::PressPoint>,
2158}
2159
2160/// Why bytes are not a usable [`RemoteActionFrame`].
2161#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
2162pub enum RemoteFrameError {
2163    #[error("remote action frame of {len} bytes exceeds the limit")]
2164    TooLarge { len: usize },
2165    #[error("remote action frame version {version} is not supported")]
2166    UnsupportedVersion { version: u16 },
2167    #[error("malformed remote action frame: {0}")]
2168    Malformed(String),
2169}
2170
2171impl RemoteActionFrame {
2172    /// Wrap `message` at this build's [`REMOTE_ACTIONS_VERSION`].
2173    #[must_use]
2174    pub const fn new(message: RemoteActionMessage) -> Self {
2175        Self {
2176            version: REMOTE_ACTIONS_VERSION,
2177            message,
2178            workspace: None,
2179            press: None,
2180            press_at: None,
2181        }
2182    }
2183
2184    /// The same request, asked by the person's press the compositor issued `serial` with, and
2185    /// carrying where the control it answered stands when its window said.
2186    #[must_use]
2187    pub fn pressed(mut self, press: Option<u32>) -> Self {
2188        self.press = press;
2189        self.press_at = press.and_then(press_points::of);
2190        self
2191    }
2192
2193    /// The same request, asked in `workspace` (none: the device's own).
2194    #[must_use]
2195    pub fn in_workspace(mut self, workspace: Option<String>) -> Self {
2196        self.workspace = workspace;
2197        self
2198    }
2199
2200    /// The workspace the request is asked in: the one a read's address names, else the one the
2201    /// frame names; `None` for the device's own.
2202    #[must_use]
2203    pub fn workspace(&self) -> Option<&str> {
2204        match &self.message {
2205            RemoteActionMessage::ResourceRead { read, .. } => Some(&read.workspace),
2206            _ => self.workspace.as_deref(),
2207        }
2208    }
2209
2210    /// Encode for a transport.
2211    ///
2212    /// # Errors
2213    ///
2214    /// Returns [`RemoteFrameError::TooLarge`] past
2215    /// [`MAX_REMOTE_ACTION_FRAME_BYTES`], or `Malformed` if a value cannot
2216    /// be encoded.
2217    pub fn encode(&self) -> Result<Vec<u8>, RemoteFrameError> {
2218        let bytes = serde_json::to_vec(self)
2219            .map_err(|error| RemoteFrameError::Malformed(error.to_string()))?;
2220        if bytes.len() > MAX_REMOTE_ACTION_FRAME_BYTES {
2221            return Err(RemoteFrameError::TooLarge { len: bytes.len() });
2222        }
2223        Ok(bytes)
2224    }
2225
2226    /// Decode bytes from a transport. The version is checked before the
2227    /// message, so a frame from a newer peer is refused by version rather
2228    /// than misread.
2229    pub fn decode(bytes: &[u8]) -> Result<Self, RemoteFrameError> {
2230        #[derive(Deserialize)]
2231        struct Version {
2232            version: u16,
2233        }
2234        if bytes.len() > MAX_REMOTE_ACTION_FRAME_BYTES {
2235            return Err(RemoteFrameError::TooLarge { len: bytes.len() });
2236        }
2237        let Version { version } = serde_json::from_slice(bytes)
2238            .map_err(|error| RemoteFrameError::Malformed(error.to_string()))?;
2239        if version != REMOTE_ACTIONS_VERSION {
2240            return Err(RemoteFrameError::UnsupportedVersion { version });
2241        }
2242        serde_json::from_slice(bytes)
2243            .map_err(|error| RemoteFrameError::Malformed(error.to_string()))
2244    }
2245}
2246
2247/// A resource read, answered by the provider's own reader through its trait object: what a
2248/// reading is made of loads with the code that reads records, not with every provider's API.
2249#[cfg(all(feature = "answer-reads", not(tilo_no_js)))]
2250fn read_answered<H: ActionProvider>(
2251    provider: &H,
2252    caller: &Caller,
2253    correlation: u64,
2254    read: ResourceReadRequest,
2255) -> Pending<RemoteActionMessage> {
2256    provider.resource_reads().map_or_else(
2257        || resource_read::unanswered(correlation),
2258        |reads| resource_read::answered_where_it_ends(reads.answer_read(caller, correlation, read)),
2259    )
2260}
2261
2262/// A build with no runtime to answer on (a model module, or one that reads no records) answers
2263/// every posted read as a provider that reads no records does.
2264#[cfg(not(all(feature = "answer-reads", not(tilo_no_js))))]
2265fn read_answered<H: ActionProvider>(
2266    _provider: &H,
2267    _caller: &Caller,
2268    correlation: u64,
2269    _read: ResourceReadRequest,
2270) -> Pending<RemoteActionMessage> {
2271    resource_read::unanswered(correlation)
2272}
2273
2274/// A call media lane is its own host's, never a provider's: one asked here says it carries none.
2275fn no_call_media_lane() -> ActionCallError {
2276    ActionCallError::Unavailable {
2277        reason: "this connection carries no call media lane".into(),
2278    }
2279}
2280
2281/// The answer to a shell asked of a provider's connection, which carries none: a shell is the
2282/// device's own, on an app's connection.
2283fn no_shell(correlation: u64) -> RemoteActionMessage {
2284    RemoteActionMessage::ShellOpenResponse {
2285        correlation,
2286        result: Err(ActionCallError::Unavailable {
2287            reason: "this connection carries no shell".into(),
2288        }),
2289    }
2290}
2291
2292/// A presence lane is its own host's, never a provider's: one asked here says it carries none.
2293fn no_presence_lane() -> ActionCallError {
2294    ActionCallError::Unavailable {
2295        reason: "this connection carries no presence lane".into(),
2296    }
2297}
2298
2299/// A sound output lane is its own host's, never a provider's: one asked here says it carries none.
2300fn no_audio_output_lane() -> ActionCallError {
2301    ActionCallError::Unavailable {
2302        reason: "this connection carries no sound output lane".into(),
2303    }
2304}
2305
2306/// A call lane is its own host's, never a provider's: one asked here says it carries none.
2307fn no_call_lane() -> ActionCallError {
2308    ActionCallError::Unavailable {
2309        reason: "this connection carries no call lane".into(),
2310    }
2311}
2312
2313/// Answer one request from `caller` against `provider`.
2314///
2315/// Returns `None` for a message that is not a request (a response arriving
2316/// at a provider is dropped, never answered). A refused invocation becomes a
2317/// [`ReceiptStatus::Rejected`] receipt so the caller always learns the fate
2318/// of the id it chose; an answer the provider abandons becomes a refusal too.
2319///
2320/// A request that asks to wait (`wait_ms` on [`RemoteActionMessage::Observe`]
2321/// or [`InvokeRequest`]) is answered once the invocation moves, through
2322/// [`ActionProvider::next_change`] and without holding a thread; see
2323/// [`settle_with`]. A provider that cannot signal changes answers at once.
2324pub fn serve<H: ActionProvider + Clone + Send + 'static>(
2325    provider: &H,
2326    caller: &Caller,
2327    message: RemoteActionMessage,
2328) -> Option<Pending<RemoteActionMessage>> {
2329    let abandoned = refuse(
2330        &message,
2331        ActionCallError::Unavailable {
2332            reason: "the provider dropped the request".into(),
2333        },
2334    )?;
2335    if let Some(answer) = unprovided(&message) {
2336        return Some(Pending::ready(answer));
2337    }
2338    let answer = match message {
2339        RemoteActionMessage::CatalogueRequest { correlation, query } => provider
2340            .query(caller, query)
2341            .map(move |result| RemoteActionMessage::CatalogueResponse {
2342                correlation,
2343                result,
2344            }),
2345        RemoteActionMessage::Invoke(request) => {
2346            invoked(provider, caller, request).map(RemoteActionMessage::Receipt)
2347        }
2348        RemoteActionMessage::Observe {
2349            correlation,
2350            invocation,
2351            wait_ms: Some(wait_ms),
2352            seen,
2353        } => settle_with(provider, caller, invocation, seen, wait::deadline(wait_ms))
2354            .map(move |state| updated(correlation, invocation, state)),
2355        RemoteActionMessage::Observe {
2356            correlation,
2357            invocation,
2358            ..
2359        } => Pending::ready(updated(
2360            correlation,
2361            invocation,
2362            provider.observe(caller, &invocation),
2363        )),
2364        RemoteActionMessage::Cancel { invocation } => provider
2365            .cancel(caller, &invocation)
2366            .map(move |result| RemoteActionMessage::CancelResponse { invocation, result }),
2367        // Read by a provider's own reader, which answers through its trait object: what a reading is
2368        // made of loads with the code that reads records, not with every provider's API.
2369        RemoteActionMessage::ResourceRead {
2370            correlation, read, ..
2371        } => read_answered(provider, caller, correlation, read),
2372        RemoteActionMessage::ChangesRequest { correlation, after } => {
2373            changed(provider, caller, correlation, after.as_deref())
2374        }
2375        RemoteActionMessage::ChangedRequest { correlation, scope } => {
2376            watch::noticed(provider, caller, correlation, scope)
2377        }
2378        RemoteActionMessage::SurfaceRequest { correlation, app } => {
2379            surfaces::surfaced(provider, correlation, &app)
2380        }
2381        RemoteActionMessage::StoreRequest {
2382            correlation,
2383            command,
2384            kind,
2385        } => store_answered(provider, caller, correlation, (command, kind)),
2386        // An answer is never a request: `refuse` classified every message before this match and
2387        // answered `None` for an answer, and `unprovided` answered what no provider takes, so
2388        // neither reaches here.
2389        _ => return None,
2390    };
2391    // An abandoned answer still answers: the caller hears a refusal.
2392    let (completer, answered) = pending();
2393    answer.then(move |answer| completer.complete(answer.unwrap_or(abandoned)));
2394    Some(answered)
2395}
2396
2397/// The answer to a request that no provider takes, or `None` for any other message. What a
2398/// stateless provider keeps none of, it refuses; a question is the person's to answer, on the
2399/// device they are at; and a lane (calls, sound output, call media, presence, shells) is its own
2400/// host's, so one asked here says it carries none.
2401fn unprovided(message: &RemoteActionMessage) -> Option<RemoteActionMessage> {
2402    Some(match *message {
2403        RemoteActionMessage::RetiredFeedbackRequest { .. }
2404        | RemoteActionMessage::ContentPutRequest { .. }
2405        | RemoteActionMessage::ContentGetRequest { .. }
2406        | RemoteActionMessage::ContentLinkRequest { .. } => not_kept(message)?,
2407        RemoteActionMessage::ConfirmationRequest { correlation, .. } => {
2408            confirmation::unanswered(correlation, ActionCallError::confirmation_required())
2409        }
2410        RemoteActionMessage::CallCarryRequest { correlation, .. } => {
2411            RemoteActionMessage::CallCarryResponse {
2412                correlation,
2413                result: Err(no_call_lane()),
2414            }
2415        }
2416        RemoteActionMessage::CallReport { correlation, .. } => {
2417            RemoteActionMessage::CallReportResponse {
2418                correlation,
2419                result: Err(no_call_lane()),
2420            }
2421        }
2422        RemoteActionMessage::AudioOutputRequest { correlation, .. } => {
2423            RemoteActionMessage::AudioOutputResponse {
2424                correlation,
2425                result: Err(no_audio_output_lane()),
2426            }
2427        }
2428        RemoteActionMessage::CallMediaRequest { correlation, .. } => {
2429            RemoteActionMessage::CallMediaResult {
2430                correlation,
2431                result: Err(no_call_media_lane()),
2432            }
2433        }
2434        RemoteActionMessage::PresenceSaid { correlation, .. } => {
2435            RemoteActionMessage::PresenceSaidResult {
2436                correlation,
2437                result: Err(no_presence_lane()),
2438            }
2439        }
2440        RemoteActionMessage::ShellOpenRequest { correlation, .. } => no_shell(correlation),
2441        _ => return None,
2442    })
2443}
2444
2445/// Run `request` at `provider`, answering its receipt once it is ready, or once it moves when it
2446/// asks to wait. How the answer travels is not part of what runs.
2447fn invoked<H: ActionProvider + Clone + Send + 'static>(
2448    provider: &H,
2449    caller: &Caller,
2450    mut request: InvokeRequest,
2451) -> Pending<InvocationReceipt> {
2452    let until = request.wait_ms.take().map(wait::deadline);
2453    let invocation = request.invocation;
2454    let receipt = provider.invoke(caller, request).map(move |result| {
2455        result.unwrap_or_else(|error| InvocationReceipt {
2456            invocation,
2457            status: ReceiptStatus::Rejected { error },
2458        })
2459    });
2460    match until {
2461        Some(until) => wait::settle_receipt(provider, caller, receipt, until),
2462        None => receipt,
2463    }
2464}
2465
2466/// The answer that refuses request `message` with `error` — for a provider that
2467/// cannot be reached or is not running. Returns `None` for a message that
2468/// is not a request.
2469#[must_use]
2470pub fn refuse(
2471    message: &RemoteActionMessage,
2472    error: ActionCallError,
2473) -> Option<RemoteActionMessage> {
2474    Some(match message {
2475        RemoteActionMessage::RetiredFeedbackRequest { correlation } => {
2476            RemoteActionMessage::RetiredFeedbackResponse {
2477                correlation: *correlation,
2478            }
2479        }
2480        RemoteActionMessage::CatalogueRequest { correlation, .. } => {
2481            RemoteActionMessage::CatalogueResponse {
2482                correlation: *correlation,
2483                result: Err(error),
2484            }
2485        }
2486        RemoteActionMessage::Invoke(request) => RemoteActionMessage::Receipt(InvocationReceipt {
2487            invocation: request.invocation,
2488            status: ReceiptStatus::Rejected { error },
2489        }),
2490        RemoteActionMessage::Observe {
2491            correlation,
2492            invocation,
2493            ..
2494        } => updated(*correlation, *invocation, None),
2495        RemoteActionMessage::Cancel { invocation } => RemoteActionMessage::CancelResponse {
2496            invocation: *invocation,
2497            result: Err(error),
2498        },
2499        RemoteActionMessage::ResourceRead { correlation, .. } => {
2500            RemoteActionMessage::ResourceReading {
2501                correlation: *correlation,
2502                result: Err(error),
2503            }
2504        }
2505        RemoteActionMessage::ConfirmationRequest { correlation, .. } => {
2506            confirmation::unanswered(*correlation, error)
2507        }
2508        RemoteActionMessage::ContentPutRequest { correlation, .. } => {
2509            RemoteActionMessage::ContentPutResponse {
2510                correlation: *correlation,
2511                result: Err(error),
2512            }
2513        }
2514        RemoteActionMessage::ContentGetRequest { correlation, .. } => {
2515            RemoteActionMessage::ContentGetResponse {
2516                correlation: *correlation,
2517                result: Err(error),
2518            }
2519        }
2520        RemoteActionMessage::ContentLinkRequest { correlation, .. } => {
2521            RemoteActionMessage::ContentLinkResponse {
2522                correlation: *correlation,
2523                result: Err(error),
2524            }
2525        }
2526        RemoteActionMessage::ChangesRequest { correlation, .. } => {
2527            RemoteActionMessage::ChangesResponse {
2528                correlation: *correlation,
2529                result: Err(error),
2530            }
2531        }
2532        RemoteActionMessage::ChangedRequest { correlation, .. } => {
2533            RemoteActionMessage::ChangedResponse {
2534                correlation: *correlation,
2535                result: Err(error),
2536            }
2537        }
2538        RemoteActionMessage::SurfaceRequest { correlation, .. } => {
2539            RemoteActionMessage::SurfaceResponse {
2540                correlation: *correlation,
2541                result: Err(error),
2542            }
2543        }
2544        RemoteActionMessage::StoreRequest { correlation, .. } => {
2545            RemoteActionMessage::StoreResponse {
2546                correlation: *correlation,
2547                result: Err(error),
2548            }
2549        }
2550        RemoteActionMessage::PresenceSaid { correlation, .. } => {
2551            RemoteActionMessage::PresenceSaidResult {
2552                correlation: *correlation,
2553                result: Err(error),
2554            }
2555        }
2556        RemoteActionMessage::ShellOpenRequest { correlation, .. } => {
2557            RemoteActionMessage::ShellOpenResponse {
2558                correlation: *correlation,
2559                result: Err(error),
2560            }
2561        }
2562        // Every other message answers a request: there is nothing to refuse.
2563        _ => return None,
2564    })
2565}
2566
2567struct LogEntry<T> {
2568    caller: Caller,
2569    request: InvokeRequest,
2570    /// `None` while a start begun with [`InvocationLog::reserve`] is in
2571    /// flight.
2572    handle: Option<T>,
2573}
2574
2575/// The idempotency log behind [`ActionProvider::invoke`].
2576///
2577/// Maps each admitted [`InvocationId`] to the caller and request that
2578/// admitted it and to the provider's own handle for the running job. A retry
2579/// with the same caller and request returns the existing handle without
2580/// starting anything; any other reuse of the id is a conflict. Only admitted
2581/// invocations are remembered — a refused one ran nothing, so retrying it
2582/// may be admitted later. At `capacity`, the oldest entry whose admission
2583/// completed is forgotten. In-flight reservations are never evicted.
2584pub struct InvocationLog<T> {
2585    entries: HashMap<InvocationId, LogEntry<T>>,
2586    order: VecDeque<InvocationId>,
2587    capacity: usize,
2588}
2589
2590impl<T> Default for InvocationLog<T> {
2591    fn default() -> Self {
2592        Self::with_capacity(DEFAULT_LOG_CAPACITY)
2593    }
2594}
2595
2596/// What [`InvocationLog::reserve`] found.
2597#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2598pub enum Reservation {
2599    /// The id is newly claimed; the caller must now start the job.
2600    Reserved,
2601    /// The same caller and request were already admitted.
2602    Admitted,
2603}
2604
2605/// Whether [`InvocationLog::admit`] started a job or found one.
2606#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2607pub enum Admission {
2608    Started,
2609    Retried,
2610}
2611
2612impl<T> InvocationLog<T> {
2613    /// A log remembering at most `capacity` invocations (at least one).
2614    #[must_use]
2615    pub fn with_capacity(capacity: usize) -> Self {
2616        Self {
2617            entries: HashMap::new(),
2618            order: VecDeque::new(),
2619            capacity: capacity.max(1),
2620        }
2621    }
2622
2623    /// Admit `request` for `caller`, calling `start` only if the id is new.
2624    ///
2625    /// # Errors
2626    ///
2627    /// Returns [`ActionCallError::InvocationConflict`] when the id was
2628    /// admitted for another caller or request, [`ActionCallError::Unavailable`]
2629    /// when all slots are reserved, or whatever `start` returns.
2630    pub fn admit(
2631        &mut self,
2632        caller: &Caller,
2633        request: &InvokeRequest,
2634        start: impl FnOnce() -> Result<T, ActionCallError>,
2635    ) -> Result<(&T, Admission), ActionCallError> {
2636        let id = request.invocation;
2637        let admission = match self.reserve(caller, request)? {
2638            Reservation::Admitted => Admission::Retried,
2639            Reservation::Reserved => match start() {
2640                Ok(handle) => {
2641                    self.complete(&id, handle);
2642                    Admission::Started
2643                }
2644                Err(error) => {
2645                    self.abandon(&id);
2646                    return Err(error);
2647                }
2648            },
2649        };
2650        self.entries
2651            .get(&id)
2652            .and_then(|entry| entry.handle.as_ref())
2653            .map(|handle| (handle, admission))
2654            .ok_or(ActionCallError::UnknownInvocation)
2655    }
2656
2657    /// First half of an admission whose start completes later (for example
2658    /// across an asynchronous resolution): claim the id for `caller` and
2659    /// `request`, then [`complete`](Self::complete) or
2660    /// [`abandon`](Self::abandon) it.
2661    ///
2662    /// # Errors
2663    ///
2664    /// Returns [`ActionCallError::InvocationConflict`] when the id belongs to
2665    /// another caller or request, [`ActionCallError::Unanswered`] while an
2666    /// earlier start of the same invocation is still in flight, and
2667    /// [`ActionCallError::Unavailable`] while every slot is held by an
2668    /// in-flight reservation.
2669    pub fn reserve(
2670        &mut self,
2671        caller: &Caller,
2672        request: &InvokeRequest,
2673    ) -> Result<Reservation, ActionCallError> {
2674        let id = request.invocation;
2675        if let Some(entry) = self.entries.get_mut(&id) {
2676            if !caller.continues(&entry.caller) || !entry.request.same_invocation(request) {
2677                return Err(ActionCallError::InvocationConflict);
2678            }
2679            // Asked again on the connection that replaced its own: it is this one's from now on.
2680            entry.caller.clone_from(caller);
2681            // Its first start has not ended: a workspace action that runs whole as it starts
2682            // (a server taking in a workspace's gigabytes) is still going. Nothing is known of
2683            // what it did yet, so the caller asks the same invocation again, as for one whose
2684            // answer was lost.
2685            return if entry.handle.is_some() {
2686                Ok(Reservation::Admitted)
2687            } else {
2688                Err(ActionCallError::Unanswered)
2689            };
2690        }
2691        while self.order.len() >= self.capacity {
2692            let oldest_completed = self.order.iter().position(|candidate| {
2693                self.entries
2694                    .get(candidate)
2695                    .is_some_and(|entry| entry.handle.is_some())
2696            });
2697            let Some(index) = oldest_completed else {
2698                return Err(ActionCallError::Unavailable {
2699                    reason: "all invocation slots are still being admitted; retry".into(),
2700                });
2701            };
2702            if let Some(oldest) = self.order.remove(index) {
2703                self.entries.remove(&oldest);
2704            }
2705        }
2706        self.order.push_back(id);
2707        self.entries.insert(
2708            id,
2709            LogEntry {
2710                caller: caller.clone(),
2711                request: InvokeRequest {
2712                    wait_ms: None,
2713                    appearance: None,
2714                    ..request.clone()
2715                },
2716                handle: None,
2717            },
2718        );
2719        Ok(Reservation::Reserved)
2720    }
2721
2722    /// Admit `request` again under its id where its person approved the asked record it waits
2723    /// in: the entry `caller` admitted for the same target and arguments, whose handle `waits`
2724    /// says is still asked, is reserved again carrying their answer, and the caller completes or
2725    /// abandons it as after [`Self::reserve`]. `waits` is handed `None` while the entry's first
2726    /// start is still in flight. False where nothing of that waits, which a reserve then refuses
2727    /// as another invocation.
2728    pub fn readmit(
2729        &mut self,
2730        caller: &Caller,
2731        request: &InvokeRequest,
2732        waits: impl FnOnce(Option<&T>) -> bool,
2733    ) -> bool {
2734        let Some(entry) = self.entries.get_mut(&request.invocation) else {
2735            return false;
2736        };
2737        let again = request.approval().is_some()
2738            && caller.continues(&entry.caller)
2739            && asked::same_call(&entry.request, request)
2740            && waits(entry.handle.as_ref());
2741        if again {
2742            entry.request = InvokeRequest {
2743                wait_ms: None,
2744                appearance: None,
2745                ..request.clone()
2746            };
2747            entry.handle = None;
2748        }
2749        again
2750    }
2751
2752    /// Record the provider's handle for a reserved invocation.
2753    pub fn complete(&mut self, id: &InvocationId, handle: T) {
2754        if let Some(entry) = self.entries.get_mut(id) {
2755            entry.handle = Some(handle);
2756        }
2757    }
2758
2759    /// Release a reservation whose start failed: nothing ran, so the id may
2760    /// be admitted later.
2761    pub fn abandon(&mut self, id: &InvocationId) {
2762        if self
2763            .entries
2764            .get(id)
2765            .is_some_and(|entry| entry.handle.is_none())
2766        {
2767            self.entries.remove(id);
2768            self.order.retain(|candidate| candidate != id);
2769        }
2770    }
2771
2772    /// The request that admitted invocation `id`, for the provider that keeps this log: what an
2773    /// app it runs the invocation in carries as the proof of a call it makes for it.
2774    #[must_use]
2775    pub fn request_of(&self, id: &InvocationId) -> Option<&InvokeRequest> {
2776        self.entries.get(id).map(|entry| &entry.request)
2777    }
2778
2779    /// The handle for an invocation `caller` admitted, or the caller it continues
2780    /// ([`Caller::continues`]).
2781    #[must_use]
2782    pub fn get(&self, caller: &Caller, id: &InvocationId) -> Option<&T> {
2783        self.entries
2784            .get(id)
2785            .filter(|entry| caller.follows(&entry.caller))
2786            .and_then(|entry| entry.handle.as_ref())
2787    }
2788
2789    /// The invocation `caller` admitted under `id`, as its handle: `Some(None)` while its start
2790    /// is still in flight, `None` where `caller` admitted nothing under `id`.
2791    #[must_use]
2792    pub fn admitted(&self, caller: &Caller, id: &InvocationId) -> Option<Option<&T>> {
2793        self.entries
2794            .get(id)
2795            .filter(|entry| caller.follows(&entry.caller))
2796            .map(|entry| entry.handle.as_ref())
2797    }
2798
2799    /// Mutable access to the handle for an invocation `caller` admitted.
2800    pub fn get_mut(&mut self, caller: &Caller, id: &InvocationId) -> Option<&mut T> {
2801        self.entries
2802            .get_mut(id)
2803            .filter(|entry| caller.follows(&entry.caller))
2804            .and_then(|entry| entry.handle.as_mut())
2805    }
2806}
2807
2808/// The accounts actions whose answer is a secret ([`crate::SECRET_ANSWER_TAG`]): a cloud mount's
2809/// sign-in, and the sign-ins whose answers carry a one-time code.
2810pub const ACCOUNT_SECRET_ANSWERS: [&str; 3] =
2811    ["cloud-credential", "begin-sign-in", "begin-cloud-sign-in"];
2812
2813/// Whether the action `action` answers a secret ([`crate::SECRET_ANSWER_TAG`]): handed to its
2814/// caller in the answer alone and kept in no record. The actions that declare it are the vault's
2815/// reveal and the code of this moment, a cloud mount's sign-in, and the sign-ins whose answers
2816/// carry a one-time code, wherever a host publishes them.
2817#[must_use]
2818pub fn answers_a_secret(action: &str) -> bool {
2819    VAULT_SECRET_ANSWERS.contains(&action) || ACCOUNT_SECRET_ANSWERS.contains(&action)
2820}
2821
2822#[cfg(test)]
2823mod tests {
2824    use std::sync::Mutex;
2825    use std::sync::atomic::{AtomicU32, Ordering};
2826
2827    use super::*;
2828    use crate::{ActionContract, ActionDescriptor, ExecutionLocus, InputSpec, OperationKind};
2829
2830    tilo_test_env::scenario! {
2831        fn a_caller_keeps_its_identity_and_authority;
2832
2833        phase a_bot_is_its_own_member_acting_for_its_installer;
2834        {
2835            let installer = [7u8; 32];
2836            let caller = Caller::bot("6f1c2a8e-3b4d-4c5e-9f60-718293a4b5c6", installer, [9u8; 32]);
2837            assert_eq!(
2838                caller.acting().member_id(),
2839                Some(&tilo_action_policy::MemberId::bot(
2840                    "6f1c2a8e-3b4d-4c5e-9f60-718293a4b5c6"
2841                ))
2842            );
2843            assert_eq!(
2844                caller.acting().acted_for_person(),
2845                Some(hex::encode(installer).as_str())
2846            );
2847            assert!(caller.acting().is_bot());
2848            assert!(caller.acting().delegated());
2849        }
2850
2851        phase an_app_caller_acts_as_the_person_whose_session_runs_it;
2852        {
2853            let caller = Caller::local_app("so.tilo.example").acting_for("ada");
2854            assert_eq!(caller.acting().person_id(), Some("ada"));
2855            assert_eq!(
2856                caller.acting().app().map(ToString::to_string).as_deref(),
2857                Some("so.tilo.example")
2858            );
2859            assert_eq!(caller.acting_for_person(), Some("ada"));
2860        }
2861
2862        phase execution_lifetime_is_shared_without_changing_caller_identity;
2863        {
2864            let first = Caller::local_person("owner").in_new_execution();
2865            let retained = first.clone();
2866            let second = first.clone().in_new_execution();
2867            let hash = |caller: &Caller| {
2868                let mut hasher = std::collections::hash_map::DefaultHasher::new();
2869                std::hash::Hash::hash(caller, &mut hasher);
2870                std::hash::Hasher::finish(&hasher)
2871            };
2872            let before = hash(&first);
2873            first.retire_execution();
2874            assert!(!retained.execution_is_live());
2875            assert!(second.execution_is_live());
2876            assert_eq!(first, retained);
2877            assert_eq!(hash(&first), before);
2878            let reconnected = retained.in_new_execution();
2879            assert!(reconnected.execution_is_live());
2880            assert_ne!(reconnected.execution_id(), first.execution_id());
2881        }
2882
2883        phase projected_execution_retains_transport_retirement_without_changing_authority;
2884        {
2885            let original = Caller::local_person("projected-person").in_new_execution();
2886            let projected = Caller::authenticated([1; 32], [2; 32])
2887                .in_execution(original.execution_lease().unwrap());
2888            assert_eq!(projected.execution_id(), original.execution_id());
2889            assert_eq!(projected.user_public_key(), Some(&[1; 32]));
2890            assert_eq!(original.user_public_key(), None);
2891            original.retire_execution();
2892            assert!(!projected.execution_is_live());
2893        }
2894    }
2895
2896    fn alice() -> Caller {
2897        Caller::authenticated([1; 32], [2; 32])
2898    }
2899
2900    fn mallory() -> Caller {
2901        Caller::authenticated([9; 32], [8; 32])
2902    }
2903
2904    tilo_test_env::scenario! {
2905        fn an_application_action_names_its_destination;
2906
2907        phase an_application_action_target_names_its_workspace_and_app;
2908        {
2909            let target =
2910                application_action_target("workspace-1", "so.tilo.chat", "chat.workspace", "call");
2911            assert_eq!(
2912                application_provider(&target.provider),
2913                Some(("workspace-1", "so.tilo.chat"))
2914            );
2915            assert_eq!(target.address, ActionAddress::new("chat.workspace", "call"));
2916            for other in [
2917                "7",
2918                "workspace:workspace-1",
2919                "application:workspace-1",
2920                "application::so.tilo.chat",
2921                "application:workspace-1:",
2922                "application:workspace-1:a:",
2923            ] {
2924                assert_eq!(application_provider(other), None, "{other}");
2925            }
2926            assert_eq!(application_provider_resource(&target.provider), None);
2927
2928            let target = application_resource_target(
2929                "workspace-1",
2930                "so.tilo.notes",
2931                "uuid:7",
2932                "notes.page:1",
2933                "open",
2934            );
2935            assert_eq!(
2936                application_provider(&target.provider),
2937                Some(("workspace-1", "so.tilo.notes"))
2938            );
2939            assert_eq!(
2940                application_provider_resource(&target.provider),
2941                Some("uuid:7")
2942            );
2943            assert_eq!(target.address, ActionAddress::new("notes.page:1", "open"));
2944        }
2945    }
2946
2947    fn descriptor(resource: &str, action: &str) -> ActionDescriptor {
2948        ActionDescriptor {
2949            did: None,
2950            state: crate::ActionState::default(),
2951            semantic_identity: None,
2952            address: ActionAddress::new(resource, action),
2953            resource_kind: "notes.note".into(),
2954            resource_label: "Groceries".into(),
2955            action_label: "Archive".into(),
2956            keywords: Vec::new(),
2957            icon: None,
2958            description: Some("Move the note to the archive".into()),
2959            locus: ExecutionLocus::ClientLocal,
2960            kind: OperationKind::Document,
2961            contract: ActionContract::default(),
2962            input: InputSpec::None,
2963            params: Vec::new(),
2964            view: None,
2965        }
2966    }
2967
2968    /// A provider with one action whose runs are counted, so a test can prove
2969    /// how many times the action actually started.
2970    struct CountingHost {
2971        runs: AtomicU32,
2972        log: Mutex<InvocationLog<Mutex<InvocationUpdate>>>,
2973    }
2974
2975    impl CountingHost {
2976        fn new() -> Self {
2977            Self {
2978                runs: AtomicU32::new(0),
2979                log: Mutex::new(InvocationLog::default()),
2980            }
2981        }
2982
2983        fn runs(&self) -> u32 {
2984            self.runs.load(Ordering::SeqCst)
2985        }
2986
2987        fn finish(&self, caller: &Caller, id: &InvocationId) {
2988            if let Some(update) = self.log.lock().unwrap().get(caller, id) {
2989                *update.lock().unwrap() = InvocationUpdate::Succeeded {
2990                    invocation: *id,
2991                    output: ActionOutput::default(),
2992                };
2993            }
2994        }
2995    }
2996
2997    impl CountingHost {
2998        fn cancel_now(&self, caller: &Caller, id: &InvocationId) -> Result<(), ActionCallError> {
2999            let log = self.log.lock().unwrap();
3000            let mut update = log
3001                .get(caller, id)
3002                .ok_or(ActionCallError::UnknownInvocation)?
3003                .lock()
3004                .unwrap();
3005            if update.is_terminal() {
3006                return Err(ActionCallError::NotCancellable {
3007                    reason: "finished".into(),
3008                });
3009            }
3010            *update = InvocationUpdate::Cancelled {
3011                invocation: *id,
3012                message: None,
3013            };
3014            drop(update);
3015            drop(log);
3016            Ok(())
3017        }
3018    }
3019
3020    impl ActionProvider for CountingHost {
3021        fn query(
3022            &self,
3023            _caller: &Caller,
3024            query: CatalogueQuery,
3025        ) -> Pending<Result<CataloguePage, ActionCallError>> {
3026            Pending::ready(Ok(CataloguePage::from_rows(
3027                "1".into(),
3028                vec![catalogue_row("note:1", "archive")],
3029                &query,
3030            )))
3031        }
3032
3033        fn invoke(
3034            &self,
3035            caller: &Caller,
3036            request: InvokeRequest,
3037        ) -> Pending<Result<InvocationReceipt, ActionCallError>> {
3038            Pending::ready((|| {
3039                if request.target.address != ActionAddress::new("note:1", "archive") {
3040                    return Err(ActionCallError::UnknownAction);
3041                }
3042                let update = {
3043                    let mut log = self.log.lock().unwrap();
3044                    let (update, _) = log.admit(caller, &request, || {
3045                        self.runs.fetch_add(1, Ordering::SeqCst);
3046                        Ok(Mutex::new(InvocationUpdate::Accepted {
3047                            invocation: request.invocation,
3048                        }))
3049                    })?;
3050                    let update = update.lock().unwrap().clone();
3051                    drop(log);
3052                    update
3053                };
3054                Ok(InvocationState::new(request.invocation, update).receipt())
3055            })())
3056        }
3057
3058        fn observe(&self, caller: &Caller, id: &InvocationId) -> Option<InvocationState> {
3059            self.log
3060                .lock()
3061                .unwrap()
3062                .get(caller, id)
3063                .map(|update| InvocationState::new(*id, update.lock().unwrap().clone()))
3064        }
3065
3066        fn cancel(
3067            &self,
3068            caller: &Caller,
3069            id: &InvocationId,
3070        ) -> Pending<Result<(), ActionCallError>> {
3071            Pending::ready(self.cancel_now(caller, id))
3072        }
3073    }
3074
3075    fn catalogue_row(resource: &str, action: &str) -> CatalogueRow {
3076        CatalogueRow {
3077            offered: None,
3078            provider: "7".into(),
3079            app_id: "notes".into(),
3080            parent_resource: String::new(),
3081            resource: CatalogueResource {
3082                id: resource.into(),
3083                kind: "notes.note".into(),
3084                label: "Groceries".into(),
3085                presentation: None,
3086            },
3087            action: Some(descriptor(resource, action)),
3088            has_children: false,
3089            visibility: None,
3090            surface: None,
3091        }
3092    }
3093
3094    /// The answer of a provider that answers immediately.
3095    fn now<T>(mut answer: Pending<T>) -> T {
3096        match answer.poll_ready() {
3097            PendingPoll::Ready(value) => value,
3098            PendingPoll::Waiting | PendingPoll::Abandoned => panic!("the provider answers at once"),
3099        }
3100    }
3101
3102    /// A provider offering more actions than one frame holds: twelve thousand,
3103    /// each described at length, as a large app's surface publishes them.
3104    #[derive(Clone)]
3105    struct HugeCatalogue;
3106
3107    const HUGE_CATALOGUE: usize = 12_000;
3108
3109    impl ActionProvider for HugeCatalogue {
3110        fn query(
3111            &self,
3112            _caller: &Caller,
3113            query: CatalogueQuery,
3114        ) -> Pending<Result<CataloguePage, ActionCallError>> {
3115            let rows = (0..HUGE_CATALOGUE)
3116                .map(|n| {
3117                    let mut row = catalogue_row(&format!("note:{n}"), &format!("archive-{n}"));
3118                    if let Some(action) = row.action.as_mut() {
3119                        action.description = Some("Moves the note out of the list. ".repeat(8));
3120                    }
3121                    row
3122                })
3123                .collect();
3124            Pending::ready(Ok(CataloguePage::from_rows("1".into(), rows, &query)))
3125        }
3126
3127        fn invoke(
3128            &self,
3129            _caller: &Caller,
3130            _request: InvokeRequest,
3131        ) -> Pending<Result<InvocationReceipt, ActionCallError>> {
3132            Pending::ready(Err(ActionCallError::UnknownAction))
3133        }
3134
3135        fn observe(&self, _caller: &Caller, _id: &InvocationId) -> Option<InvocationState> {
3136            None
3137        }
3138
3139        fn cancel(
3140            &self,
3141            _caller: &Caller,
3142            _id: &InvocationId,
3143        ) -> Pending<Result<(), ActionCallError>> {
3144            Pending::ready(Err(ActionCallError::UnknownInvocation))
3145        }
3146    }
3147
3148    /// The workspace's own app keeps its governance and its record of agents under one name: a
3149    /// caller that writes `workspace` reaches it, instead of being asked which of two apps it
3150    /// meant.
3151    #[test]
3152    fn the_workspaces_own_app_keeps_one_name() {
3153        assert_eq!(
3154            WORKSPACE_AGENTS_APP, WORKSPACE_GOVERNANCE_PROVIDER,
3155            "a workspace's agents are the workspace's own app's record"
3156        );
3157        assert_eq!(
3158            crate::tree::app_meant("workspace", &[(WORKSPACE_GOVERNANCE_PROVIDER, "Workspace")]),
3159            Ok(Some(WORKSPACE_GOVERNANCE_PROVIDER.to_owned())),
3160            "`workspace` names the workspace's own app"
3161        );
3162    }
3163
3164    /// A caller paging a catalogue larger than a frame, through the provider's
3165    /// answer and the frame each page travels in, reads every action once, and
3166    /// no frame is over the limit: a page ends at its size as well as its count,
3167    /// whatever count was asked for, plain or a resource at a time.
3168    #[test]
3169    fn a_catalogue_larger_than_a_frame_travels_in_pages_that_each_fit_one() {
3170        for by_resource in [false, true] {
3171            let mut query = CatalogueQuery {
3172                max_results: u32::MAX,
3173                by_resource,
3174                ..CatalogueQuery::default()
3175            };
3176            let mut listed = Vec::new();
3177            let mut pages = 0usize;
3178            loop {
3179                let asked = RemoteActionMessage::CatalogueRequest {
3180                    correlation: 1,
3181                    query: query.clone(),
3182                };
3183                let answer =
3184                    now(serve(&HugeCatalogue, &alice(), asked).expect("a request is answered"));
3185                let bytes = RemoteActionFrame::new(answer)
3186                    .encode()
3187                    .expect("every page fits one frame");
3188                assert!(bytes.len() <= MAX_REMOTE_ACTION_FRAME_BYTES);
3189                let RemoteActionMessage::CatalogueResponse {
3190                    result: Ok(page), ..
3191                } = RemoteActionFrame::decode(&bytes).unwrap().message
3192                else {
3193                    panic!("a catalogue request is answered with its page");
3194                };
3195                pages += 1;
3196                listed.extend(
3197                    expand(page.rows)
3198                        .into_iter()
3199                        .filter_map(|row| row.action.map(|action| action.address.action)),
3200                );
3201                if page.exhausted {
3202                    break;
3203                }
3204                query.cursor = page.next_cursor;
3205                query.revision = Some(page.revision);
3206            }
3207            assert!(pages > 1, "the catalogue is larger than one frame");
3208            let expected: Vec<String> = (0..HUGE_CATALOGUE)
3209                .map(|n| format!("archive-{n}"))
3210                .collect();
3211            assert_eq!(listed, expected, "every action is listed once, in order");
3212        }
3213    }
3214
3215    fn archive(invocation: InvocationId) -> InvokeRequest {
3216        InvokeRequest {
3217            on_behalf_of: None,
3218            invocation,
3219            target: RemoteActionTarget {
3220                provider: "7".into(),
3221                address: ActionAddress::new("note:1", "archive"),
3222            },
3223            argument: InvokeArgument::None,
3224            context: None,
3225            confirmation: None,
3226            revision: None,
3227            wait_ms: None,
3228            appearance: None,
3229            signed: None,
3230        }
3231    }
3232
3233    fn round_trip(message: RemoteActionMessage) -> RemoteActionMessage {
3234        let bytes = RemoteActionFrame::new(message).encode().unwrap();
3235        RemoteActionFrame::decode(&bytes).unwrap().message
3236    }
3237
3238    /// One of each catalogue and invoke message shape.
3239    fn request_messages(invocation: InvocationId) -> Vec<RemoteActionMessage> {
3240        let mut arguments = serde_json::Map::new();
3241        arguments.insert("title".into(), serde_json::json!("Weekly"));
3242        vec![
3243            RemoteActionMessage::CatalogueRequest {
3244                correlation: 3,
3245                query: CatalogueQuery::default(),
3246            },
3247            RemoteActionMessage::CatalogueRequest {
3248                correlation: 5,
3249                query: CatalogueQuery {
3250                    provider: Some("7".into()),
3251                    parent_resource: Some("folder:a".into()),
3252                    needle: "gro".into(),
3253                    cursor: vec![1, 2],
3254                    revision: Some("r1".into()),
3255                    max_results: 8,
3256                    limits: Some(CatalogueLimits {
3257                        max_bytes: Some(4096),
3258                        max_work: None,
3259                        max_depth: Some(1),
3260                    }),
3261                    ..CatalogueQuery::default()
3262                },
3263            },
3264            RemoteActionMessage::CatalogueResponse {
3265                correlation: 3,
3266                result: now(CountingHost::new().query(&alice(), CatalogueQuery::default())),
3267            },
3268            RemoteActionMessage::CatalogueResponse {
3269                correlation: 4,
3270                result: Err(ActionCallError::Unavailable {
3271                    reason: "no apps".into(),
3272                }),
3273            },
3274            RemoteActionMessage::Invoke(InvokeRequest {
3275                on_behalf_of: None,
3276                argument: InvokeArgument::Json(arguments),
3277                context: Some(ActionContext::for_resource(
3278                    "note:1",
3279                    "notes.note",
3280                    "Groceries",
3281                )),
3282                ..archive(invocation)
3283            }),
3284            RemoteActionMessage::Invoke(InvokeRequest {
3285                on_behalf_of: None,
3286                argument: InvokeArgument::Text("hello".into()),
3287                ..archive(invocation)
3288            }),
3289            RemoteActionMessage::Invoke(InvokeRequest {
3290                on_behalf_of: None,
3291                confirmation: Some(Confirmation::Phrase("delete it".into())),
3292                ..archive(invocation)
3293            }),
3294            RemoteActionMessage::Invoke(InvokeRequest {
3295                wait_ms: Some(2_000),
3296                appearance: None,
3297                ..archive(invocation)
3298            }),
3299        ]
3300    }
3301
3302    /// One of each receipt, update and cancel message shape.
3303    fn outcome_messages(invocation: InvocationId) -> Vec<RemoteActionMessage> {
3304        vec![
3305            RemoteActionMessage::Receipt(InvocationReceipt {
3306                invocation,
3307                status: ReceiptStatus::Completed {
3308                    output: ActionOutput {
3309                        value: Some(serde_json::json!({"archived": true})),
3310                        resources: vec!["notes.note:1".into()],
3311                    },
3312                },
3313            }),
3314            RemoteActionMessage::Receipt(InvocationReceipt {
3315                invocation,
3316                status: ReceiptStatus::Failed {
3317                    error: ActionFailure {
3318                        code: "disk_full".into(),
3319                        message: "no space".into(),
3320                        details: None,
3321                        retryable: true,
3322                    },
3323                },
3324            }),
3325            RemoteActionMessage::Receipt(InvocationReceipt {
3326                invocation,
3327                status: ReceiptStatus::Rejected {
3328                    error: ActionCallError::InvocationConflict,
3329                },
3330            }),
3331            RemoteActionMessage::Receipt(InvocationReceipt {
3332                invocation,
3333                status: ReceiptStatus::Cancelled {
3334                    message: Some("stopped".into()),
3335                },
3336            }),
3337            RemoteActionMessage::observe(invocation),
3338            RemoteActionMessage::Observe {
3339                correlation: 7,
3340                invocation,
3341                wait_ms: Some(10_000),
3342                seen: Some(UpdateMark::Progress { sequence: 2 }),
3343            },
3344            RemoteActionMessage::Update {
3345                invocation,
3346                state: Some(InvocationState::new(
3347                    invocation,
3348                    InvocationUpdate::Progress {
3349                        invocation,
3350                        sequence: 2,
3351                        phase: "copying".into(),
3352                        completed: Some(1),
3353                        total: Some(4),
3354                        message: None,
3355                    },
3356                )),
3357                correlation: Some(7),
3358            },
3359            RemoteActionMessage::Update {
3360                invocation,
3361                state: None,
3362                correlation: Some(7),
3363            },
3364            RemoteActionMessage::Cancel { invocation },
3365            RemoteActionMessage::CancelResponse {
3366                invocation,
3367                result: Err(ActionCallError::NotCancellable {
3368                    reason: "finished".into(),
3369                }),
3370            },
3371        ]
3372    }
3373
3374    tilo_test_env::scenario! {
3375        fn remote_messages_and_failures_read_back_typed;
3376
3377        phase a_stale_revision_is_typed_and_travels_as_older_peers_read_it;
3378        // A stale revision is typed in this build and travels in the shape
3379        // every peer decodes: an older peer reads the invalid request it always
3380        // sent, and the reasons older providers gave it read back as the variant.
3381        {
3382            let encoded = serde_json::to_value(ActionCallError::StaleRevision).unwrap();
3383            assert_eq!(
3384                encoded,
3385                serde_json::json!({"InvalidRequest": {"reason": STALE_REVISION_REASON}})
3386            );
3387            assert_eq!(
3388                serde_json::from_value::<ActionCallError>(encoded).unwrap(),
3389                ActionCallError::StaleRevision
3390            );
3391            assert_eq!(ActionCallError::StaleRevision.code(), "stale_revision");
3392            // Only that exact reason: a refusal that merely mentions a revision
3393            // is the refusal it is.
3394            let other = ActionCallError::Refused {
3395                reason: "the call changed since that revision, honestly".into(),
3396            };
3397            let round_trip: ActionCallError =
3398                serde_json::from_value(serde_json::to_value(&other).unwrap()).unwrap();
3399            assert_eq!(round_trip, other);
3400            let needs = ActionCallError::InvalidRequest {
3401                reason: CONFIRMED_ACTION_NEEDS_REVISION.into(),
3402            };
3403            assert!(needs.needs_revision());
3404            assert!(!ActionCallError::StaleRevision.needs_revision());
3405        }
3406
3407        phase a_failure_with_details_round_trips;
3408        // A failure's structured details travel beside its message.
3409        {
3410            let update = InvocationUpdate::Failed {
3411                invocation: InvocationId::new(),
3412                error: ActionFailure {
3413                    code: "invalid_arguments".into(),
3414                    message: "argument `pageSize` must be at most 64".into(),
3415                    details: Some(serde_json::json!({
3416                        "param": "pageSize",
3417                        "violation": {"kind": "maximum", "bound": 64}
3418                    })),
3419                    retryable: false,
3420                },
3421            };
3422            let encoded = serde_json::to_string(&update).unwrap();
3423            assert_eq!(
3424                serde_json::from_str::<InvocationUpdate>(&encoded).unwrap(),
3425                update
3426            );
3427        }
3428
3429        phase a_refusal_for_want_of_the_person_carries_what_they_are_shown;
3430        // A run that reached something only the person may allow is refused for
3431        // want of their answer, and that refusal carries what the run stated
3432        // about it: the page departure it holds, as it travels to whoever asks them.
3433        {
3434            let facts = asked::AskedFacts::default()
3435                .with_fact("kind", "submit")
3436                .with_fact("destination", "https://visa.example")
3437                .with_fact("picture", "tilo.content:5f2b");
3438            let invocation = InvocationId::new();
3439            let state = InvocationState::new(
3440                invocation,
3441                InvocationUpdate::Failed {
3442                    invocation,
3443                    error: ActionFailure {
3444                        code: CONFIRMATION_REQUIRED_CODE.into(),
3445                        message: "the person has to allow this".into(),
3446                        details: Some(facts.to_details()),
3447                        retryable: false,
3448                    },
3449                },
3450            );
3451            let receipt = state.receipt();
3452            let ReceiptStatus::Rejected {
3453                error: ActionCallError::ConfirmationRequired(stated),
3454            } = &receipt.status
3455            else {
3456                panic!("a run waiting on the person is a refusal: {receipt:?}");
3457            };
3458            assert_eq!(**stated, facts);
3459            // The refusal travels with it, so whoever asks the person in another process
3460            // shows what leaves and not a name for it.
3461            let error = ActionCallError::asks(facts);
3462            let wire = serde_json::to_value(&error).unwrap();
3463            assert_eq!(
3464                serde_json::from_value::<ActionCallError>(wire).unwrap(),
3465                error
3466            );
3467            let wire = postcard::to_allocvec(&error).unwrap();
3468            assert_eq!(postcard::from_bytes::<ActionCallError>(&wire).unwrap(), error);
3469        }
3470
3471        phase the_remote_wire_is_versioned_and_explicit;
3472        // Every message round-trips through a frame, frames from another version are refused not
3473        // misread, and the wire names versions and messages explicitly.
3474        // Invocations each phase below in order; every phase builds its own fixture.
3475        {
3476            every_message_round_trips_through_a_frame();
3477            frames_from_another_version_are_refused_not_misread();
3478            the_wire_names_versions_and_messages_explicitly();
3479        }
3480    }
3481
3482    fn every_message_round_trips_through_a_frame() {
3483        let invocation = InvocationId(uuid::Uuid::from_u128(7));
3484        let messages = request_messages(invocation)
3485            .into_iter()
3486            .chain(outcome_messages(invocation));
3487        for message in messages {
3488            assert_eq!(round_trip(message.clone()), message);
3489        }
3490    }
3491
3492    fn frames_from_another_version_are_refused_not_misread() {
3493        let mut frame = serde_json::to_value(RemoteActionFrame::new(
3494            RemoteActionMessage::CatalogueRequest {
3495                correlation: 1,
3496                query: CatalogueQuery::default(),
3497            },
3498        ))
3499        .unwrap();
3500        frame["version"] = serde_json::json!(REMOTE_ACTIONS_VERSION + 1);
3501        // A newer peer may also use a message this build has never seen.
3502        frame["message"] = serde_json::json!({"Subscribe": {"topic": 1}});
3503        let bytes = serde_json::to_vec(&frame).unwrap();
3504        assert_eq!(
3505            RemoteActionFrame::decode(&bytes),
3506            Err(RemoteFrameError::UnsupportedVersion {
3507                version: REMOTE_ACTIONS_VERSION + 1
3508            })
3509        );
3510        assert!(matches!(
3511            RemoteActionFrame::decode(
3512                format!(r#"{{"version":{REMOTE_ACTIONS_VERSION},"message":{{"Subscribe":{{}}}}}}"#)
3513                    .as_bytes()
3514            ),
3515            Err(RemoteFrameError::Malformed(_))
3516        ));
3517        assert!(matches!(
3518            RemoteActionFrame::decode(&vec![b' '; MAX_REMOTE_ACTION_FRAME_BYTES + 1]),
3519            Err(RemoteFrameError::TooLarge { .. })
3520        ));
3521    }
3522
3523    fn the_wire_names_versions_and_messages_explicitly() {
3524        let bytes = RemoteActionFrame::new(RemoteActionMessage::Cancel {
3525            invocation: InvocationId(uuid::Uuid::nil()),
3526        })
3527        .encode()
3528        .unwrap();
3529        assert_eq!(
3530            String::from_utf8(bytes).unwrap(),
3531            format!(
3532                r#"{{"version":{REMOTE_ACTIONS_VERSION},"message":{{"Cancel":{{"invocation":"00000000-0000-0000-0000-000000000000"}}}}}}"#
3533            )
3534        );
3535    }
3536
3537    fn a_retried_invocation_reports_the_original_and_runs_once() {
3538        let provider = CountingHost::new();
3539        let id = InvocationId::new();
3540        let first = now(provider.invoke(&alice(), archive(id))).unwrap();
3541        assert_eq!(first.status, ReceiptStatus::Accepted);
3542        let retry = now(provider.invoke(&alice(), archive(id))).unwrap();
3543        assert_eq!(retry, first);
3544        assert_eq!(provider.runs(), 1, "a retry never starts a second run");
3545
3546        provider.finish(&alice(), &id);
3547        let after = now(provider.invoke(&alice(), archive(id))).unwrap();
3548        assert!(matches!(after.status, ReceiptStatus::Completed { .. }));
3549        assert_eq!(provider.runs(), 1, "a retry after completion reports it");
3550    }
3551
3552    fn an_invocation_id_cannot_be_reused_or_borrowed() {
3553        let provider = CountingHost::new();
3554        let id = InvocationId::new();
3555        now(provider.invoke(&alice(), archive(id))).unwrap();
3556
3557        let mut different = archive(id);
3558        different.argument = InvokeArgument::Text("other".into());
3559        assert_eq!(
3560            now(provider.invoke(&alice(), different)),
3561            Err(ActionCallError::InvocationConflict)
3562        );
3563        assert_eq!(
3564            now(provider.invoke(&mallory(), archive(id))),
3565            Err(ActionCallError::InvocationConflict),
3566            "another actor cannot attach to someone else's invocation"
3567        );
3568        assert_eq!(provider.observe(&mallory(), &id), None);
3569        assert_eq!(
3570            now(provider.cancel(&mallory(), &id)),
3571            Err(ActionCallError::UnknownInvocation)
3572        );
3573        assert_eq!(provider.runs(), 1);
3574    }
3575
3576    fn a_refused_invocation_is_not_remembered() {
3577        let mut log = InvocationLog::<u32>::default();
3578        let request = archive(InvocationId::new());
3579        assert_eq!(
3580            log.admit(&alice(), &request, || Err(ActionCallError::NotPermitted)),
3581            Err(ActionCallError::NotPermitted)
3582        );
3583        let (handle, admission) = log.admit(&alice(), &request, || Ok(5)).unwrap();
3584        assert_eq!((*handle, admission), (5, Admission::Started));
3585    }
3586
3587    fn the_log_forgets_oldest_invocations_past_capacity() {
3588        let mut log = InvocationLog::<u32>::with_capacity(2);
3589        let requests: Vec<_> = (0..3).map(|_| archive(InvocationId::new())).collect();
3590        for (n, request) in (0u32..).zip(&requests) {
3591            log.admit(&alice(), request, || Ok(n)).unwrap();
3592        }
3593        assert_eq!(log.get(&alice(), &requests[0].invocation), None);
3594        assert_eq!(log.get(&alice(), &requests[2].invocation), Some(&2));
3595    }
3596
3597    fn serve_answers_requests_and_ignores_responses() {
3598        let provider = std::sync::Arc::new(CountingHost::new());
3599        let id = InvocationId::new();
3600        let Some(RemoteActionMessage::Receipt(receipt)) = serve(
3601            &provider,
3602            &alice(),
3603            RemoteActionMessage::Invoke(archive(id)),
3604        )
3605        .map(now) else {
3606            panic!("an invoke is answered with a receipt");
3607        };
3608        assert_eq!(receipt.status, ReceiptStatus::Accepted);
3609
3610        let mut unknown = archive(InvocationId::new());
3611        unknown.target.address = ActionAddress::new("note:2", "delete");
3612        assert_eq!(
3613            serve(
3614                &provider,
3615                &alice(),
3616                RemoteActionMessage::Invoke(unknown.clone())
3617            )
3618            .map(now),
3619            Some(RemoteActionMessage::Receipt(InvocationReceipt {
3620                invocation: unknown.invocation,
3621                status: ReceiptStatus::Rejected {
3622                    error: ActionCallError::UnknownAction
3623                },
3624            }))
3625        );
3626        assert_eq!(
3627            serve(
3628                &provider,
3629                &alice(),
3630                RemoteActionMessage::Cancel { invocation: id }
3631            )
3632            .map(now),
3633            Some(RemoteActionMessage::CancelResponse {
3634                invocation: id,
3635                result: Ok(()),
3636            })
3637        );
3638        let Some(RemoteActionMessage::Update {
3639            state: Some(state), ..
3640        }) = serve(&provider, &alice(), RemoteActionMessage::observe(id)).map(now)
3641        else {
3642            panic!("an observe is answered with the invocation state");
3643        };
3644        assert!(matches!(
3645            state.receipt().status,
3646            ReceiptStatus::Cancelled { .. }
3647        ));
3648        assert!(serve(&provider, &alice(), RemoteActionMessage::Receipt(receipt)).is_none());
3649    }
3650
3651    fn typed_arguments_use_the_local_invocation_slot() {
3652        let mut object = serde_json::Map::new();
3653        object.insert("n".into(), serde_json::json!(2));
3654        assert_eq!(InvokeArgument::None.to_slot(), None);
3655        assert_eq!(
3656            InvokeArgument::Text("hi".into()).to_slot().as_deref(),
3657            Some("hi")
3658        );
3659        assert_eq!(
3660            InvokeArgument::Json(object.clone()).to_slot(),
3661            Some(format!("{ARGUMENTS_JSON_PREFIX}{{\"n\":2}}"))
3662        );
3663        // A slot read back names the argument it was written from, so a
3664        // device that sends an invocation on runs what it admitted.
3665        for argument in [
3666            InvokeArgument::None,
3667            InvokeArgument::Text("hi".into()),
3668            InvokeArgument::Json(object),
3669        ] {
3670            assert_eq!(
3671                InvokeArgument::from_slot(argument.to_slot().as_deref()),
3672                argument
3673            );
3674        }
3675    }
3676
3677    fn a_remote_device_is_the_person_its_root_names() {
3678        let caller = Caller::authenticated([0xAB; 32], [1; 32]);
3679        assert_eq!(
3680            caller.acting().member_id(),
3681            Some(&tilo_action_policy::MemberId::person("ab".repeat(32))),
3682            "every device of one person is the same member"
3683        );
3684        assert_eq!(caller.workspace(), None);
3685        let agent = Caller::local_agent("helper", "ada").in_workspace("workspace-1");
3686        assert_eq!(
3687            agent.acting().member_id(),
3688            Some(&tilo_action_policy::MemberId::agent("helper", "ada"))
3689        );
3690        assert_eq!(agent.workspace(), Some("workspace-1"));
3691        assert_eq!(agent.device_public_key(), None);
3692    }
3693
3694    fn a_refusal_answers_every_request_and_nothing_else() {
3695        let error = ActionCallError::Unavailable {
3696            reason: "down".into(),
3697        };
3698        let id = InvocationId::new();
3699        assert_eq!(
3700            refuse(&invoke_message(id), error.clone()),
3701            Some(RemoteActionMessage::Receipt(InvocationReceipt {
3702                invocation: id,
3703                status: ReceiptStatus::Rejected {
3704                    error: error.clone()
3705                },
3706            }))
3707        );
3708        assert_eq!(
3709            refuse(&RemoteActionMessage::observe(id), error.clone()),
3710            Some(RemoteActionMessage::Update {
3711                invocation: id,
3712                state: None,
3713                correlation: Some(0),
3714            })
3715        );
3716        assert_eq!(
3717            refuse(
3718                &RemoteActionMessage::Update {
3719                    invocation: id,
3720                    state: None,
3721                    correlation: None,
3722                },
3723                error
3724            ),
3725            None
3726        );
3727    }
3728
3729    fn invoke_message(id: InvocationId) -> RemoteActionMessage {
3730        RemoteActionMessage::Invoke(archive(id))
3731    }
3732
3733    /// A change feed, asked across the API.
3734    mod change_wire;
3735
3736    tilo_test_env::scenario! {
3737        fn a_host_serves_each_invocation_once_as_its_caller;
3738
3739        phase a_retry_with_another_appearance_is_another_invocation;
3740        {
3741            let request = archive(InvocationId(uuid::Uuid::from_u128(9)));
3742            let appearing = InvokeRequest {
3743                appearance: Some(crate::Appearance::new("alice", None, None).unwrap()),
3744                ..request.clone()
3745            };
3746            assert!(!request.same_invocation(&appearing));
3747            assert!(appearing.same_invocation(&InvokeRequest {
3748                wait_ms: Some(10),
3749                ..appearing.clone()
3750            }));
3751            let json = serde_json::to_string(&request).unwrap();
3752            assert!(!json.contains("appearance"), "{json}");
3753        }
3754
3755        phase remote_invocations_run_at_most_once_per_owned_id;
3756        // A retried invocation reports the original and runs once; ids cannot be reused or borrowed;
3757        // refusals are not remembered; the log forgets the oldest past capacity; a reservation holds
3758        // the id until the start completes.
3759        // Invocations each phase below in order; every phase builds its own fixture.
3760        {
3761            a_retried_invocation_reports_the_original_and_runs_once();
3762            an_invocation_id_cannot_be_reused_or_borrowed();
3763            a_refused_invocation_is_not_remembered();
3764            the_log_forgets_oldest_invocations_past_capacity();
3765            a_reservation_holds_the_id_until_the_start_completes();
3766        }
3767
3768        phase admitted_executions_share_authority_but_cannot_borrow_invocations;
3769        {
3770            let first = alice().in_new_execution();
3771            let second = alice().in_new_execution();
3772            assert_eq!(first.acting(), second.acting());
3773            assert_eq!(first.workspace(), second.workspace());
3774            assert_ne!(first.execution_id(), second.execution_id());
3775            let provider = CountingHost::new();
3776            let id = InvocationId::new();
3777            let admitted = now(provider.invoke(&first, archive(id))).unwrap();
3778            assert_eq!(now(provider.invoke(&first, archive(id))).unwrap(), admitted);
3779            assert_eq!(
3780                now(provider.invoke(&second, archive(id))),
3781                Err(ActionCallError::InvocationConflict)
3782            );
3783            assert_eq!(provider.observe(&second, &id), None);
3784            assert_eq!(
3785                now(provider.cancel(&second, &id)),
3786                Err(ActionCallError::UnknownInvocation)
3787            );
3788            let retained = first.clone();
3789            let hash = |caller: &Caller| {
3790                let mut hasher = std::collections::hash_map::DefaultHasher::new();
3791                std::hash::Hash::hash(caller, &mut hasher);
3792                std::hash::Hasher::finish(&hasher)
3793            };
3794            let before = hash(&first);
3795            provider.retire_execution(&first);
3796            assert!(!retained.execution_is_live());
3797            assert!(second.execution_is_live());
3798            assert_eq!(first, retained);
3799            assert_eq!(hash(&first), before);
3800            let reconnected = retained.in_new_execution();
3801            assert!(reconnected.execution_is_live());
3802            assert_ne!(reconnected.execution_id(), first.execution_id());
3803            provider.finish(&first, &id);
3804            assert!(matches!(
3805                now(provider.invoke(&first, archive(id))).unwrap().status,
3806                ReceiptStatus::Completed { .. }
3807            ));
3808            assert!(provider.observe(&first, &id).is_some());
3809            assert!(provider.observe(&second, &id).is_none());
3810            // The connection that replaced the ended one is the same caller going on: it follows
3811            // and asks again what it started there, and the invocation is carried out once. The
3812            // one open beside it borrows nothing, even now.
3813            assert!(reconnected.continues(&first));
3814            assert!(!second.continues(&first));
3815            assert!(provider.observe(&reconnected, &id).is_some());
3816            assert!(matches!(
3817                now(provider.invoke(&reconnected, archive(id))).unwrap().status,
3818                ReceiptStatus::Completed { .. }
3819            ));
3820            assert_eq!(provider.runs(), 1);
3821            let someone_else = Caller::authenticated([3; 32], [4; 32]).in_new_execution();
3822            assert!(!someone_else.continues(&first), "another device continues nothing");
3823        }
3824
3825        phase serving_answers_each_request_as_the_person_the_device_belongs_to;
3826        // Serve answers requests and ignores responses, typed arguments use the local invocation slot,
3827        // a remote device is the person its root names, and a refusal answers every request and nothing
3828        // else.
3829        // Invocations each phase below in order; every phase builds its own fixture.
3830        {
3831            serve_answers_requests_and_ignores_responses();
3832            typed_arguments_use_the_local_invocation_slot();
3833            a_remote_device_is_the_person_its_root_names();
3834            a_refusal_answers_every_request_and_nothing_else();
3835        }
3836
3837        phase capacity_churn_preserves_in_flight_deduplication;
3838        {
3839            let caller = alice();
3840            let mut log = InvocationLog::<u32>::with_capacity(3);
3841            let pending = archive(InvocationId::new());
3842            assert_eq!(log.reserve(&caller, &pending), Ok(Reservation::Reserved));
3843            let mut completed = VecDeque::new();
3844            for n in 0..8 {
3845                let request = archive(InvocationId::new());
3846                assert_eq!(
3847                    log.admit(&caller, &request, || Ok(n)),
3848                    Ok((&n, Admission::Started))
3849                );
3850                completed.push_back(request.invocation);
3851                if completed.len() > 2 {
3852                    let evicted = completed.pop_front().unwrap();
3853                    assert_eq!(log.get(&caller, &evicted), None);
3854                }
3855                for id in &completed {
3856                    assert!(log.get(&caller, id).is_some());
3857                }
3858                assert!(matches!(
3859                    log.admit(&caller, &pending, || panic!("duplicate dispatch")),
3860                    Err(ActionCallError::Unanswered)
3861                ));
3862                assert_eq!(
3863                    log.reserve(&mallory(), &pending),
3864                    Err(ActionCallError::InvocationConflict)
3865                );
3866            }
3867            log.complete(&pending.invocation, 99);
3868            assert_eq!(
3869                log.admit(&caller, &pending, || panic!("duplicate dispatch")),
3870                Ok((&99, Admission::Retried))
3871            );
3872            let next = archive(InvocationId::new());
3873            assert_eq!(log.reserve(&caller, &next), Ok(Reservation::Reserved));
3874            assert_eq!(log.get(&caller, &pending.invocation), None);
3875        }
3876
3877        phase capacity_churn_refuses_new_ids_when_every_slot_is_reserved;
3878        {
3879            let caller = alice();
3880            // Zero capacity is clamped to one, which must still protect its reservation.
3881            for capacity in 0..=2 {
3882                let mut log = InvocationLog::<u32>::with_capacity(capacity);
3883                let pending: Vec<_> = (0..capacity.max(1))
3884                    .map(|_| archive(InvocationId::new()))
3885                    .collect();
3886                for request in &pending {
3887                    assert_eq!(log.reserve(&caller, request), Ok(Reservation::Reserved));
3888                }
3889                let refused = archive(InvocationId::new());
3890                for _ in 0..4 {
3891                    assert!(matches!(
3892                        log.admit(&caller, &refused, || panic!("dispatch at capacity")),
3893                        Err(ActionCallError::Unavailable { .. })
3894                    ));
3895                    for request in &pending {
3896                        assert!(matches!(
3897                            log.admit(&caller, request, || panic!("duplicate dispatch")),
3898                            Err(ActionCallError::Unanswered)
3899                        ));
3900                    }
3901                }
3902                for (n, request) in pending.iter().enumerate() {
3903                    let n = u32::try_from(n).unwrap();
3904                    log.complete(&request.invocation, n);
3905                    assert_eq!(
3906                        log.admit(&caller, request, || panic!("duplicate dispatch")),
3907                        Ok((&n, Admission::Retried))
3908                    );
3909                }
3910                // Capacity refusals are not remembered and can be retried later.
3911                assert_eq!(log.reserve(&caller, &refused), Ok(Reservation::Reserved));
3912                log.abandon(&refused.invocation);
3913                assert_eq!(log.reserve(&caller, &refused), Ok(Reservation::Reserved));
3914            }
3915        }
3916    }
3917
3918    fn a_reservation_holds_the_id_until_the_start_completes() {
3919        let mut log = InvocationLog::<u32>::default();
3920        let request = archive(InvocationId::new());
3921        assert_eq!(log.reserve(&alice(), &request), Ok(Reservation::Reserved));
3922        assert!(
3923            matches!(
3924                log.reserve(&alice(), &request),
3925                Err(ActionCallError::Unanswered)
3926            ),
3927            "a retry during the start neither runs twice nor pretends to be admitted: it is \
3928             asked again, as an answer lost on its way is"
3929        );
3930        assert_eq!(log.get(&alice(), &request.invocation), None);
3931        log.complete(&request.invocation, 9);
3932        assert_eq!(log.reserve(&alice(), &request), Ok(Reservation::Admitted));
3933        assert_eq!(log.get(&alice(), &request.invocation), Some(&9));
3934
3935        let failed = archive(InvocationId::new());
3936        assert_eq!(log.reserve(&alice(), &failed), Ok(Reservation::Reserved));
3937        log.abandon(&failed.invocation);
3938        assert_eq!(
3939            log.reserve(&alice(), &failed),
3940            Ok(Reservation::Reserved),
3941            "an abandoned start ran nothing and may be admitted again"
3942        );
3943    }
3944
3945    #[test]
3946    fn action_call_error_constructors_build_the_exact_variants() {
3947        let refused = ActionCallError::refused("not allowed now");
3948        assert_eq!(
3949            refused,
3950            ActionCallError::Refused {
3951                reason: "not allowed now".to_owned(),
3952            }
3953        );
3954        assert_eq!(refused.code(), "refused");
3955        assert_eq!(refused.said(), "refused: not allowed now");
3956        let owned_refusal = String::from("not allowed now");
3957        assert_eq!(ActionCallError::refused(owned_refusal), refused);
3958
3959        let invalid = ActionCallError::invalid_request("missing field");
3960        assert_eq!(
3961            invalid,
3962            ActionCallError::InvalidRequest {
3963                reason: "missing field".to_owned(),
3964            }
3965        );
3966        assert_eq!(invalid.code(), "invalid_arguments");
3967        assert_eq!(invalid.said(), "invalid_arguments: missing field");
3968        let owned_invalid = String::from("missing field");
3969        assert_eq!(ActionCallError::invalid_request(owned_invalid), invalid);
3970
3971        let unavailable = ActionCallError::unavailable("service off");
3972        assert_eq!(
3973            unavailable,
3974            ActionCallError::Unavailable {
3975                reason: "service off".to_owned(),
3976            }
3977        );
3978        assert_eq!(unavailable.code(), "remote_actions_unavailable");
3979        assert_eq!(unavailable.said(), "unavailable: service off");
3980        let owned_unavailable = String::from("service off");
3981        assert_eq!(ActionCallError::unavailable(owned_unavailable), unavailable);
3982    }
3983}