Web Prolog manual

This web edition of Appendix B specifies the common Web Prolog language and API contract. The node’s HTTP and WebSocket interfaces are specified separately in Appendix D of the book. Both references describe a design in progress: the rules stated here are requirements for conforming implementations, rather than an inventory of current implementation behaviour. Deployment and implementation guides document setup, capabilities and any remaining conformance gaps.

The classification shown beside each entry identifies the minimum public node profile in which the predicate is available, or another relevant execution context. ISOBASE provides general stateless Prolog calls, ISOTOPE adds persistent toplevel sessions, and ACTOR adds the full stateful actor-messaging model. The profiles are cumulative, so an entry marked isotope is also available in ACTOR. The classification concerns the client language, not predicates used internally to implement a profile. Entries additionally marked owner only are reserved for code running with node-owner authority and are not available to ordinary client code.

The draft interoperability baseline 0.1 links selected requirements to executable tests and a coverage matrix. It includes GNU Prolog at ISOBASE level; this does not imply ACTOR support or completion of its broader ISOBASE audit. Untested and unresolved behavior remains explicit rather than being counted as passing.

Each predicate entry has a stable anchor based on its indicator. For runtime setup, deployment and implementation differences, see the native SWI guide, Trealla guide, GNU ISOBASE guide and SWI-WASM guide. The service examples document application-specific text handling.

Common conventions

The language contract is independent of the host Prolog system and execution mechanism. Environmental capabilities, including persistence, inbound connectivity, DOM access and hard termination, are reported by runtime_property/1. They do not change predicate meanings or result formats.

A client context groups one client interaction and its descendants. The hosting environment establishes the context and its lifetime, for example for an interactive session or a stateless request. Local and remote child creation retain that association. At each node, ordinary names and promises are scoped to this context. Sharing authentication credentials does not by itself merge contexts; reuse across requests requires an explicitly retained client context. Ending one request or replacing one toplevel within an explicitly retained context does not close that context. A remote descendant returning to a node retains its original context association there; it does not acquire a new context merely because its transport or execution engine changes.

Closing a context ends admission to its ordinary-name and promise scopes. Late creation, publication or attachment cannot reopen the closed scopes. An attachment concurrent with closure either joins the still-open context or is rejected after closure; it must not join a context whose retirement has already been committed. Context closure and actor termination are distinct: closing these scopes does not by itself terminate surviving actors. Standalone execution has an environment-provided root context.

Operator declarations

Web Prolog uses the following operator declarations.

:- op(800, xfx, !).
:- op(1000, xfy, if).
:- op(200, xfx, @).

Thus @ binds more tightly than !, which binds more tightly than conjunction. The right-associative if has the same priority as the comma, so Pattern if A, B -> Body is read as (Pattern if (A, B)) -> Body. Parentheses around a conjunctive guard remain useful for readability.

URI values

A URI value is an atom, a string object, or a proper list of characters or character codes. This applies to RPC and promise destinations, source URIs, the node/1 spawn option, and the node component of an actor address Id@Node used by sends, monitors and exits. Accepted text is normalised to an atom for routing; different text representations of the same node identify the same actor. The node alias localhost identifies the caller's own node.

For node identity, an empty root path is canonical: https://node/ and https://node identify the same node. Peer credentials and owner dial mappings use that canonical node key. Duplicate canonical credential entries and conflicting endpoint mappings are rejected. Different schemes, authorities, ports and non-root paths remain distinct; query and fragment text is preserved.

An implicit local spawn retains its caller’s client context. An explicit node URL uses a receiving transport context, including a URL that points back to the same server. Ordinary names remain scoped to that client context; published services provide node-wide discovery.

An uninstantiated URI value raises an instantiation error without binding it; a non-text value raises type_error(atom_or_string, Value). The compound Host:Port shorthand is not accepted. Validation precedes source fetching, actor creation or request dispatch, as appropriate.

Representation normalisation does not introduce URI resolution, case-folding, escaping or fetch permissions. URI syntax, schemes, ports, relative paths, file access and origin restrictions remain subject to each entry’s resolution and fetch policy. Accepted text need not denote an allowed or reachable URI.

Options and validation

A Boolean option takes the atom true or false. This applies to link/1, monitor/1, session/1, trace/1 and once/1.

Option lists must be proper lists of recognised options with the documented arities and values. Every occurrence is validated, including later duplicates. The first occurrence of a scalar option determines its setting; repeated source options are additive. These rules apply to the creation predicates, toplevel calls and their synchronous wrappers, first_solution/3, rpc/3, promise/4 and yield/3.

Validation preserves shared variables and does not bind uninstantiated option values or execute goals or callbacks. It completes before source fetching, actor creation, request dispatch or promise collection, as appropriate. An invalid yield/3 option leaves the promise available for retry.

Errors have the form error(Formal, Context). A required value that is uninstantiated raises instantiation_error; a value of the wrong type raises type_error(ExpectedType, Value); and a value of the required type outside the permitted domain raises domain_error(Domain, Value). Boolean values have type atom and domain boolean. An unknown option or an option with an incorrect arity raises a domain error identifying the API’s option family. The Context argument supplies diagnostic information and is not part of the portable contract. Internal implementation metadata is not a public option.

Transport endpoints decode their wire representations before invoking the language API. Transport decoding is specified separately in Appendix D of the book.

Source loading

Source options are processed from left to right in option-list order, regardless of source kind. Clause order is preserved within each source text, clause list or copied predicate. Repeated clause-source options are additive; repeated URIs are fetched separately at each occurrence. An entry requiring exactly one initial document, such as statechart_spawn/2, rejects multiple document sources instead of combining them. All source is loaded before the goal runs and remains private to the receiving actor or stateless call. A source-loading failure prevents the goal from starting.

A directive in supplied source that fails, or that the receiving engine does not carry out, is a creation error. Creation raises error(directive_failed(Directive), Context), where Directive is the first such directive without module qualification. No actor or session is created and the goal does not run. This applies to spawn/3, toplevel_spawn/2 and the other creation predicates that accept source options, locally and remotely, on every engine. A directive that raises an exception remains subject to the engine’s exception reporting.

The caller prepares source before local execution or remote dispatch. For URI source, the caller fetches the contents and supplies them to the destination in the position specified by the option list. This rule applies to local and remote actor creation, RPC and promises. A promise completes source preparation before starting its asynchronous request and returning its reference; preparation errors are raised by the promise call itself.

The caller also fetches the initial statechart XML when it is supplied by URI and passes the document to the engine or node that will run the chart. The document’s URI is preserved as the base for resolving relative references. Any later document fetch explicitly requested by the running chart takes place in that chart’s execution environment.

URI resolution and fetching follow the caller’s access restrictions, including file-access permissions, origin restrictions and CORS where applicable. Relative source URIs are resolved in the caller’s environment, not against the destination’s public URL. Loading and execution follow the destination’s profile and sandbox; sender module names grant no authority.

Source text may be supplied as an atom or a string. Source predicates are identified by atom names and nonnegative integer arities.

Predicates for programming with core actors

Predicate: self/1
actor
self(-Pid) is det.

Binds Pid to the process identifier of the calling process.
Note: A pid is an actor address whose canonical global form is Id@Node, where Id is assigned by Node. This ordinary Prolog compound is part of the language contract: programs may copy, store, construct, decompose, compare, and serialise it. A shell may omit @Node when displaying a pid on the shell’s own node, but this is only a local abbreviation. Constructing a pid does not create an actor, confirm that it is live, or grant access to it; an operation reaches an actor only when the pair designates that actor and the node authorises the operation. Arithmetic on a numeric Id has no defined actor-level meaning. Web Prolog runtimes reserve localhost as the local-node designator. Passing such a pid across a node boundary requires preserving its originating routing context; it must not be reinterpreted as an address on the receiving node. Actor identifiers carry no host-engine or placement semantics.

In the browser, the main actor has pid main@localhost. Other local browser actors have pids of the form Id@localhost.

Predicate: spawn/1-3
actor
spawn(+Goal) is det.
spawn(+Goal, -Pid) is det.
spawn(+Goal, -Pid, +Options) is det.

Creates a new Web Prolog actor process running a copy of Goal. The new actor’s pid is unified with Pid before Goal is copied. If the same variable occurs in Goal and the pid argument, those occurrences therefore carry the child’s pid in the copy. Variables occurring more than once in Goal retain that sharing within the copy, but no variable identity is shared between the parent and child: bindings produced by the child do not bind variables in the parent, and subsequent parent bindings do not bind variables in the child. These rules are the same for local and remote spawning. Results that must cross the process boundary have to be returned explicitly, for example in a message or through a toplevel protocol.

Admission charges the principal’s whole locally hosted subtree. At the actor or CPU quota, spawning raises error(resource_error(actors),Context) or error(resource_error(cpu),Context). A non-owner’s link(false) raises:

error(permission_error(spawn, detached_actor, link(false)),
      Context)

Loss of the transport during a remote spawn raises:

error(remote_spawn_failed(connection_closed), Context)

The remote outcome is unknown, so a retry of effectful work requires application duplicate suppression.

Valid options are:

