@primusclaw/personal-agent-runtime 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The platform services the Python worker always talks to, in place of the neutral plugins a deployment did not replace:
3
+ * whose key it is from SaFE's `/users/self` (the Python `safe.user_id_of` / `safe.whoami`, used by the subscriptions,
4
+ * `/whoami` and a report), and whose exchanged identity token it is from Claw's `/v1/me` (SaFE refuses such a token), a key deleted at SaFE when it is given up (`safe.revoke_own_key`: /unlink, and pending keys
5
+ * nobody redeemed), and the GitHub issues a report is filed as (`FeedbackService`'s GitHub sink, when FEEDBACK_REPO
6
+ * and a credential are set). A plugin a deployment did replace is kept.
7
+ */
8
+ import { type Logger, type Plugins, type SecretName, type Settings } from "@primusclaw/personal-agent";
9
+ import type { WorkerEnv } from "./worker-api.js";
10
+ export interface PlatformDeps {
11
+ readonly env: WorkerEnv;
12
+ readonly settings: Settings;
13
+ readonly secrets: ReadonlyMap<SecretName, string>;
14
+ readonly fetch: typeof fetch;
15
+ /** Seconds since the epoch. */
16
+ readonly now: () => number;
17
+ readonly logger: Logger;
18
+ }
19
+ /** `plugins` with the identity lookup and the feedback sink the Python worker builds in `main.run` where they are neutral. */
20
+ export declare function platformPlugins(plugins: Plugins, deps: PlatformDeps): Plugins;
@@ -0,0 +1,3 @@
1
+ import type { Worker } from "./worker-api.js";
2
+ /** Build a worker with `build` and run it until SIGTERM or SIGINT; the exit status the process should end with. */
3
+ export declare function runMain(build: () => Promise<Worker>, write?: (line: string) => void): Promise<number>;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * A built worker's run: its HTTP endpoints and /metrics listening, the features started, the timers running, then the
3
+ * inbound consumer (or, with no queue, waiting) until it is stopped; everything closed on the way out.
4
+ */
5
+ import type { Clock, Logger } from "@primusclaw/personal-agent";
6
+ import { type buildServer } from "@primusclaw/personal-agent-runtime";
7
+ import { type Timer } from "./timers.js";
8
+ import type { Worker } from "./worker-api.js";
9
+ /** The HTTP server the runtime builds (the worker does not depend on its framework). */
10
+ type Server = ReturnType<typeof buildServer>;
11
+ /**
12
+ * Where a surface's inbound events come from when they are not posted to the worker's own HTTP routes (Teams: the Service
13
+ * Bus queue's consumer). `run` resolves when it has stopped (after `stop`) and rejects when it fails; the worker stops
14
+ * then.
15
+ */
16
+ export interface InboundSource {
17
+ run(): Promise<void>;
18
+ stop(): void;
19
+ }
20
+ export interface RunnerParts {
21
+ readonly app: Server;
22
+ readonly metricsApp: Server;
23
+ readonly host: string;
24
+ readonly port: number;
25
+ readonly metricsPort: number;
26
+ readonly consumer: InboundSource | undefined;
27
+ readonly start: () => Promise<void>;
28
+ readonly timers: readonly Timer[];
29
+ readonly clock: Clock;
30
+ readonly logger: Logger;
31
+ readonly close: () => Promise<void>;
32
+ }
33
+ /** Run every close in turn, each even when one before it failed; a failure is logged by its kind. */
34
+ export declare function closeAll(logger: Logger, closes: readonly (() => unknown)[]): Promise<void>;
35
+ export declare function runner(parts: RunnerParts): Worker;
36
+ export {};
@@ -0,0 +1,7 @@
1
+ /**
2
+ * A setting the worker cannot work with, found while it is built: the start stops with this error's message (one CRITICAL
3
+ * line, status 1). The surface's own settings stop it the same way.
4
+ */
5
+ export declare class StartupError extends Error {
6
+ name: string;
7
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * What a surface package implements to run the worker on its chat app (`assembleWorker(adapter, env, plugins)`). The
3
+ * worker reads core's settings and secrets, opens the store and the Claw client, builds the features behind the router,
4
+ * serves its HTTP endpoints and runs its timers; the surface brings its own settings, its `Surface` (core's port: posting,
5
+ * editing, streams, files, views rendered its way), how a stored conversation reference is read back, and where its
6
+ * inbound events come from. The stages are called in this order, once each, and any of them may throw to stop the start
7
+ * (one CRITICAL line; a `SecretsUnavailable` exits with status 2, anything else with 1):
8
+ *
9
+ * prepare(env) before anything else is read: what the surface refuses first
10
+ * loadSecrets(deps) the secrets core's settings need (default: the environment alone)
11
+ * configure(settings) after core's settings, before the store opens: the surface's own settings
12
+ * open(context) once the store and the Claw client exist: its outbound side and its `Surface`
13
+ * connect(context) once the features are built: its inbound side (HTTP routes, or a source the worker runs)
14
+ *
15
+ * A surface package depends on core, the runtime and this package, and never on another surface package.
16
+ */
17
+ import type { Clock, ConversationRef, GroupContext, InboundEvent, Logger, MessageId, MetricsPort, Random, SecretName, Settings, Surface, TokenExchange } from "@primusclaw/personal-agent";
18
+ import type { HttpRoute, SqliteStore } from "@primusclaw/personal-agent-runtime";
19
+ import type { SurfaceShape } from "./features-base.js";
20
+ import type { Features } from "./features.js";
21
+ import type { InboundSource } from "./runner.js";
22
+ import type { WorkerEnv } from "./worker-api.js";
23
+ /** What every stage may use: the worker's clock, its logger and the `fetch` it sends with. */
24
+ export interface SurfaceDeps {
25
+ readonly clock: Clock;
26
+ readonly logger: Logger;
27
+ readonly fetch: typeof fetch;
28
+ }
29
+ export interface SurfaceAdapter {
30
+ /** The surface's name in the logs: the worker logs as `<name>_agent` ("teams": `teams_agent`). */
31
+ readonly name: string;
32
+ /** Before the secrets and core's settings are read; throws for a setting the surface refuses first. */
33
+ prepare(env: WorkerEnv): PreparedSurface;
34
+ }
35
+ export interface PreparedSurface {
36
+ /**
37
+ * The secrets `names` (what core's settings need), from where the surface's settings say. Without it the worker reads
38
+ * them from the environment, and SECRETS_SOURCE must be `env`.
39
+ */
40
+ loadSecrets?(names: readonly SecretName[], deps: SurfaceDeps): Promise<ReadonlyMap<SecretName, string>>;
41
+ /** After core's settings, before the store opens: the surface's own settings; throws for one it cannot use. */
42
+ configure(settings: Settings): ConfiguredSurface;
43
+ }
44
+ export interface ConfiguredSurface {
45
+ /** Where the worker's HTTP endpoints listen: "0.0.0.0", or the loopback while a test entry drives the worker. */
46
+ readonly host: string;
47
+ /** What the features read of the surface besides its port. */
48
+ readonly shape: SurfaceShape;
49
+ /** Once the store and the Claw client exist: the surface's outbound side and its `Surface`. */
50
+ open(context: SurfaceDeps & {
51
+ readonly random: Random;
52
+ }): OpenedSurface;
53
+ }
54
+ export interface OpenedSurface {
55
+ readonly surface: Surface;
56
+ /**
57
+ * `text` as the event the surface would have made of the person's own message `messageId` in `conversation` (what a
58
+ * plugin's `WorkerServices.handleAsTyped` hands the router); undefined when it cannot be read as one.
59
+ */
60
+ typedEvent(conversation: ConversationRef, messageId: MessageId, text: string): InboundEvent | undefined;
61
+ /** Once the features are built: the surface's inbound side. */
62
+ connect(context: ConnectContext): ConnectedSurface;
63
+ /**
64
+ * What the surface closes when the worker stops: after the features and the plugins' background tasks, before the store;
65
+ * in order, each even when one before it failed.
66
+ */
67
+ readonly closes: readonly (() => unknown)[];
68
+ }
69
+ export interface ConnectContext {
70
+ /** The router: every inbound event goes here. */
71
+ readonly route: (event: InboundEvent) => Promise<void>;
72
+ /** The recent messages kept of group chats: a removal, delete or edit the surface hears of changes them. */
73
+ readonly groupContext: GroupContext;
74
+ readonly store: SqliteStore;
75
+ readonly exchange: TokenExchange;
76
+ /** What a test entry reads: the subscriptions, and the Claw sessions this worker made. */
77
+ readonly gate: Features["gate"];
78
+ readonly metrics: MetricsPort;
79
+ readonly clock: Clock;
80
+ readonly logger: Logger;
81
+ }
82
+ export interface ConnectedSurface {
83
+ /** The surface's HTTP routes, served after the worker's own on its server (a webhook, a test entry); none: []. */
84
+ readonly routes: readonly HttpRoute[];
85
+ /** Where its inbound events come from otherwise (a queue's consumer, a socket); the worker runs it until it stops. */
86
+ readonly source: InboundSource | undefined;
87
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The worker's background loops (the Python worker's sweep, release, resend, retry and mend tasks): each runs every
3
+ * `everyMs` (first at start when `runAtStart`) until the worker stops; a run that fails is logged by its kind and the loop
4
+ * goes on.
5
+ */
6
+ import type { Clock, Logger } from "@primusclaw/personal-agent";
7
+ export interface Timer {
8
+ readonly name: string;
9
+ readonly everyMs: number;
10
+ readonly runAtStart: boolean;
11
+ run(): Promise<void>;
12
+ }
13
+ /** Run every timer until `signal` aborts; resolves when all have stopped. */
14
+ export declare function startTimers(timers: readonly Timer[], clock: Clock, logger: Logger, signal: AbortSignal): Promise<void>;
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The worker process, as an assembly can build it: the public `main` builds it with the neutral plugins, a deployment's
3
+ * own `main` (with its identity platform, model gateway rules, extra routes) builds it with its plugins. Everything else
4
+ * (store, Claw client, the surface's outbound and inbound, HTTP endpoints) is assembled from the environment the same way
5
+ * for both. A surface package (such as `@primusclaw/personal-agent-teams`) exports its own `buildWorker` and `main` of
6
+ * these shapes, made with `assembleWorker` and its `SurfaceAdapter`.
7
+ */
8
+ import type { Clock, ConversationRef, IntegrationRegistry, Logger, MessageId, Plugins } from "@primusclaw/personal-agent";
9
+ /** The environment the worker reads its settings from (`process.env`, or a copy a test or a gate made). */
10
+ export type WorkerEnv = Readonly<Record<string, string | undefined>>;
11
+ export interface WorkerOptions {
12
+ /** Defaults: the system clock, a line logger on stderr, the global `fetch`. */
13
+ readonly clock?: Clock;
14
+ readonly logger?: Logger;
15
+ readonly fetch?: typeof fetch;
16
+ /**
17
+ * A deployment's own services (its MCP servers, its /whoami lines), registered as the worker is built, on top of
18
+ * whatever the plugins' `integrations` already hold. Registering a server again renames it, but cannot clear the
19
+ * `query` flag the plugins gave it (the registry only adds). The public worker registers none.
20
+ */
21
+ readonly registerIntegrations?: (registry: IntegrationRegistry) => void;
22
+ }
23
+ /** A built worker: nothing runs until `run`. */
24
+ export interface Worker {
25
+ /**
26
+ * Start every part (HTTP endpoints, the inbound consumer or the gate's test entry, the timers) and resolve when the
27
+ * worker has stopped: after `stop`, or when a part fails (the promise rejects then).
28
+ */
29
+ run(): Promise<void>;
30
+ /** Stop taking new work, finish what is in hand, close connections. */
31
+ stop(): Promise<void>;
32
+ }
33
+ /**
34
+ * What a deployment's plugins may use of the worker they are built for (what the Python worker's on-behalf route used of
35
+ * its `Agent`). A person is named by the store's user id: their directory id (Teams: the Entra object id). `post` and the
36
+ * store reads work as soon as the plugins are built; `handleAsTyped` and `spawn` work once the worker is assembled (before
37
+ * then they throw: a plugin calls them from a request, never while it is built).
38
+ */
39
+ export interface WorkerServices {
40
+ /** The people whose link recorded Claw user `clawUserId`. */
41
+ channelUsersOf(clawUserId: string): readonly string[];
42
+ /** The Claw user a person's link recorded. */
43
+ clawUserOf(userId: string): string | undefined;
44
+ /** Whether a person's link holds a key. */
45
+ hasKey(userId: string): boolean;
46
+ /** Where the bot last talked with a person (their stored conversation reference). */
47
+ conversationOf(userId: string): ConversationRef | undefined;
48
+ /** The people this worker knows by name. */
49
+ knownPeople(): readonly {
50
+ readonly name: string;
51
+ readonly objectId: string;
52
+ }[];
53
+ /** Post `text` into `conversation`; the id the channel gave it, or undefined when it did not say it arrived. */
54
+ post(conversation: ConversationRef, text: string): Promise<MessageId | undefined>;
55
+ /** Handle `text` as the person's own message `messageId` in `conversation`, with provenance "on_behalf". */
56
+ handleAsTyped(conversation: ConversationRef, userId: string, messageId: MessageId, text: string): Promise<void>;
57
+ /** Run `task` in the background; the worker waits for it when it stops, and logs a failure by its kind. */
58
+ spawn(task: () => Promise<void>): void;
59
+ /** One `on_behalf_message` security event (operation "on_behalf"); the fields are shape-checked like every event's. */
60
+ audit(fields: Readonly<Record<string, string | number | null>>): void;
61
+ readonly logger: Logger;
62
+ }
63
+ /** A deployment's plugins, built with the worker's services; what it leaves out is the neutral default. */
64
+ export type PluginFactory = (services: WorkerServices) => Partial<Plugins>;
65
+ /**
66
+ * Build the worker from `env` with `plugins` (or a factory that builds them with the worker's services). Rejects at start,
67
+ * before anything is served, when the settings are not usable (a missing required setting, an unreadable key file): a
68
+ * worker that starts must be able to answer.
69
+ */
70
+ export type BuildWorker = (env: WorkerEnv, plugins: Plugins | PluginFactory, options?: WorkerOptions) => Promise<Worker>;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The worker's services a deployment's plugins are built with (`WorkerServices`): the store's reads, a post into a chat,
3
+ * and a message handled as the person's own (the Python worker's `Agent.on_behalf`: `activity_of_reference` with the text,
4
+ * handled in a task of its own with provenance "on_behalf"). The router is bound once it is built.
5
+ */
6
+ import { type ConversationRef, type InboundEvent, type JsonObject, type Logger, type MessageId, type Router, type SecurityLog, type Surface } from "@primusclaw/personal-agent";
7
+ import type { SqliteStore } from "@primusclaw/personal-agent-runtime";
8
+ import type { WorkerServices } from "./worker-api.js";
9
+ export interface ServicesParts {
10
+ readonly store: SqliteStore;
11
+ readonly surface: Surface;
12
+ readonly securityLog: SecurityLog;
13
+ readonly logger: Logger;
14
+ /** A stored conversation reference back as core's (the surface's `restoreRef`). */
15
+ readonly restoreRef: (stored: JsonObject) => ConversationRef | undefined;
16
+ /**
17
+ * `text` as the event the surface would have made of the person's own message `messageId` in `conversation` (the
18
+ * surface's `typedEvent`); undefined when it cannot be read.
19
+ */
20
+ readonly typedEvent: (conversation: ConversationRef, messageId: MessageId, text: string) => InboundEvent | undefined;
21
+ }
22
+ /** The services, the router they wait for, and the background tasks to wait for when the worker stops. */
23
+ export interface BoundServices {
24
+ readonly services: WorkerServices;
25
+ bind(router: Router): void;
26
+ /** Resolves when every task spawned so far has ended. */
27
+ idle(): Promise<void>;
28
+ }
29
+ export declare function workerServices(parts: ServicesParts): BoundServices;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @primusclaw/personal-agent-runtime/worker: the worker process, whatever chat app it runs on. It builds the features
3
+ * behind the router, the store, the Claw client, the HTTP endpoints, /metrics and the background loops from the
4
+ * environment, and runs them on a surface a surface package brings (`SurfaceAdapter`, handed to `assembleWorker`). It
5
+ * uses core and runtime's main entry (by package name, so its bundle carries no second copy of runtime), never a surface
6
+ * package; nothing else of runtime imports it.
7
+ */
8
+ export * from "./worker/worker-api.js";
9
+ export * from "./worker/surface-adapter.js";
10
+ export { assembleWorker, envSecrets, withInboundStats, withRegistered } from "./worker/assemble.js";
11
+ export { runMain } from "./worker/run-main.js";
12
+ export { BUILD_INFO_METRIC, buildInfoText, withBuildInfo } from "./worker/build-info.js";
13
+ export { StartupError } from "./worker/startup-error.js";
14
+ export type { InboundSource } from "./worker/runner.js";
15
+ export { ASSISTANT_ACTION, buildFeatures, ON_BEHALF_PATH, SWEEP_MS, type AssemblyBase, type FeatureTimer, type Features, type GateSubscriptions, type ReplyStyle, type SurfaceShape, } from "./worker/features.js";
16
+ export { workerServices, type BoundServices, type ServicesParts } from "./worker/worker-services.js";
17
+ /** Parts of the assembly a surface package's tests check on their own (the remote ask's card, a review's work card). */
18
+ export { remoteAskCard } from "./worker/features-assistant.js";
19
+ export { workCardPoster } from "./worker/features-review.js";
20
+ export { platformPlugins, type PlatformDeps } from "./worker/plugins.js";