Note: In spawn(+Goal, -Pid, +Options), the option monitor(true) installs monitoring as part of process creation. When the child terminates, the parent receives a message down(Pid, Ref, Reason) where Pid is the terminated actor, Reason is its exit reason, and Ref identifies the monitor instance. For monitoring created via monitor(true), the portable contract is Ref = Pid; this lets the spawning process identify and remove that monitor even though spawn/3 returns no separate monitor reference.
Down-reason contract: The third argument of down(Pid, Ref, Reason) uses the following portable vocabulary: true means that the actor goal succeeded; false means that it failed; exception(E) carries the public representation of the uncaught exception; an arbitrary nonvar term may be supplied explicitly through exit/1-2; and no_process means that the monitored target did not exist when the monitor was installed. The boundary reason connection_closed means that observation of a remote target was lost; it does not assert that the target terminated. For an uncaught error(Formal,Context), the monitor notification preserves Formal but replaces Context with an unbound variable. An undefined-procedure error also omits a private generated actor-module qualification. Other exit reasons are unchanged.
Note: The semantics of link(true) are directional: if a parent spawns a child with linking enabled, termination of the parent causes linked children to be terminated. The link does not imply symmetric bidirectional exit propagation, and the child cannot trap the termination. The same rule applies to local and remote children. Remote creation installs the link before activation, and loss of the owning connection causes the hosting node to request termination of its linked children. A partition may delay detection and cleanup; observation loss alone does not establish completed reclamation. See the book’s section on remote links and monitors.

Options follow the common validation rules in Options and validation. node/1 takes an atom; link/1 and monitor/1 take true or false. Source options follow Source loading. Plain spawn/3 does not accept name/1; the specialised creation predicates provide named creation.

Named creation reserves the caller’s ordinary name before starting the actor and publishes it only after successful setup. An occupied or pending name prevents creation; pending names are invisible to whereis/2 and cannot be cancelled by unregister/1. Failure or interruption releases the reservation and reclaims resources owned by that attempt. Publication guarantees neither continued liveness nor application readiness. A remote name is an alias in the caller’s namespace, not a registration on the destination. Both local and remote named creation publish the prepared actor before activating its application goal. Remote creation therefore requires a preparation acknowledgement and an activation step after caller-side publication. A failed preparation never publishes a name. See register/2 for namespace and alias lifetimes.

Named remote creation requires a correlated spawn acknowledgement. An uncorrelated peer is rejected with remote_spawn_failed(uncorrelated_spawn_reply). Peer negotiation and compatibility adapters are specified separately from this language contract. Connection loss can raise remote_spawn_failed(connection_closed) while leaving the remote outcome unknown. Cleanup can request termination of a known remote pid but cannot undo remote side effects or guarantee cancellation after connection loss.

Local target/1 and io_target/1 select actor I/O routing, with io_target/1 taking precedence. Public WebSocket creation retains the connection’s control of those routes. Validation follows Options and validation, and mixed-source ordering follows Source loading.

Predicate: actors/1
actor
actors(-Pids) is det.

Binds Pids to the list of actor pids visible from the current execution context. In ordinary public client execution, this means the current actor or toplevel together with any actors that have been spawned on behalf of the same client interaction. Actors belonging to other clients are not included.

Note: Outside public client execution, for example in node-owned runtime code or administrative code, actors/1 returns the pids of all active local actors on the node.

Predicate: monitor/2
actor
monitor(+PidOrName, -Ref) is det.

Installs a monitor and returns a fresh reference in Ref. The first argument may be a pid or a registered local name, subject to the same target policy as sending. Fresh references are single-use and provide correlation, not sender authentication. References are opaque and must not be constructed or interpreted by application code. When the monitored process terminates, the monitoring process receives a message of the form down(Pid, Ref, Reason). If observation of a remote target is lost, the runtime instead delivers the same form with Reason = connection_closed. This discharges the monitor without claiming that the target terminated; reconnection does not restore it automatically.

Spawn-time monitoring and additional monitors are independent, including private monitors used by synchronous waits. Each active reference receives its own termination notification; removing a private or explicit monitor does not suppress notifications for other references.

Note: Using monitor(true) in spawn/3 installs monitoring before the child can terminate, so its actual exit reason is observed. If monitor/2 is called after the target has already terminated, the runtime still discharges the monitor with down(Pid,Ref,no_process).

Predicate: demonitor/1-2
actor
demonitor(+Ref) is det.
demonitor(+Ref, +Options) is det.

Stops the calling actor’s monitor identified by Ref. An unknown reference or another actor’s reference has no effect. This is idempotent. There is only one valid option:

For a remote monitor, removal is confirmed before the operation returns or applies flush. If confirmation times out, the operation raises error(remote_demonitor_timeout(Pid), Context) and retains the local monitor record for retry. Once the connection has been declared closed, local withdrawal suffices because that connection can deliver no further notifications. A successful removal prevents later notifications for that reference; already queued notifications remain unless flush is used.

Predicate: register/2
actor
register(+Name, +Pid) is det.

Registers the actor identified by Pid under atom Name. A pid may have one ordinary name and, independently, one service name. An occupied name or already named pid is rejected; a missing or terminating local pid raises existence_error(process,Pid). Registering a remote pid does not establish that it is alive or install a monitor.

Ordinary names belong to the caller’s client context and are inherited by its descendants. The node-wide service namespace is separate. Closing a client context removes its registrations and pending reservations and rejects late publication; removing a name does not terminate its actor.

Local termination removes ordinary registrations. A remote alias is withdrawn on observed termination of its exact pid or closure of the connection through which that alias is maintained. Cleanup preserves aliases associated with other connections, names rebound to another pid, service names and unrelated monitors. Connection loss does not prove remote death. Without an observed event, explicit unregister/1 may still be needed.

An already named pid raises permission_error(register, process, Pid); an occupied name raises permission_error(register, actor_name, Name). These formal terms are wrapped in error(Formal,Context) as described in the common error contract. The same errors apply to pending name reservations and named creation; a rejected operation preserves the existing registration and does not create or publish a replacement actor. A closed context rejects late registration with permission_error(register, closed_namespace, Namespace).

Predicate: whereis/2
actor
whereis(+Name, -Pid) is det.

Binds Pid to the value registered under Name in the caller’s ordinary namespace, or to undefined if no such registration exists. Lookup does not establish that the actor is alive.

Predicate: unregister/1
actor
unregister(+Name) is det.

Removes the association in the caller’s ordinary namespace. The actor itself is not terminated. The operation is idempotent and succeeds without effect if Name is not registered in that namespace.

Predicate: register_service/2
actor, owner only
register_service(+Name, +Pid) is det.

Publishes the live local actor identified by Pid under Name in the node’s public service namespace. Name must be an atom, Pid must identify an actor on the publishing node, and there may be at most one published service with a given name on a node. If the name is already published, register_service/2 raises permission_error(register, service, Name), even when the existing entry denotes the same actor. Replacement is therefore explicit: the owner must first withdraw the old mapping.

The public service namespace is distinct from the ordinary registration namespace used by register/2; the same atom may occur in both without a collision. A qualified address Name@Node is resolved against the public service namespace of Node. whereis/2 consults only the ordinary namespace; owner-side code may inspect the service namespace with whereis_service/2.

Publication neither changes the actor’s links nor places it under supervision. In particular, register_service/2 does not detach the actor from its parent. When the actor terminates, the node controller removes the service mapping atomically, so a published name never remains bound to a dead pid. A supervisor that starts a replacement actor must publish that actor again under the stable name.

Only code executing with node-owner authority may call this predicate. A call by any other principal raises permission_error(register, service, Name). A non-atom Name raises type_error(atom, Name); a Pid that does not identify a live actor raises existence_error(process, Pid); and an attempt to publish an actor on another node raises permission_error(register, service, Pid).

Predicate: whereis_service/2
actor, owner only
whereis_service(+Name, -Pid) is det.

Binds Pid to the live local actor published as Name, or to undefined if no such service is published. This predicate inspects only the public service namespace. Only code executing with node-owner authority may call it; other callers receive:

permission_error(access, actor_service_registry,
                 whereis_service(Name, Pid))

A non-atom Name raises type_error(atom, Name).

Predicate: unregister_service/1
actor, owner only
unregister_service(+Name) is det.

Withdraws Name from the node’s public service namespace. This operation removes only the name; it neither terminates nor otherwise changes the actor that the name denoted. The operation is idempotent: if no published service called Name exists, it succeeds without effect.

Only code executing with node-owner authority may call this predicate. A call by any other principal raises permission_error(unregister, service, Name), and a non-atom Name raises type_error(atom, Name).

Predicate: exit/1
actor
exit(+Reason) is det.

Terminates the calling process with Reason. If termination of the calling process has already been committed, the call has no effect and the original reason stands.

Predicate: exit/2
actor
exit(+Pid, +Reason) is det.

Sends an untrappable termination signal to the process identified by Pid, using Reason as its exit reason. The signal is not a mailbox message. The target must belong to the caller’s ownership tree unless the caller is a node owner; otherwise the call raises error(permission_error(exit,actor,Pid),Context). Host thread numbers and aliases are not actor pids. For remote actors, the runtime routes this request through the remote node. Termination commits when the target first accepts a termination signal; the first reason committed is final, and later termination or abort signals have no further observable effect. The signal takes effect at the target’s next safe point, which some operations can delay; see the book’s section on actors talking to other actors.

Predicates: !/2, send/2-3
actor
+PidOrName ! +Message is det.
send(+PidOrName, +Message) is det.
send(+PidOrName, +Message, +Options) is det.

Sends Message to the mailbox of the process identified as PidOrName. PidOrName may be a local pid, a local registered name, a global pid of the form Id@Node, or a published service address of the form Name@Node. A global pid may be a value returned by the runtime or a term constructed directly from a known identifier and node; the two are equivalent. Qualified service addresses are resolved only through the destination node’s live service registry. If such a service is absent or the sender is not authorised to use it, the send succeeds without delivery and does not reveal which condition applied. By contrast, an unknown local registered name raises existence_error(actor_name,Name); a send to an unknown pid succeeds without delivery. Language-level sending is open subject to node policy; admission may raise resource_error(mailbox) or resource_error(term_depth). Valid options for send/3 are:

Portable actor application messages are acyclic ordinary Prolog terms. Atoms, strings, numbers, variables, lists, and compound terms are portable. Each send constructs a fresh copy in the recipient: repeated occurrences of one variable remain shared within that copied message, but no variable identity is shared with the sender or with any separately sent message. There is consequently no distributed unification channel hidden in message passing. Attributed variables, streams, and other non-text blob values must be encoded explicitly by the application. A double-quoted literal denotes a string. The same message-term contract applies to local and remote sending; additional host-specific terms are outside the language.
Ordering: For one sender, messages sent repeatedly to the same pid are delivered in send order while one controller route remains in use. The same holds for one unchanged name binding during that routing epoch. There is no portable order across pid/name addressing, name rebinding, reconnects or rerouting, different senders, or messages and runtime signals. For delayed sends, ordering begins when the delayed operation actually emits the message. See the book’s section on uniform messaging across node boundaries.

Predicate: cancel/1
actor
cancel(+ID) is det.

Tries to cancel all delayed messages with the specified ID that were scheduled by the calling actor. Identifiers are actor-local: another actor may use the same ID without its delayed sends being affected. Cancellation is best-effort only, since a message may already have been sent by the time the call is made.

Predicate: output/1-2
actor
output(+Data) is det.
output(+Data, +Options) is det.

Sends a message output(Pid, Data) to the target process. Pid is the pid of the current process. Valid option:

This is a convenience predicate for ordinary actor messaging. Terminal writes such as format/2 and writeln/1 instead use the inherited terminal I/O target described in the book’s section on terminal authority across node boundaries. Any actor may use !/2 to send any term to any process to which it has a pid.

Predicate: input/2-3
actor
input(+Prompt, -Data) is det.
input(+Prompt, -Data, +Options) is det.

Sends prompt(Pid, Ref, Prompt) to the target process and waits for a reply carrying the fresh reference Ref. Prompt may be any Prolog term. Pid is the pid of the current process. Data is bound to the reply supplied through respond/3. Valid option:

Predicate: respond/3
actor
respond(+Pid, +Ref, +Input) is det.

Sends Input to Pid in response to the prompt that supplied Ref. A reply for an earlier prompt cannot answer a later prompt, even when both prompts came from the same actor.
The ACTOR badges on output/1-2, input/2-3, and respond/3 describe their availability to client programs. ISOTOPE sessions provide standard I/O predicates such as read/1 and writeln/1; the runtime implements session I/O through internal actor communication without exposing these actor predicates to ISOTOPE clients.

Predicate: receive/1-2
actor
receive(+Clauses) is nondet.
receive(+Clauses, +Options) is nondet.

Waits for, selects, and consumes one message from the calling process’s mailbox. A call is single-message, but not necessarily single-solution. During one invocation it selects and consumes at most one message. Messages are considered in arrival order, and each message is tested against the receive clauses in textual order. The first message accepted by a clause is removed from the mailbox. This selection is committed: backtracking through the invocation never selects another message or another clause.

The selected clause body is ordinary Prolog code. The call as a whole therefore has the determinism of the fired body: a body may fail, succeed once, throw an exception, or yield several solutions. Choice points left by the body remain available, but they enumerate solutions of that same body; they do not inspect the mailbox again. The selected message remains consumed if the body fails or throws, and is not restored on backtracking. Thus the nondet declaration concerns the possible number of logical solutions, not the number of messages consumed by one invocation. For example, after one foo message has arrived, receive({foo -> member(X, [a,b])}) consumes that message once but can yield both X = a and X = b.

A cut executed in a selected clause body is scoped to that body, as if the body were invoked through call/1. It can prune choice points created since entry to the body, but it cannot prune choice points in the caller; nor does it alter the already committed message and clause selection.

Clauses has the following form:

{  Pattern1 [if Guard1] ->
         Body1 ;
   ...
   PatternN [if GuardN] ->
         BodyN
}

A clause accepts a message if its pattern matches the message and its optional guard succeeds. Matching is one-sided: the pattern must subsume the message, so matching may bind variables in the pattern but never binds variables that occur in the message. For a ground message this is the same as unification. A guard is an ordinary goal and is not restricted in this way; a guard that checks a correlation reference or a pid should test the value, for example with ==, rather than bind it. Candidate matching and guard evaluation use a tentative substitution. If matching or the guard fails, all bindings made while trying that candidate are discarded before the next clause or message is considered; the mailbox is not changed until a clause accepts. A guard is evaluated for its first solution only, as if by once/1. Bindings from the successful pattern and guard are in scope in the body.

For portable code, a guard must be observationally free of side effects; the runtime is not required to enforce this restriction, and effects performed by a non-conforming guard are not undone when that guard fails. If a guard raises an ordinary exception, the exception and its tentative bindings are discarded and the clause does not accept the message. Control exceptions (abort, termination, and the enforced running-time limit; see the book’s section on actors talking to other actors) are not discarded: they propagate out of receive/1-2, and the message being examined remains in the mailbox in its original position. This error-as-non-match rule follows the selection discipline of restricted actor guards, but it also means that a guard which calls a fallible external service should translate failures into explicit results when the actor needs to distinguish them from an ordinary non-match.

Messages accepted by no clause are deferred: they remain in the mailbox, without any change in their contents or relative order, and are available to later receive calls. receive({}) accepts no message and waits, subject to Options. Valid options for receive/2 are:

Predicate: flush/0
actor
flush is det.

Removes all messages currently pending in the mailbox of the calling process. Each removed message is rendered through the actor terminal-output path as a line of the form Shell got Message, where Message is the full Prolog term.

Note: flush/0 is primarily a shell-level inspection utility. It does not wait for future messages: once the mailbox is empty at the time of the call, it succeeds immediately.

Predicate: listing/0-1
isotope
listing is det.
listing(+What) is det.

listing/0 lists the content of the private database of the current actor process through the terminal-output path. Imported predicates and the injected I/O wrapper predicates are omitted.

listing/1 lists the predicates or clauses in the current process’s private database selected by What, following the conventional Prolog meaning of listing/1. What may be a predicate indicator (Name/Arity or Name//Arity), a callable head pattern, a clause reference, or a list of such specifications. It does not provide access to another actor’s private database.

Predicates for programming with toplevel actors

Predicate: toplevel_spawn/1-2
actor
toplevel_spawn(-Pid) is det.
toplevel_spawn(-Pid, +Options) is det.

Spawns a toplevel actor and binds Pid to its pid. All options accepted by spawn/3 are also accepted by toplevel_spawn/2. URI fetching follows Source loading, as for spawn/3. In addition, toplevel_spawn/2 accepts the following options:

With a remote node/1, the caller requests a toplevel from the destination node. Source loading follows Source loading; requested session and lifecycle options are applied at the destination, subject to its owner ceilings. Answer targets, links and monitors retain their ordinary remote-creation semantics.

Both finite lifecycle limits must be positive numbers of seconds. A public client may request tighter values, but cannot weaken the node owner’s ceilings. These limits are distinct from the timeout on an ISOTOPE session HTTP request, which only bounds the wait for the next queued event and does not abort the goal or terminate the session.

Options follow the common validation rules; session/1 is boolean, names are atoms, and finite lifecycle limits are positive numbers. Source loading follows the source conventions.

Predicate: toplevel_call/2-3
actor
toplevel_call(+Pid, +Goal) is det.
toplevel_call(+Pid, +Goal, +Options) is det.

Asks the toplevel Pid for solutions to Goal. Valid options are:

Variables in Goal are not bound directly in the caller. Instead, the outcome is reported by one of the following answer terms, delivered as a message to the target mailbox:

A toplevel serves one controlling client at a time, and each call starts afresh: when it accepts Goal, it discards any toplevel_next/1-2, toplevel_stop/1 or input left over from an earlier query, that is, sent before the call; one sent after the call is kept. If Goal raises an exception after a finite limit has already collected some solutions, those solutions are delivered first as success(Pid, Data, true), and the error answers the following toplevel_next/1-2; toplevel_stop/1 discards it, and so does once(true).

Answers are plain terms. A solution that still carries constraints, such as those left by dif/2, freeze/2 or CLP(FD), cannot be represented in an answer, since printing it would drop the constraints. The toplevel then reports error(Pid, error(representation_error(constraints), _)) instead of the page, and the query ends. This holds whether the client is local or remote. A goal that needs such answers can bind the constrained variables, for example by labelling, or return the constraints as ordinary terms.

Returned solution templates must also be acyclic. A cyclic template ends the query with error(Pid, error(representation_error(cyclic_term), _)). The usual paging rules determine when an error following earlier solutions is delivered. The toplevel can accept a new call after the error. A goal may use cyclic terms internally if the template it returns is acyclic.

Predicate: toplevel_next/1-2
actor
toplevel_next(+Pid) is det.
toplevel_next(+Pid, +Options) is det.

Asks toplevel Pid for more solutions. Valid options:

Delivers the same answer messages as toplevel_call/2-3 to the target mailbox.

Predicates: toplevel_call_synch/3-4, toplevel_next_synch/2-3
actor
toplevel_call_synch(+Pid, +Goal, -Answer) is semidet.
toplevel_call_synch(+Pid, +Goal, -Answer, +Options) is semidet.
toplevel_next_synch(+Pid, -Answer) is semidet.
toplevel_next_synch(+Pid, -Answer, +Options) is semidet.

Send one command and collect its answer in the calling actor. Answers retain success(Pid,Data,More), failure(Pid) and error(Pid,Error); goal variables remain independent in the caller. Query errors are returned as answer terms rather than thrown by the wrapper. A private request reference prevents an old answer after a timeout from satisfying a later wait. Ordinary asynchronous answers and I/O are preserved. An asynchronous call or next uses ordinary answer messages.

The caller must be the answer target. An explicit target/1 must identify that same actor. Call options are template/1, offset/1, limit/1 and once/1; next accepts limit/1. Both accept receive options timeout/1 and on_timeout/1. Both wrappers also accept io_target(+Pid) for terminal I/O routing; this is independent of their answer target and subject to the node’s I/O policy. The wrappers accept actor pids and ordinary aliases, locally or remotely, under the same addressing and authorisation rules as other actor operations. Connection and correlation bookkeeping is internal. Timeout callbacks retain the caller’s execution context and shared variables without requiring qualification of the option list. Options follow Options and validation.

The default wait is unbounded. Without a callback, a receive timeout succeeds with Answer unbound. A timeout callback runs once in the caller’s context, retaining its bindings, failure and exceptions. Timeout does not stop the query; a stale correlated answer cannot satisfy a subsequent wait or extend its deadline. Observed termination throws toplevel_down(Reason). An answer is selected before output unification, so a mismatch consumes it and fails. The wait’s monitor is removed on every exit path, preserving unrelated monitors and messages.

An unknown registered name raises existence_error(actor_name, Name) before a request is sent. A remote peer must support correlated calls; otherwise the operation raises permission_error(use, toplevel_correlation, Node) before starting or advancing the query. Connection setup is outside the receive timeout.

These wrappers retain the toplevel’s single-client protocol. They provide neither concurrent-client coordination nor remote cancellation.

Predicate: toplevel_stop/1
actor
toplevel_stop(+Pid) is det.

Asks toplevel Pid to stop searching for more solutions.

Predicate: toplevel_abort/1
actor
toplevel_abort(+Pid) is det.

Tells the local toplevel Pid to abort the execution of the currently running goal. Abort runs supported cleanup, bypasses recovery in client catch/3, and returns a persistent session to PTCP state s1; it does not terminate a persistent toplevel actor. A toplevel spawned with session(false) terminates instead. An abort that arrives while the toplevel is idle in s1 leaves a persistent toplevel idle and ends a one-shot toplevel; one that arrives in s3 abandons the suspended solution sequence, as toplevel_stop/1 would. An abort that arrives after termination of the toplevel has been committed is ignored. Every other abort, including one in s1, is acknowledged: the toplevel sends abort(Pid) to its client (before any call, to its spawn target), after any answers of the aborted query. An unknown or non-local pid has no effect.

Predicate: toplevel_halt/1-2
actor
toplevel_halt(+Pid) is det.
toplevel_halt(+Pid, -Reply) is det.

Terminates toplevel actor Pid from any protocol state. The one-argument form requests termination through the actor runtime and returns without waiting for confirmation. The two-argument form installs a private monitor, requests termination, and waits for its notification. An observed termination yields Reply = true, regardless of its reason. The special reason no_process also yields true: the target is confirmed absent, without establishing when or why it terminated. For a remote target, connection_closed instead yields Reply = error(connection_closed): observation was lost and termination is unconfirmed. Halt is an untrappable termination signal, not the interruption signal used by abort.

Note: The private monitor used by toplevel_halt/2 is distinct from any existing monitor. If the toplevel was spawned with monitor(true), the caller still receives its original down(Pid, Pid, true) notification.

Predicates for programming with server actors

Predicate: server_spawn/3-4
actor
server_spawn(+Pred, +State, -Pid) is det.
server_spawn(+Pred, +State, -Pid, +Options) is det.

Spawns a generic server actor using callback predicate Pred/4 and initial state State. The callback receives (Request, OldState, Response, NewState). All options are forwarded to spawn/3 except:

Options follow the common validation rules and source conventions. The explicit State argument supplies the initial state; internal compatibility metadata is not a public option.

Predicate: server_request/3-4
actor
server_request(+To, +Request, -Response) is det.
server_request(+To, +Request, -Response, +Options) is det.

Makes a synchronous request-response call to the server To, where To may be a pid or a registered local name. server_request/4 accepts the options of receive/2, for example timeout(+Seconds). Monitoring is installed automatically. If the server terminates before replying, the call promptly throws server_down(Reason).

Predicate: server_promise/3-4
actor
server_promise(+To, +Request, -Ref) is det.
server_promise(+To, +Request, -Ref, -MonRef) is det.

Sends Request to the server To and returns a correlation reference Ref. The reply must later be collected with server_yield/2-4.

The four-argument variant additionally installs a monitor and returns its reference in MonRef. If subsequent setup or sending fails or throws, that monitor and its pending notifications are removed, preserving the original outcome. A successful send retains the monitor for server_yield/4.

Predicate: server_yield/2-4
actor
server_yield(+Ref, -Response) is det.
server_yield(+Ref, -Response, +Options) is det.
server_yield(+Ref, +MonRef, -Response, +Options) is det.

Waits for the response matching Ref. The reply is selected before unifying Response; a conflicting output consumes that reply and fails. Replies with other references remain available. The three-argument variant accepts the options of receive/2, preserving timeout callback bindings, failure, exceptions and alternatives.

The four-argument variant uses MonRef to detect server termination and throws server_down(Reason) if the server dies before replying. When the wait finishes, fails, or throws, it removes the monitor and flushes pending notifications for that reference. This includes timeout paths. Alternatives supplied by on_timeout/1 remain available; cleanup occurs when the call finishes, exhausts its alternatives, or is cut.

Cleanup also covers interruption and an output mismatch. Only MonRef and its notifications are removed; unrelated monitors and messages remain available. Removing a remote monitor is best effort. Timeout or cleanup does not cancel the server request or discard a later reply.

Predicate: server_upgrade/2-3
actor
server_upgrade(+To, +Pred) is det.
server_upgrade(+To, +Pred, +Options) is det.

Replaces the callback predicate of the running server To without disturbing its current state. Pred must denote a callback predicate of arity four.

The two-argument form transfers no code and therefore requires the callback to be already available to the server process. The three-argument form accepts the following source-loading options:

Options are validated and source is prepared by the caller before sending the upgrade request. Sources are loaded in option-list order, following Source loading. The operation replies only after the callback has been loaded and validated. It preserves the current state value and performs no state migration. If installation fails, server_upgrade/2-3 rethrows the reported error and the state is unchanged. Source changes made in the server’s private database before the error are not rolled back.

Predicate: server_halt/2
actor
server_halt(+To, -Reply) is det.

Asks the server To to stop gracefully and binds Reply to its acknowledgement. The request carries a fresh correlation reference, so an unrelated acknowledgement in the caller’s mailbox cannot satisfy the operation. A private monitor is installed before the request; if the server terminates without acknowledging it, the operation throws server_down(Reason).

Predicates for programming with statechart actors

Predicate: statechart_spawn/2
actor
statechart_spawn(-Pid, +Options) is det.

Spawns a statechart actor and binds Pid to its pid.

statechart_spawn/2 requires exactly one initial XML source option:

In addition, statechart_spawn/2 accepts:

All remaining options are passed through to spawn/3.

src_list/1 and src_predicates/1 are accepted as supplemental Prolog sources loaded into the statechart actor’s private module. They do not count as the required XML source. The SXML document notation is specified in Appendix C of the book.

Options follow the common validation rules in Options and validation. Exactly one initial XML source is required: neither an absent source nor multiple XML source options are accepted. Supplemental Prolog source options are additive and processed in option-list order. Source preparation, including the initial XML fetch, follows Source loading.

Statecharts support hierarchical and parallel states, shallow/deep history, guarded actions, internal/completion events, timed transitions and deferred events. Deferred events are re-offered from a snapshot when the net active configuration changes. A self-transition that leaves the final active configuration unchanged does not trigger re-offering merely because states were exited and re-entered. Supplemental Prolog source precedes the embedded XML datamodel. Mutable datamodel facts are private to the chart; empty declared predicates fail normally when called.

Child invocation supports actors, toplevels, servers, supervisors and nested charts, locally or on compatible remote nodes. Server invocation uses callback/1 and state/1; supervisor invocation uses children/1. Child entry predicates and explicit copied sources resolve in the parent chart at invocation time; inline source is private to the child. Source loading and destination checks follow the source conventions. Invocation settles immediate transitions and internal events before emitting the internal event spawned(Pid). Nested supervisor child starts may name remote destinations under the same rules as direct child creation.

State exit requests termination of invoked children, including detached children, without waiting for completed shutdown. Results and termination use ordinary messages and optional monitors. Child termination does not by itself synthesise a done(State) event; statechart completion events follow the chart’s own final-state rules. The trace/1 setting is fixed at creation. Embedded datamodel directives obey the same admitted-language and sandbox rules as other supplied source. Actor identifiers and engine placement follow ordinary creation rules for every chart.

Validation and caller-side source preparation errors are reported before successful creation. All source must be loaded before chart execution begins; a loading failure prevents the chart from starting. Embedded action checks occur during execution, and later execution failures are observed through ordinary down/3 notifications when monitoring is enabled.

Predicate: statechart_halt/2-3
actor
statechart_halt(+Pid, -Reply) is det.
statechart_halt(+Pid, -Reply, +Timeout) is det.

Asks the statechart actor Pid to halt gracefully, running the exit actions of its active states, and waits for an acknowledgement in Reply. The two-argument form waits indefinitely.

The three-argument form waits at most Timeout seconds. If the actor does not reply in time, it is killed and Reply becomes killed.

Predicate: raise/1
statechart builtin
raise(+Event) is det.

Enqueues Event on the internal event queue of the current statechart interpreter. It is handled after the current block of executable content and before a new external message.
Important: raise/1 is only meaningful inside executable statechart content such as <onentry>, <onexit>, and <go>.

Predicate: in/1
statechart builtin
in(+Id) is semidet.

Succeeds if the state identified by Id belongs to the current active configuration of the statechart interpreter.

Important: in/1 is only meaningful inside statechart guards or executable statechart content such as <onentry>, <onexit>, and <go>.

Predicates for programming with supervisor actors

Predicate: supervisor_spawn/2-3
actor
supervisor_spawn(+ChildSpecs, -Pid) is det.
supervisor_spawn(+ChildSpecs, -Pid, +Options) is det.

Spawns a supervisor actor and starts its children. Supported options are:

Other options are passed through to spawn/3.

Child specifications take the form child(Id, ChildOptions). Child options are:

Creation and child options follow the common validation rules. intensity/1 is a nonnegative integer; period/1 is a positive number, including fractional seconds. The complete initial child list, including recognised nested server and supervisor starts, is validated before creation. Specifications are acyclic, sibling ids are unique, and start/1 is required. Missing starts raise existence_error(option, start(Id)); duplicate initial ids raise permission_error(duplicate,supervisor_child_id,Id). Validation checks callable starts and callbacks without executing them. Child ids are atoms in all supervisor operations. An uninstantiated id raises instantiation_error; a non-atom raises type_error(atom, Id). Nested specifications need only be instantiated when the creation predicate is called. Admission checks must allow them to be constructed by preceding goals in the submitted query; validation still completes before any child is created.

Child-specification options are start/1, restart/1, shutdown/1 and type/1. Spawn settings belong in the child start goal or the nested server/supervisor options, rather than in ChildOptions. Internal compatibility metadata is not a public option. Shared variables and the original restart specifications are retained.

A permanent child restarts after any termination, a transient child after failure or abnormal termination but not success (true), and a temporary child never restarts. one_for_one replaces the affected child; one_for_all restarts the whole group; rest_for_one restarts that child and later siblings. Replacements retain child order, dynamic additions append, successfully completed transient children retain an inactive specification, and temporary children are removed.

Startup rollback: Failed initial startup reclaims that attempt’s provisional children in reverse start order using their shutdown policies. A failed dynamic addition reclaims only its own provisional child and leaves existing siblings and supervisor state unchanged, allowing retry. These paths preserve unrelated monitors and messages, and cleanup errors do not replace the primary startup failure or prevent other cleanup attempts. An infinity shutdown policy may delay completion indefinitely. Startup here means creation, preparation and admission; a child terminating after successful creation follows its restart policy.

An ordinary initial startup failure has reason init_failed; an initial exception retains its original error term. Dynamic additions and explicit respawn return error(start_failed) for ordinary failure or error(Error) for an exception, leaving the supervisor available. Reserved runtime control transfers still propagate.

Restart failure: A failed explicit respawn rolls back only that attempt, retaining existing siblings and the inactive specification for retry. If an automatic replacement fails, provisional replacements are reclaimed, remaining children are stopped in reverse start order using their shutdown policies, and the supervisor exits with restart_failed(Id,Reason). Id identifies the replacement that failed; Reason is start_failed or its original exception. These paths preserve unrelated actors, monitors and messages; cleanup errors do not replace the primary failure or prevent other cleanup attempts.

Restart-intensity exhaustion: The restart budget is checked before replacement startup. Exhaustion starts no excess replacement, stops remaining recorded children in reverse start order using their shutdown policies, and exits with shutdown. An intensity(0) budget permits no automatic restarts. Cleanup preserves unrelated monitors and messages; ordinary cleanup errors do not replace the shutdown reason or prevent attempts to stop other children.

Startup completion: Creation returns successfully only after all initial child starts have completed creation, preparation and admission. This does not require their application goals to finish or establish application readiness. A failed initial start rolls back the provisional children and raises error(supervisor_start_failed(Pid, Reason), Context), where Reason is init_failed or the original exception. Failed named creation releases its reservation. Child application goals may run during supervisor setup, so rollback cannot undo their external effects.

Child shutdown policies govern explicit termination, normal halt, rollback and group-restart stopping. brutal_kill stops immediately with reason kill. A recognised server start receives a graceful stop request and is forced down with reason shutdown if its numeric timeout expires. Zero and fractional timeouts are supported. Plain actors and nested supervisors receive direct termination with reason shutdown; recursive cooperative shutdown is not guaranteed. A stop acknowledgement alone does not establish completed termination.

These guarantees require the runtime to execute its cleanup paths. Hard termination can bypass Prolog cleanup; losing a remote connection does not prove remote death, and an unacknowledged remote start can have an unknown outcome. No general guarantee is made here for cleanup after arbitrary supervisor exits. Synchronous request waits and their errors are described below.

Predicate: supervisor_spawn_child/3
actor
supervisor_spawn_child(+Pid, +ChildSpec, -Reply) is det.

Dynamically adds and starts one child. On success, Reply is ok. If a child with the same Id is already present, it is error(already_present). If startup fails, it is error(start_failed).

The child specification is validated before sending. A startup exception returns error(Error); failed setup rolls back only that addition and leaves existing children and state intact. A failed id remains available for retry. The supervisor also validates directly received additions before changing its state. See supervisor_spawn/2-3 for rollback qualifications.

Predicate: supervisor_terminate_child/3
actor
supervisor_terminate_child(+Pid, +Id, -Reply) is det.

Stops child Id but keeps its specification. Reply is ok or error(not_found).

The stopped specification retains its position with pid undefined; terminating an already stopped child returns ok. The supervisor applies its shutdown policy and waits for termination before replying.

Predicate: supervisor_delete_child/3
actor
supervisor_delete_child(+Pid, +Id, -Reply) is det.

Removes a non-running child specification. Reply is ok, error(running), or error(not_found).

Predicate: supervisor_respawn_child/3
actor
supervisor_respawn_child(+Pid, +Id, -Reply) is det.

Restarts a previously terminated child from its stored specification. Reply is either ok(NewPid), error(running), error(not_found), or error(start_failed).

A startup exception returns error(Error); a failed replacement retains the inactive specification. Success is ok(NewPid). A replacement retains the record’s original position in child order.

Predicate: supervisor_which_children/2
actor
supervisor_which_children(+Pid, -Children) is det.

Returns a list in child start order, with one entry per retained specification:

info(Id, Pid, Type, Restart)

Here Pid is undefined for a retained stopped child. The list reflects processed supervisor state rather than an independent instantaneous liveness check.

Predicate: supervisor_count_children/2
actor
supervisor_count_children(+Pid, -Counts) is det.

Returns:

[specs-Specs, active-Active,
 supervisors-Supervisors, workers-Workers]

Each value is a nonnegative integer count for its key. specs counts retained specifications, active counts records whose pid is not undefined, and supervisors and workers count active children of each type. Counts reflect processed supervisor state.

Predicate: supervisor_halt/1
actor
supervisor_halt(+Pid) is det.

Stops the supervisor and shuts down children in reverse start order.

The supervisor acknowledges only after its recorded children have completed shutdown under their policies. The acknowledgement precedes its own normal termination; a separate monitor observes that termination. A caller timeout can occur while shutdown continues and does not cancel it.

The request uses the ten-second deadline described below. A matching acknowledgement takes precedence over a termination notification already queued for the wait. If normal termination is observed before the acknowledgement arrives, the caller continues waiting within the same deadline. Expiry after observed normal termination raises supervisor_down(true); other expiry raises supervisor_call_timeout(Sup, stop). Abnormal termination without a matching acknowledgement raises supervisor_down(Reason).

Synchronous supervisor calls

Child management, inspection and halt use monitored synchronous requests with a ten-second reply deadline starting after sending. Connection setup is outside that deadline. Timeout does not cancel the operation or consume a later reply. Termination or expiry may raise:

Supervisor request waits select the matching reply before unifying outputs; a mismatch consumes it and fails. The waits remove only their private wait monitor on success, failure, exception or interruption, and flush its pending termination notifications, preserving unrelated monitors and messages. This includes an exception while sending the request. Cleanup does not cancel the operation or discard a later reply. The halt wait has its own acknowledgement-ordering rules above.

Prolog-style generics

Predicate: parallel/1
actor
parallel(+Goals) is semidet.

Runs the proper list of independent goals Goals concurrently, using one monitored worker actor per goal. The call succeeds when every goal has produced its first solution and returns the resulting variable bindings. parallel([]) succeeds immediately. Further solutions are not enumerated on backtracking.

The predicates parallel/1 and first_solution/2-3 can be called directly in an ACTOR toplevel, with or without supplied source. Worker goals may use predicates supplied in the caller’s source.

If any goal fails, the remaining workers are terminated and the call fails. If any goal throws an exception, the remaining workers are terminated and the exception is rethrown. If a worker terminates without a result for any other reason, including true, the remaining workers are terminated and worker_exit(Pid,Reason) is thrown. Once a worker’s result has been accepted, its termination notification only confirms that it has stopped. If several workers have abnormal outcomes, the first failure or error notification observed by parallel/1 determines the result; this selection may depend on scheduling and does not promise leftmost-goal precedence. Result and monitor messages belonging to the workers are removed before the predicate returns, fails, or throws.

Worker cleanup covers partial startup failure, exceptions, caller interruption and abandonment of the call. Only the combinator’s workers and their result/monitor messages are reclaimed; unrelated actors, monitors and messages are preserved. This is local cleanup and does not cancel remote computations already requested by a worker. A shell abort closes that shell’s combinator scopes; ordinary actors outside those scopes follow their own lifetime rules. Forced termination that bypasses runtime cleanup remains a limitation.

The goals must not depend on bindings or side effects produced by sibling goals. Actor creation and message copying add overhead, and the one-worker-per-goal model gives large goal lists a correspondingly large resource footprint.

A non-list Goals raises type_error(list, Goals). An element that is not callable raises the corresponding callable type error from its worker, which is propagated to the caller.

Predicate: first_solution/2-3
actor
first_solution(?Solution, +Goals) is semidet.
first_solution(?Solution, +Goals, +Options) is semidet.

Runs the proper list of alternative goals Goals concurrently in monitored worker actors and unifies Solution with the result produced by the first solver to succeed. Once a winner has been selected, all remaining workers are terminated and their result and monitor messages are removed. The predicate does not enumerate later solutions on backtracking, and an empty goal list fails.

The two-argument form continues after an individual solver fails and stops on the first error. An exception retains its original term. Any other exit without a result, apart from ordinary failure, is reported as worker_exit(Pid,Reason), including an exit with reason true. These exits use the existing on_error policy. The three-argument form accepts:

If all alternatives are removed under a continue policy, the predicate fails. Goals should not depend on side effects produced by sibling solvers.

Options follow Options and validation and are validated before worker creation. An uninstantiated required list or policy value raises instantiation_error. A non-list Goals or Options raises type_error(list,Term). Policy values must be atoms: a non-atom raises type_error(atom,Action), and an atom other than stop or continue raises domain_error(first_solution_policy,Action). An unknown or incorrectly aritied option raises domain_error(first_solution_option,Option). Every occurrence is checked and the first setting for each policy takes precedence.

The parallel/1 worker-cleanup and unexpected-exit rules also apply here. on_error/1 governs unexplained worker exits as well as exceptions. A winner is selected before output unification; even if the caller’s output does not match, remaining workers are cleaned up before the call fails.

Predicates for remote Prolog-style calls

Predicate: rpc/2-3
isobase
rpc(+URI, +Goal) is nondet.
rpc(+URI, +Goal, +Options) is nondet.

Executes a copy of Goal through the stateless /call endpoint of the node identified by URI, then unifies the local goal with each returned solution on backtracking. This remains a stateless call even when the destination is an ACTOR node: actor-only predicates such as self/1, spawn/1-3, and receive/1-2 are not available through rpc/2-3.

A stateless goal can itself call rpc/2-3 or create and collect a promise. The same profile, sandbox and client-context rules apply. A promise reference can be used across requests only if those requests retain the same client context at the creating node.

The first argument alone selects the execution node. localhost means the node on which rpc/2-3 is running. Source-loading options supply source for the call’s temporary private database. For example:

rpc('http://n2.org', Goal, [
   src_uri('http://n3.org')
])

executes Goal on n2.org. The caller fetches the source from n3.org and sends its text to n2.org, following Source loading. The options are:

The following HTTP transport options are also accepted. They affect the client’s requests to the execution node, including later slice requests; they do not configure source fetching or remote goal execution:

Header values and credential arguments accept atoms, strings and proper lists of one-character atoms. Textual field values use UTF-8 on the wire. Basic credentials are encoded as UTF-8 before Base64 encoding. Header-name comparison also applies across option forms: authorization/1 supplies the Authorization field and user_agent/1 supplies User-Agent, so the first applicable option in list order wins.

Malformed header pairs raise type_error(http_request_header, Value); unsupported credential forms raise domain_error(http_authorization, Value). Text values of the wrong type raise type_error(atom_or_string, Value). Invalid field-name or field-value characters raise domain errors with domains http_header_name or http_header_value, respectively. An uninstantiated required component raises an instantiation error.

Only the documented transport options are accepted. Caller access policy, including browser restrictions on request fields and CORS, still applies. Request fields do not grant authority to assert trusted proxy identity; reserved identity fields raise permission_error(set, proxy_header, Name). An operator-bound credential may also prevent a caller from supplying a conflicting Authorization field.

Options follow the common validation rules in Options and validation. limit/1 is a positive integer; once/1 is boolean. Source options follow Source loading. template/1 and offset/1 belong to promise/4 and are rejected by rpc/3.

For rpc/3, every answer in the first slice remains available on backtracking; once(true) prevents subsequent page requests even if the peer reports more answers. The client forwards the setting to the destination, which finishes the computation after that slice and retains no continuation. This does not provide remote cancellation.

timeout/1 requests a destination-side execution timeout; http_timeout/1 sets the caller’s transport timeout. Both require numbers of seconds; negative values are normalised to zero. Omission leaves the corresponding default in effect. These are separate settings, each using its first occurrence, and every occurrence is validated before source preparation or dispatch.

The HTTP timeout bounds each complete request, including response headers and body, and starts afresh for each later slice. It does not bound caller-side source preparation, which follows Source loading. Exhaustion raises error(rpc_error(http_timeout),_) in rpc/3. A promise delivers the local exception as error(error(rpc_error(http_timeout),_)) through yield/2-3. This does not establish that the destination’s computation has stopped.

Predicate: promise/3-4
isobase
promise(+URI, +Goal, -Ref) is det.
promise(+URI, +Goal, -Ref, +Options) is det.

Starts one asynchronous stateless call to node URI with Goal and returns a local promise reference in Ref. As with rpc/2-3, the first argument selects the execution node and localhost denotes the current node. Source-loading options populate the promised call’s temporary private database; they do not change its execution node. The caller completes source preparation, including any src_uri/1 fetch, before returning Ref; errors at this stage are raised by promise/3-4 itself. The remote query runs asynchronously. It accepts the same limit/1, once/1, timeout/1, http_timeout/1, and src_*/1 options as rpc/3, together with:

The reference returned in Ref can later be used by yield/2-3 to collect the single answer term. Programs must not infer meaning from its digits or construct references themselves.

A promise always collects one slice. With once(true), it additionally asks the destination to finish the computation after that slice rather than retain a continuation; omission defaults to false. The complete peer answer, including its More flag, is returned unchanged. A local yield timeout does not change this setting or consume the promise.

Options use the same validation rules and HTTP transport options as rpc/3, plus arbitrary template/1 and nonnegative integer offset/1. Template variables remain shared with the goal, and the caller’s variables are not bound by remote execution. Collection, explicit disposal and five-minute expiry reclaim local promise resources; pending and ready but uncollected promises can expire. Late completion cannot recreate a disposed reference.

A promise is local to its creating node and belongs to the client context in which it was created. Its reference identifies it within that node and context independently of engine placement. Code running at that node on behalf of the same context may collect or dispose of it; code in another context cannot. Passing a reference to a remote node does not create a distributed promise or confer access to the originating node’s promise. Authentication alone does not grant access to another context’s promises. A client collecting across requests must retain its context explicitly. Ownership transfer is unsupported.

For example, suppose a client at node A creates a promise there and spawns a child at node B. A descendant of that child returning to A may collect the promise while the original context remains open. A separate client at A, even one using the same authentication credentials, cannot collect it. The reference alone grants neither access at A nor collection at B.

Closing the context disposes of all its pending and uncollected promises. This does not itself terminate surviving actors or cancel remote execution. Moving work between engines at the same node within a context must preserve reference identity and access rules. Numeric references must not be reused while an earlier reference could still designate a promise in that context.

Predicate: yield/2-3
isobase
yield(+Ref, -Answer) is det.
yield(+Ref, -Answer, +Options) is det.

Waits for the answer term from a previous call to promise/3-4. The reference is local to its creating node and client context. The contract is one collection of one answer term; backtracking does not enumerate further results. Timeout handling must return a defined answer term or throw an exception. Remote answers are success(Data,More), failure, or error(Error). If on_timeout/1 is omitted, the timeout path succeeds with Answer = timeout. A timeout callback may supply its own defined result. This wait outcome is distinct from remote logical failure or an error answer. yield/2 is equivalent to yield/3 with an empty option list. Valid options are:

Options follow the common validation rules in Options and validation. timeout/1 requires a number and on_timeout/1 requires a callable goal. Callback context and sharing with Answer are preserved. A local producer failure is delivered as an error answer rather than leaving the collector blocked.

Only one collector may wait on a reference at a time; a competing yield raises permission_error(collect,promise,Ref). Timeout, cooperative interruption or an exception before collection commits releases the collector and retains the promise. Collection consumes the selected answer before output unification; a mismatch therefore fails without making the answer available again. Disposal or expiry wakes a waiting collector with existence_error(promise,Ref), without invoking its timeout callback. Access from another ownership scope is treated as a missing reference.

Completing one request or ending one toplevel within a retained client context does not dispose of that context’s promises. Closing the context wakes collectors with a missing-reference error and closes further admission, while surviving actors remain alive. A collection that commits first returns its answer; disposal that wins invalidates the reference. Timeout and retry remain possible only while the reference and its owner remain valid. Ownership transfer and guaranteed remote cancellation remain separate work in Appendix F of the book.

Predicate: promise_cleanup/1
isobase
promise_cleanup(+Ref) is det.

Disposes of the caller-accessible promise and its local resources. Ref must be an integer. Cleanup is idempotent for missing, consumed, expired, disposed or inaccessible references; a later yield raises existence_error(promise,Ref). The ownership boundaries under promise/3-4 apply. Disposing of local resources does not guarantee cancellation of execution on the remote node.

Predicate: runtime_property/1
isobase
runtime_property(?Property) is nondet.

Enumerates capabilities of the execution environment. These properties describe available facilities and lifetime constraints without changing the language contract. Defined properties are:

Boolean property values are true or false. persistent/1 reports whether the environment can outlive the client page or interactive connection; inbound_addressable/1 reports whether it accepts incoming node connections; dom/1 reports access to the page DOM. actor_isolation/1 distinguishes independently scheduled actors from actors sharing a cooperative execution engine. hard_termination/1 reports whether an actor can be stopped without its cooperation. Hard termination does not guarantee execution of Prolog cleanup handlers. Source access may additionally be restricted by origin, CORS, file-access or other deployment policies.

An unbound argument enumerates the properties; unsupported properties and non-matching values fail. Implementation identity and host-engine details belong in diagnostic tools and deployment guides.

Common error contract

Predicate entries above state specialised errors where they matter. Standard Prolog exceptions have the form error(Formal,Context). The formal term identifies the condition. The context is implementation-defined. Portable handlers match the formal term and leave the context open, for example error(type_error(integer,Culprit),_). Registration conflicts use permission_error/3; missing required child start options use existence_error(option,start(Id)), retaining the child id in the portable formal term. These runtime failures are wrapped in error/2. An explicit throw(Term) can raise an application exception with any portable term shape, including an error/2 term with its own context. The common formal terms have the following roles:

FormMeaning
instantiation_errorA required input was insufficiently instantiated.
type_error/2The value has the wrong Prolog type; arguments identify the expected type and culprit.
domain_error/2The type is acceptable but the value is outside the operation’s domain.
existence_error/2A required process, procedure, source, or other object does not exist.
permission_error/3The operation is defined but not authorised in this execution context.
evaluation_error/1An arithmetic operation raised an exception, for example division by zero.
resource_error/1The runtime cannot supply a required bounded resource.
resource_error(time)A configured execution limit expired.

A direct predicate call throws the exception term. PTCP reports a submitted-goal error as error(Pid,E); stateless calls use error(E); HTTP and WebSocket bindings place its public representation in a type:"error" envelope. An uncaught actor exception is observed by a monitor as down(Pid,Ref,exception(E)). Boundary sanitisation may remove host-private context but must preserve the portable formal error in Prolog-format responses and node-to-node term fields. JSON diagnostic text may differ across nodes. The demonstrator displays concise prose by default. Enable Show exception terms under Settings → Terminal to display the Prolog exception with its context omitted, when the response supplies one. For programmatic classification use the Prolog term or a documented protocol code. Appendix D of the book specifies these representations and the available machine-readable error codes.

If admission rejects a submitted goal before execution starts, the submission interface reports the error. A catch/3 inside the goal can handle exceptions raised during its execution.

ISO predicates and related constructs

Web Prolog supports the following ISO predicates and related constructs, including the extensions listed here. Directives and DCG rules are source-level items, and read/1 and the write predicates are provided through the session I/O layer rather than ambient ISO stream I/O.

Control and meta-call

!/0, (,)/2, (;)/2, (->)/2, (\+)/1, call/1-8, catch/3, fail/0, false/0, once/1, repeat/0, throw/1, true/0

Directives and DCGs

-->/2, discontiguous/1, dynamic/1, multifile/1, op/3, phrase/2-3

Operator declarations are subject to the node’s admitted language; a restricted profile may omit op/3. An empty dynamic/1 or discontiguous/1 declaration establishes an existing predicate: calls fail normally rather than raising an undefined-procedure error. Copied source retains these declarations. The admitted declaration set is determined by the node’s profile and explicit source policy, rather than by the host Prolog system. Admitted multifile/1 declarations concern only the receiving actor’s private database and confer no access to another actor’s predicates. Embedded statechart datamodels obey the same policy. Arbitrary goal-executing directives require explicit admission; checked declarations do not grant execution authority. A directive that fails, or that the engine does not carry out, raises directive_failed(Directive) at creation; see Source loading.

Term relations, comparison, and construction

(=)/2, (=..)/2, (==)/2, (@<)/2, (@=<)/2, (@>)/2, (@>=)/2, (\=)/2, (\==)/2, arg/3, compare/3, copy_term/2, functor/3, subsumes_term/2, term_variables/2, unify_with_occurs_check/2

Arithmetic predicates

(<)/2, (=:=)/2, (=<)/2, (=\=)/2, (>)/2, (>=)/2, is/2

Arithmetic evaluable functors

The arithmetic evaluable functors specified by ISO/IEC 13211-1 are supported in arithmetic expressions.

Type testing

acyclic_term/1, atom/1, atomic/1, callable/1, compound/1, float/1, ground/1, integer/1, nonvar/1, number/1, var/1

Database and all-solutions

abolish/1, assert/1, asserta/1, assertz/1, bagof/3, clause/2, findall/3, keysort/2, retract/1, retractall/1, setof/3, sort/2

Atomic term processing

atom_chars/2, atom_codes/2, atom_concat/3, atom_length/2, char_code/2, number_chars/2, number_codes/2, sub_atom/5

Session I/O

display/1, format/1-2, nl/0, print/1, read/1, time/1, write/1, write_canonical/1, write_term/2, writeln/1, writeq/1

read/1 uses the session prompt protocol. time/1 reports timing through the output channel and checks its goal under the active profile and sandbox. write/1 and writeln/1 display a list of characters as a list term, including the empty list. For text presentation, format('~s', [[a,b,c]]) displays abc.

The goal-executing ~@ format directive, including forms with numeric arguments or a colon modifier, is rejected with permission_error(use, format_specifier, '~@'). An escaped tilde in ~~@ produces literal text.

Standard library and utility predicates

Nodes that accept general Prolog goals supply these library predicates without explicit loading, as described in Chapter 2 of the book:

List relations and indexing:

member/2, memberchk/2, append/3, length/2, select/3, nth0/3-4, nth1/3-4.

Integer relations:

between/3, succ/2.

Iteration and solution processing:

maplist/2-8, foldl/4-6, call_nth/2, countall/2, forall/2.

Library callbacks are checked when invoked: an uninstantiated callback raises instantiation_error; a non-callable value raises type_error(callable,Value) with the original value as culprit. An empty maplist or foldl, and a vacuous forall test, do not invoke their unused callbacks. Exceptions from callbacks propagate unchanged. These rules do not alter the ISO call/N error contract.
For background and further examples, see Ulrich Neumerkel’s A Prologue for Prolog, a working draft for common library predicates.1 The entries here specify the Web Prolog contract. A + argument must be instantiated; a ? argument may be uninstantiated. The descriptions state which combinations are supported. A semidet call has at most one answer; a nondet call may have several, depending on its arguments. Callback arguments appended by maplist and foldl follow any arguments already present in the closure. Callbacks execute in the caller’s source context and retain their ordinary failure, backtracking and exception behaviour.

Predicate: member/2
isobase
member(?Element, ?List) is nondet.

Unifies Element with successive elements of List, from left to right. Backtracking visits each position, including positions containing equal elements. With an uninstantiated list, it generates lists containing the element at successively later positions.

?- findall(X, member(X, [a,b,a]), Xs).
Xs = [a,b,a].
Predicate: memberchk/2
isobase
memberchk(?Element, ?List) is semidet.

Searches from the start of the list and commits to the first element that unifies with Element. That unification may bind variables. Backtracking does not try another position. A successful match does not require inspection of the remaining tail; use member/2 to enumerate matches.

?- memberchk(X, [a,b,a]).
X = a.
Predicate: append/3
isobase
append(?Prefix, ?Suffix, ?Whole) is nondet.

Relates a list prefix, its following suffix and their concatenation. It joins two supplied lists, removes a supplied prefix from a list, or splits a supplied list at successive positions on backtracking, starting with an empty prefix. The order within both parts is preserved.

?- findall(P-S, append(P, S, [a,b]), Splits).
Splits = [[]-[a,b], [a]-[b], [a,b]-[]].
Predicate: length/2
isobase
length(?List, ?Length) is nondet.

Relates a proper list to its non-negative integer length. It counts a supplied list or constructs a list of a supplied length, filling unknown positions with distinct fresh variables. With a partial list and an uninstantiated length, it enumerates proper completions in increasing length. In particular, two fresh arguments enumerate lengths zero, one, two and so on.

?- length([a|Tail], 3).
Tail = [_A,_B].
Predicate: select/3
isobase
select(?Element, ?List, ?Rest) is nondet.

Removes one occurrence unifying with Element, leaving Rest in its original order. Backtracking tries successive positions. It can also insert an element into a supplied remainder at successive positions. Equal elements at different positions remain distinct choices.

?- findall(R, select(a, [a,b,a], R), Rs).
Rs = [[b,a], [a,b]].
Predicates: nth0/3-4, nth1/3-4
isobase
nth0(?Index, ?List, ?Element) is nondet.
nth1(?Index, ?List, ?Element) is nondet.
nth0(?Index, ?List, ?Element, ?Rest) is nondet.
nth1(?Index, ?List, ?Element, ?Rest) is nondet.

Relates an element to its position in a list, counting from zero for nth0 and from one for nth1. An uninstantiated index enumerates positions in ascending order. The four-argument forms additionally relate Rest to the list with that occurrence removed. They also construct a list by inserting Element into a supplied remainder. An index beyond the end of a supplied finite list fails.

?- nth0(1, [a,b,c], E, Rest).
E = b, Rest = [a,c].
?- nth1(2, List, b, [a,c]).
List = [a,b,c].
Predicate: between/3
isobase
between(+Lower, +Upper, ?Integer) is nondet.

The bounds are integers. With an uninstantiated third argument, enumerates every integer from Lower through Upper, in ascending order and including both bounds. With a supplied integer, tests membership in that interval. An interval whose lower bound exceeds its upper bound has no solutions.

?- findall(N, between(-1, 2, N), Ns).
Ns = [-1,0,1,2].
Predicate: succ/2
isobase
succ(?Predecessor, ?Successor) is semidet.

Relates non-negative integers differing by one. At least one argument must be supplied. It computes a successor from its predecessor, computes the predecessor of a positive successor, or checks a supplied pair. Zero has no non-negative predecessor.

?- succ(4, S).
S = 5.
?- succ(P, 4).
P = 3.
Predicate: maplist/2-8
isobase
maplist(?Closure, ?L1) is nondet.
maplist(?Closure, ?L1, ?L2) is nondet.
maplist(?Closure, ?L1, ?L2, ?L3) is nondet.
maplist(?Closure, ?L1, ?L2, ?L3, ?L4) is nondet.
maplist(?Closure, ?L1, ?L2, ?L3, ?L4, ?L5) is nondet.
maplist(?Closure, ?L1, ?L2, ?L3, ?L4, ?L5, ?L6) is nondet.
maplist(?Closure, ?L1, ?L2, ?L3, ?L4, ?L5, ?L6, ?L7) is nondet.

Traverses one to seven lists together, from left to right. For each position, appends the corresponding elements to Closure’s existing arguments and calls the resulting goal, in list-argument order. The lists have the same length in every successful answer. Variables in any list may be bound by the callback, whose alternatives remain available on backtracking. Empty lists succeed without invoking the closure.

?- maplist(=, Xs, [same,same]).
Xs = [same,same].
?- maplist(=(same), [A,B]).
A = same, B = same.
Predicate: foldl/4-6
isobase
foldl(?Closure, ?L1, ?State0, ?State) is nondet.
foldl(?Closure, ?L1, ?L2, ?State0, ?State) is nondet.
foldl(?Closure, ?L1, ?L2, ?L3, ?State0, ?State) is nondet.

Traverses one to three lists from left to right, threading an accumulator. At each position, the callback receives the corresponding list elements in list-argument order, followed by the incoming and outgoing accumulators. Thus the one-list form calls call(Closure,Element,S0,S1); the next position receives S1 as its incoming accumulator. The last outgoing accumulator unifies with State. All lists have the same length in a successful answer. Callback alternatives are preserved. Empty lists unify State0 with State without invoking the closure. For example, with this callback:

add_to_sum(X, S0, S) :- S is S0+X.

?- foldl(add_to_sum, [2,3,4], 0, Sum).
Sum = 9.
Predicate: call_nth/2
isobase
call_nth(+Goal, ?Nth) is nondet.

Executes Goal and numbers its successive answers from one, including equal answers reached by different alternatives. With an uninstantiated Nth, returns the goal’s bindings together with each answer number. A supplied positive integer selects that answer only; it does not enumerate later answers on backtracking. Selection past the final answer fails. A non-integer Nth raises type_error(integer,Nth); zero or a negative integer raises domain_error(not_less_than_one,Nth).

?- findall(X-N, call_nth(member(X, [a,b,a]), N), Pairs).
Pairs = [a-1,b-2,a-3].
?- call_nth(member(X, [a,b,a]), 2).
X = b.
Predicate: countall/2
isobase
countall(+Goal, ?Count) is semidet.

Exhausts Goal and unifies Count with its number of answers, counting duplicates separately. A supplied non-negative integer count succeeds exactly when it equals that number. A failing goal has count zero. Bindings made while enumerating the goal do not escape; variables shared with Count are bound only by unification with the final count. Backtracking does not produce another count. An exception propagates without returning a partial count. A goal with infinitely many answers does not yield a completed count.

?- countall(member(X, [a,b,a]), N), var(X).
N = 3.
?- countall(fail, N).
N = 0.
Predicate: forall/2
isobase
forall(+Generate, ?Test) is semidet.

Requires Test to succeed for every answer of Generate. Each generator answer supplies bindings to its test; one successful test alternative is enough for that answer. The predicate fails as soon as a test has no successful alternative. Bindings made by either callback do not escape. If the generator has no answers, forall/2 succeeds without invoking the test. These rules also apply inside other meta-predicates. It has the same success and binding behaviour as:

\+ (call(Generate), \+ call(Test))

For example:

?- forall(member(X, [1,2,3]), X > 0), var(X).
true.
?- forall(fail, Unused), var(Unused).
true.
Predicate: make_ref/1
actor
make_ref(-Ref) is det.

Produces a fresh opaque correlation reference suitable for transport in messages. Programs compare references with == and must not depend on their representation. This is distinct from installing a monitor: no process is monitored and no notification is requested.

Predicate: sleep/1
isobase
sleep(+Seconds) is det.

Suspends execution for a non-negative number of seconds, which may be fractional. It does not consume mailbox messages and may be interrupted by control signals or an execution limit. An actor can also express the delay using a timed receive/2.

Node introspection

Predicate: node_setting/2
all public profiles
node_setting(?Key, ?Value) is nondet.

Enumerates publicly visible settings of the node servicing the current request. With Key bound, succeeds for its visible current value; an unknown or unavailable key fails. Shared-database source, credentials, and principal policies are not exposed. The public keys are:

General settings:

url, profile, sandbox, auth, timeout, and rate_window_seconds.

Stateless API:

max_inflight_calls, max_term_text_bytes, and max_call_requests_per_window.

Private database:

max_load_text_bytes and load_uri_allowed_origins.

Session API:

max_sessions_per_principal and max_session_spawns_per_window.

Actor API:

max_ws_actors_per_principal, max_ws_frame_bytes, and max_ws_commands_per_window.

API-specific keys are visible only when their corresponding built-in family is enabled for the node’s current profile. The predicate reports settings; it does not change them.

Remote execution and compatibility

A defined remote operation remains subject to the caller’s source-access policy, permission to use the destination, and the destination’s admission and execution policy. These are separate requirements: permission to fetch source does not grant permission to create an actor at that origin, and an allowed destination does not supply transport credentials. Retaining a client context across nodes does not widen any of these permissions. A deployment may restrict permitted peers without changing the operation’s language meaning.

Remote execution-time exhaustion is reported as error(resource_error(time), _), and memory exhaustion as error(resource_error(space), _). RPC clients propagate these exceptions. A client transport timeout does not establish that the remote computation has stopped.

Compatible peers preserve complete ordinary Prolog answer terms, variable sharing, quoted atoms, strings and exceptions. Public asynchronous answers remain success(Pid, Slice, More), failure(Pid) and error(Pid, Error). Missing or invalid term payloads raise remote_answer_protocol_error(missing_term) or remote_answer_protocol_error(invalid_term). Display text is not a substitute for a structured answer. Protocol negotiation and adapters for older peers are specified outside the language reference. This does not relax the message-term contract for send/2-3.

Monitor references retain their complete value, independently of pid display abbreviation. Correlated synchronous operations require peer support and fail explicitly when unavailable; peer compatibility is checked before dispatching operations that require it. A timeout or connection loss is not remote cancellation.

Page sizes are caller-controlled: HTTP requests, persistent-toplevel calls and next honour limit(N) without silently reducing it to an owner solution-count cap. A finite goal may finish with fewer answers; applicable resource limits still apply.

HTTP paging offsets advance by the number of answers actually returned, rather than the requested limit. A short non-final page therefore does not skip answers or a pending error. When an HTTP request resumes a retained computation, it uses that computation’s private database. A request supplying different source cannot resume it.

Execution and memory limits are deployment policies. Exhaustion uses the common formal errors stated above, independently of the host engine. If a failure prevents a usable protocol response, the connection may close; this does not establish whether remote work completed. Per-request budgets, continuation retention and cleanup after transport failure must not silently alter the documented paging or answer contract.

Deployment guides document resource accounting, source-fetch machinery, continuation storage and cleanup mechanisms. Protocol negotiation, wire envelopes, terminal acknowledgements and session replay are specified with the transport interfaces rather than as additional language predicates.

The complete wire specification remains in Appendix D of the book.


  1. https://www.complang.tuwien.ac.at/ulrich/iso-prolog/prologue↩︎