@plico-ai/server 0.0.0-reserved.0 → 0.1.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.
Files changed (77) hide show
  1. package/NOTICE +4 -0
  2. package/README.md +8 -3
  3. package/dist/api.d.ts +32 -0
  4. package/dist/api.js +87 -0
  5. package/dist/app/assemble.d.ts +10 -0
  6. package/dist/app/assemble.js +49 -0
  7. package/dist/app/errors.d.ts +6 -0
  8. package/dist/app/errors.js +24 -0
  9. package/dist/app/events.d.ts +9 -0
  10. package/dist/app/events.js +52 -0
  11. package/dist/app/metadata.d.ts +4 -0
  12. package/dist/app/metadata.js +24 -0
  13. package/dist/app/runs.d.ts +31 -0
  14. package/dist/app/runs.js +81 -0
  15. package/dist/app/scope.d.ts +8 -0
  16. package/dist/app/scope.js +18 -0
  17. package/dist/app/threads.d.ts +15 -0
  18. package/dist/app/threads.js +133 -0
  19. package/dist/app/types.d.ts +103 -0
  20. package/dist/app/types.js +1 -0
  21. package/dist/body.d.ts +4 -0
  22. package/dist/body.js +54 -0
  23. package/dist/create-plico.d.ts +18 -0
  24. package/dist/create-plico.js +75 -0
  25. package/dist/errors.d.ts +7 -0
  26. package/dist/errors.js +19 -0
  27. package/dist/index.d.ts +6 -0
  28. package/dist/index.js +3 -0
  29. package/dist/listener.d.ts +6 -0
  30. package/dist/listener.js +8 -0
  31. package/dist/mount.d.ts +32 -0
  32. package/dist/mount.js +34 -0
  33. package/dist/origin-guard.d.ts +15 -0
  34. package/dist/origin-guard.js +39 -0
  35. package/dist/project.d.ts +2 -0
  36. package/dist/project.js +10 -0
  37. package/dist/recovery.d.ts +19 -0
  38. package/dist/recovery.js +84 -0
  39. package/dist/responses.d.ts +1 -0
  40. package/dist/responses.js +6 -0
  41. package/dist/routes/artifacts.d.ts +2 -0
  42. package/dist/routes/artifacts.js +165 -0
  43. package/dist/routes/eval.d.ts +2 -0
  44. package/dist/routes/eval.js +38 -0
  45. package/dist/routes/health.d.ts +2 -0
  46. package/dist/routes/health.js +8 -0
  47. package/dist/routes/index.d.ts +11 -0
  48. package/dist/routes/index.js +72 -0
  49. package/dist/routes/metadata-query.d.ts +4 -0
  50. package/dist/routes/metadata-query.js +13 -0
  51. package/dist/routes/project.d.ts +2 -0
  52. package/dist/routes/project.js +23 -0
  53. package/dist/routes/readiness.d.ts +2 -0
  54. package/dist/routes/readiness.js +17 -0
  55. package/dist/routes/runs.d.ts +2 -0
  56. package/dist/routes/runs.js +82 -0
  57. package/dist/routes/threads.d.ts +2 -0
  58. package/dist/routes/threads.js +60 -0
  59. package/dist/routes/types.d.ts +30 -0
  60. package/dist/routes/types.js +1 -0
  61. package/dist/script.d.ts +8 -0
  62. package/dist/script.js +35 -0
  63. package/dist/serve-static.d.ts +2 -0
  64. package/dist/serve-static.js +37 -0
  65. package/dist/server.d.ts +4 -0
  66. package/dist/server.js +25 -0
  67. package/dist/sse.d.ts +3 -0
  68. package/dist/sse.js +12 -0
  69. package/dist/stream.d.ts +13 -0
  70. package/dist/stream.js +58 -0
  71. package/dist/thread-failure.d.ts +7 -0
  72. package/dist/thread-failure.js +42 -0
  73. package/dist/thread-titles.d.ts +11 -0
  74. package/dist/thread-titles.js +37 -0
  75. package/dist/types.d.ts +12 -0
  76. package/dist/types.js +1 -0
  77. package/package.json +37 -8
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Plico
2
+ Copyright 2026 Plico contributors
3
+
4
+ This product includes software developed by the Plico contributors.
package/README.md CHANGED
@@ -1,6 +1,11 @@
1
1
  # @plico-ai/server
2
2
 
3
- The Plico HTTP API and embeddable library.
3
+ The thin native HTTP API over the Plico runtime and event store: runs, threads, signals, approvals, cancel, artifacts, events and readiness.
4
4
 
5
- This is a pre-release placeholder. The first developer preview is in progress at
6
- https://github.com/ITZSHOAIB/plico. Docs: https://plico.sohab.dev
5
+ Embed it in your own Node backend with `createPlico({ projectRoot, databasePath })`, which returns `threads`, `runs` (including `runs.events()`, an async iterator over a run's events), `approvals` and `close()`. Files define the agent; the library only runs it. `plico.fetch()` and `plico.node()` mount the `/v1` API in Express, Hono, Next.js and similar hosts, with a per-request `scope` and `context`. `servePlico` is `createPlico` plus an HTTP listener.
6
+
7
+ Threads and runs take a host `metadata` JSON object at creation (immutable; lists filter by exact match on top-level keys). A run takes a `context` that tools read as `ctx.context`; it is recorded on `run.started`, so it must not carry secrets. See `docs/threads.md`.
8
+
9
+ Start the HTTP server with `plico serve [path]` from [`@plico-ai/cli`](../cli). It binds to loopback by default and rejects cross-origin and DNS-rebinding requests unless `--allow-remote` is set. Run requests that carry a `script` are refused with 403 `run.script_disabled` unless `--allow-script` (`allowScript: true`) is set.
10
+
11
+ Requires Node `>=22.18`. Wire types come from `@plico-ai/contracts`.
package/dist/api.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ import { Hono } from "hono";
2
+ import type { PlicoInternals } from "./app/assemble.js";
3
+ import type { Metadata } from "./app/metadata.js";
4
+ /** What a host computes from each request on a mounted API. */
5
+ export type RequestData = (request: Request) => Metadata | undefined | Promise<Metadata | undefined>;
6
+ /** The HTTP-only options. A library embedder never sets these. */
7
+ export interface ListenerOptions {
8
+ studioPath?: string;
9
+ /**
10
+ * Skip the loopback `Host` check. Set it when the server is deliberately reachable under another
11
+ * name, for example behind a host app's own authentication. Cross-origin requests stay refused.
12
+ */
13
+ allowRemote?: boolean;
14
+ /**
15
+ * The origin browsers use to reach this server, such as `https://plico.example` when TLS ends at
16
+ * a proxy. A request `Origin` must match it exactly, scheme and port included. Without it, the
17
+ * scheme of the connection and the `Host` header decide.
18
+ */
19
+ publicOrigin?: string;
20
+ /**
21
+ * Accept a `script` on `POST /v1/runs` and `POST /v1/runs/dry`. A script calls project tool
22
+ * handlers with arguments the caller chooses and skips the model, so it is off by default.
23
+ */
24
+ allowScript?: boolean;
25
+ /** Computed per request on a mounted API; see `MountOptions`. */
26
+ scope?: RequestData;
27
+ context?: RequestData;
28
+ /** The path the API is mounted under, removed before routing. */
29
+ basePath?: string;
30
+ }
31
+ /** The `/v1` API, and Studio when `studioPath` is set, over one `Plico`, as a Hono app. */
32
+ export declare function createApi({ deps, stop }: PlicoInternals, options?: ListenerOptions): Hono;
package/dist/api.js ADDED
@@ -0,0 +1,87 @@
1
+ import { Hono } from "hono";
2
+ import { readMetadata } from "./app/metadata.js";
3
+ import { errorResponse, HttpError } from "./errors.js";
4
+ import { assertTrustedRequest } from "./origin-guard.js";
5
+ import { handleRequest } from "./routes/index.js";
6
+ import { serveStaticFile } from "./serve-static.js";
7
+ /** The `/v1` API, and Studio when `studioPath` is set, over one `Plico`, as a Hono app. */
8
+ export function createApi({ deps, stop }, options = {}) {
9
+ const { studioPath } = options;
10
+ const api = new Hono();
11
+ api.use("*", async (context, next) => {
12
+ try {
13
+ assertTrustedRequest(context.req.raw, {
14
+ allowRemote: options.allowRemote === true,
15
+ publicOrigin: options.publicOrigin,
16
+ });
17
+ }
18
+ catch (error) {
19
+ if (!(error instanceof HttpError))
20
+ throw error;
21
+ return errorResponse(error.status, error.code, error.message);
22
+ }
23
+ await next();
24
+ });
25
+ api.all("*", async (context) => {
26
+ const request = withoutBasePath(context.req.raw, options.basePath);
27
+ const url = new URL(request.url);
28
+ const isApiPath = url.pathname === "/health" || url.pathname.startsWith("/v1/");
29
+ const route = async () => {
30
+ try {
31
+ return await handleRequest({
32
+ app: await requestDeps(deps, request, options),
33
+ stop,
34
+ studioPath,
35
+ allowScript: options.allowScript === true,
36
+ request,
37
+ });
38
+ }
39
+ catch (error) {
40
+ if (!(error instanceof HttpError))
41
+ throw error;
42
+ return errorResponse(error.status, error.code, error.message);
43
+ }
44
+ };
45
+ if (isApiPath || !studioPath)
46
+ return route();
47
+ return ((await serveStaticFile(studioPath, url.pathname)) ??
48
+ (await serveStaticFile(studioPath, "/index.html")) ??
49
+ route());
50
+ });
51
+ return api;
52
+ }
53
+ /**
54
+ * The deps for one request. A host function that fails or returns something other than a JSON
55
+ * object ends the request: an unreadable scope must never mean "no scope".
56
+ */
57
+ async function requestDeps(deps, request, options) {
58
+ if (!options.scope && !options.context)
59
+ return deps;
60
+ try {
61
+ const scope = options.scope ? readMetadata(await options.scope(request), "scope") : undefined;
62
+ if (options.scope && scope === undefined)
63
+ throw new TypeError("scope must be a JSON object.");
64
+ const context = options.context
65
+ ? readMetadata(await options.context(request), "context")
66
+ : undefined;
67
+ return {
68
+ ...deps,
69
+ ...(scope === undefined ? {} : { scope }),
70
+ ...(context === undefined ? {} : { context }),
71
+ };
72
+ }
73
+ catch (error) {
74
+ console.error(`plico: could not compute scope or context: ${error instanceof Error ? error.message : String(error)}`);
75
+ throw new HttpError(500, "server.error", "Internal server error.");
76
+ }
77
+ }
78
+ function withoutBasePath(request, basePath) {
79
+ const prefix = basePath?.replace(/\/+$/, "");
80
+ if (!prefix)
81
+ return request;
82
+ const url = new URL(request.url);
83
+ if (url.pathname !== prefix && !url.pathname.startsWith(`${prefix}/`))
84
+ return request;
85
+ url.pathname = url.pathname.slice(prefix.length) || "/";
86
+ return new Request(url, request);
87
+ }
@@ -0,0 +1,10 @@
1
+ import type { AppDeps, Plico } from "./types.js";
2
+ /** What the HTTP listener needs behind a `Plico`. Never part of the public surface. */
3
+ export interface PlicoInternals {
4
+ deps: AppDeps;
5
+ /** Aborts when `close()` starts, so open event streams end. */
6
+ stop: AbortSignal;
7
+ }
8
+ export declare function internalsOf(plico: Plico): PlicoInternals;
9
+ /** Builds the programmatic API over stores that already exist. `onClose` releases what they hold. */
10
+ export declare function assemblePlico(appDeps: AppDeps, onClose?: () => void | Promise<void>): Plico;
@@ -0,0 +1,49 @@
1
+ import { createFetchHandler, createNodeHandler } from "../mount.js";
2
+ import { withThreadTitles } from "../thread-titles.js";
3
+ import { followEvents } from "./events.js";
4
+ import { cancelRun, decideApproval, listRuns, startRun } from "./runs.js";
5
+ import { createThread, getThread, listThreads, renameThread, sendMessage, threadMessages, } from "./threads.js";
6
+ const registry = new WeakMap();
7
+ export function internalsOf(plico) {
8
+ const internals = registry.get(plico);
9
+ if (!internals)
10
+ throw new TypeError("Not a Plico instance created by this package.");
11
+ return internals;
12
+ }
13
+ /** Builds the programmatic API over stores that already exist. `onClose` releases what they hold. */
14
+ export function assemblePlico(appDeps, onClose = () => { }) {
15
+ const deps = { ...appDeps, eventStore: withThreadTitles(appDeps) };
16
+ const stopper = new AbortController();
17
+ let closing;
18
+ const plico = {
19
+ threads: {
20
+ create: (options) => createThread(deps, options),
21
+ get: (threadId) => getThread(deps, threadId),
22
+ list: (filter) => listThreads(deps, filter),
23
+ rename: (threadId, title) => renameThread(deps, threadId, title),
24
+ messages: (threadId) => threadMessages(deps, threadId),
25
+ send: (threadId, content, options) => sendMessage(deps, threadId, content, options),
26
+ },
27
+ runs: {
28
+ start: (options) => startRun(deps, options),
29
+ get: (runId) => deps.eventStore.getRun(runId),
30
+ list: (filter) => listRuns(deps, filter),
31
+ cancel: (runId) => cancelRun(deps, runId),
32
+ events: (runId, options) => followEvents(deps, runId, { ...options, stop: stopper.signal }),
33
+ },
34
+ approvals: {
35
+ decide: (runId, requestId, approved, options) => decideApproval(deps, runId, requestId, approved, options),
36
+ },
37
+ fetch: (options) => createFetchHandler({ deps, stop: stopper.signal }, options),
38
+ node: (options) => createNodeHandler({ deps, stop: stopper.signal }, options),
39
+ close() {
40
+ closing ??= (async () => {
41
+ stopper.abort();
42
+ await onClose();
43
+ })();
44
+ return closing;
45
+ },
46
+ };
47
+ registry.set(plico, { deps, stop: stopper.signal });
48
+ return plico;
49
+ }
@@ -0,0 +1,6 @@
1
+ /** A failure the shared layer reports by code. The HTTP routes map the code to a status. */
2
+ export declare class PlicoError extends Error {
3
+ readonly code: string;
4
+ constructor(code: string, message: string);
5
+ }
6
+ export declare function statusForCode(code: string): number;
@@ -0,0 +1,24 @@
1
+ /** A failure the shared layer reports by code. The HTTP routes map the code to a status. */
2
+ export class PlicoError extends Error {
3
+ code;
4
+ constructor(code, message) {
5
+ super(message);
6
+ this.code = code;
7
+ }
8
+ }
9
+ const statusByCode = {
10
+ "thread.not_found": 404,
11
+ "run.not_found": 404,
12
+ "workspace.not_found": 404,
13
+ "thread.busy": 409,
14
+ "thread.invalid_title": 400,
15
+ "message.invalid": 400,
16
+ "request.invalid": 400,
17
+ "threads.unavailable": 503,
18
+ "threads.store_mismatch": 503,
19
+ "provider.unavailable": 503,
20
+ "workspace.unavailable": 503,
21
+ };
22
+ export function statusForCode(code) {
23
+ return statusByCode[code] ?? 500;
24
+ }
@@ -0,0 +1,9 @@
1
+ import type { PlicoEvent } from "@plico-ai/contracts";
2
+ import type { AppDeps, EventFollowOptions } from "./types.js";
3
+ /**
4
+ * Yields a run's events from a cursor and ends after its terminal event. The first read happens
5
+ * on the first `next()`, so callers that need a 404 before writing anything check the run first.
6
+ */
7
+ export declare function followEvents(deps: Pick<AppDeps, "eventStore" | "scope">, runId: string, options: EventFollowOptions & {
8
+ stop: AbortSignal;
9
+ }): AsyncGenerator<PlicoEvent, void, void>;
@@ -0,0 +1,52 @@
1
+ import { PlicoError } from "./errors.js";
2
+ import { inScope } from "./scope.js";
3
+ // Waiting is not terminal: the stream stays open for approval (#69). run.error is followed by
4
+ // run.failed, which closes the stream.
5
+ const terminalEventTypes = [
6
+ "run.completed",
7
+ "run.failed",
8
+ "run.cancelled",
9
+ ];
10
+ const terminalStatuses = ["completed", "failed", "cancelled"];
11
+ /**
12
+ * Yields a run's events from a cursor and ends after its terminal event. The first read happens
13
+ * on the first `next()`, so callers that need a 404 before writing anything check the run first.
14
+ */
15
+ export async function* followEvents(deps, runId, options) {
16
+ const { eventStore } = deps;
17
+ const stop = options.signal ? AbortSignal.any([options.signal, options.stop]) : options.stop;
18
+ const pollMs = options.pollMs ?? 2000;
19
+ const first = await eventStore.getRun(runId);
20
+ if (!first || !inScope(deps, first.metadata))
21
+ throw new PlicoError("run.not_found", `Unknown run ID: ${runId}`);
22
+ let cursor = options.after ?? 0;
23
+ while (!stop.aborted) {
24
+ const events = await eventStore.getEvents(runId, { afterSequence: cursor });
25
+ for (const event of events) {
26
+ yield event;
27
+ cursor = event.sequence;
28
+ }
29
+ if (events.some((event) => terminalEventTypes.includes(event.type)))
30
+ return;
31
+ const run = await eventStore.getRun(runId);
32
+ if (run && terminalStatuses.includes(run.status)) {
33
+ for (const event of await eventStore.getEvents(runId, { afterSequence: cursor }))
34
+ yield event;
35
+ return;
36
+ }
37
+ await sleep(pollMs, stop);
38
+ }
39
+ }
40
+ function sleep(ms, signal) {
41
+ return new Promise((resolve) => {
42
+ if (signal.aborted)
43
+ return resolve();
44
+ const done = () => {
45
+ clearTimeout(timer);
46
+ signal.removeEventListener("abort", done);
47
+ resolve();
48
+ };
49
+ const timer = setTimeout(done, ms);
50
+ signal.addEventListener("abort", done);
51
+ });
52
+ }
@@ -0,0 +1,4 @@
1
+ import type { JsonValue } from "@plico-ai/contracts";
2
+ export type Metadata = Record<string, JsonValue>;
3
+ /** Accepts a plain JSON object and returns it; anything else is a `request.invalid` error. */
4
+ export declare function readMetadata(value: unknown, name?: string): Metadata | undefined;
@@ -0,0 +1,24 @@
1
+ import { PlicoError } from "./errors.js";
2
+ /** Accepts a plain JSON object and returns it; anything else is a `request.invalid` error. */
3
+ export function readMetadata(value, name = "metadata") {
4
+ if (value === undefined)
5
+ return undefined;
6
+ if (!isPlainObject(value) || !isJson(value))
7
+ throw new PlicoError("request.invalid", `${name} must be a JSON object.`);
8
+ return value;
9
+ }
10
+ function isPlainObject(value) {
11
+ if (typeof value !== "object" || value === null || Array.isArray(value))
12
+ return false;
13
+ const prototype = Object.getPrototypeOf(value);
14
+ return prototype === Object.prototype || prototype === null;
15
+ }
16
+ function isJson(value) {
17
+ if (value === null || typeof value === "string" || typeof value === "boolean")
18
+ return true;
19
+ if (typeof value === "number")
20
+ return Number.isFinite(value);
21
+ if (Array.isArray(value))
22
+ return value.every(isJson);
23
+ return isPlainObject(value) && Object.values(value).every(isJson);
24
+ }
@@ -0,0 +1,31 @@
1
+ import type { PlicoEvent, RunSummary } from "@plico-ai/contracts";
2
+ import { type DryRunScriptStep, type RunResult } from "@plico-ai/runtime";
3
+ import type { AppDeps } from "./types.js";
4
+ export declare function startRun(deps: AppDeps, options?: {
5
+ script?: DryRunScriptStep[];
6
+ mockTools?: boolean;
7
+ metadata?: unknown;
8
+ context?: unknown;
9
+ }): Promise<{
10
+ runId: string;
11
+ }>;
12
+ /** Runs the project to the end without a model and returns its result. */
13
+ export declare function runDry(deps: AppDeps, options?: {
14
+ script?: DryRunScriptStep[];
15
+ mockTools?: boolean;
16
+ }): Promise<RunResult>;
17
+ export declare function listRuns(deps: AppDeps, filter?: {
18
+ metadata?: unknown;
19
+ }): Promise<RunSummary[]>;
20
+ export declare function requireRun(deps: AppDeps, runId: string): Promise<RunSummary>;
21
+ export declare function cancelRun(deps: AppDeps, runId: string): Promise<string>;
22
+ /**
23
+ * Sends a client's signal. An approval signal from a client carries no `context` of its own: only
24
+ * the host may say who decided, through `decideApproval` or the `context` of a mounted handler.
25
+ */
26
+ export declare function signalRun(deps: AppDeps, runId: string, name: string, value: unknown): Promise<string>;
27
+ /** Approval decisions are signals on the wait named `approval:<requestId>` (ADR 0008). */
28
+ export declare function decideApproval(deps: AppDeps, runId: string, requestId: string, approved: boolean, options?: {
29
+ context?: unknown;
30
+ }): Promise<string>;
31
+ export declare function listRunEvents(deps: AppDeps, runId: string, afterSequence?: number): Promise<PlicoEvent[]>;
@@ -0,0 +1,81 @@
1
+ import { runProject } from "@plico-ai/runtime";
2
+ import { PlicoError } from "./errors.js";
3
+ import { readMetadata } from "./metadata.js";
4
+ import { inScope, scopedFilter, scopedMetadata } from "./scope.js";
5
+ export async function startRun(deps, options = {}) {
6
+ const metadata = scopedMetadata(deps, readMetadata(options.metadata));
7
+ const context = readMetadata(options.context, "context") ?? deps.context;
8
+ let resolveStarted;
9
+ let rejectStarted;
10
+ const started = new Promise((resolve, reject) => {
11
+ resolveStarted = resolve;
12
+ rejectStarted = reject;
13
+ });
14
+ void runProject(deps.projectRoot, {
15
+ eventStore: deps.eventStore,
16
+ engine: deps.engine,
17
+ ...(options.script === undefined ? {} : { script: options.script }),
18
+ ...(options.mockTools === true ? { mockTools: true } : {}),
19
+ ...(metadata === undefined ? {} : { metadata }),
20
+ ...(context === undefined ? {} : { context }),
21
+ onStarted: resolveStarted,
22
+ }).catch(rejectStarted);
23
+ return { runId: await started };
24
+ }
25
+ /** Runs the project to the end without a model and returns its result. */
26
+ export function runDry(deps, options = {}) {
27
+ return runProject(deps.projectRoot, {
28
+ ...(options.script === undefined ? {} : { script: options.script }),
29
+ ...(options.mockTools === true ? { mockTools: true } : {}),
30
+ eventStore: deps.eventStore,
31
+ engine: deps.engine,
32
+ });
33
+ }
34
+ export async function listRuns(deps, filter = {}) {
35
+ const metadata = scopedFilter(deps, readMetadata(filter.metadata));
36
+ return deps.eventStore.listRuns(metadata === undefined ? {} : { metadata });
37
+ }
38
+ export async function requireRun(deps, runId) {
39
+ const run = await deps.eventStore.getRun(runId);
40
+ if (!run || !inScope(deps, run.metadata))
41
+ throw new PlicoError("run.not_found", `Unknown run ID: ${runId}`);
42
+ return run;
43
+ }
44
+ export async function cancelRun(deps, runId) {
45
+ await requireRun(deps, runId);
46
+ return deps.engine.cancel(runId);
47
+ }
48
+ /**
49
+ * Sends a client's signal. An approval signal from a client carries no `context` of its own: only
50
+ * the host may say who decided, through `decideApproval` or the `context` of a mounted handler.
51
+ */
52
+ export function signalRun(deps, runId, name, value) {
53
+ const clean = name.startsWith("approval:") &&
54
+ typeof value === "object" &&
55
+ value !== null &&
56
+ !Array.isArray(value)
57
+ ? {
58
+ ...Object.fromEntries(Object.entries(value).filter(([key]) => key !== "context")),
59
+ ...(deps.context === undefined ? {} : { context: deps.context }),
60
+ }
61
+ : value;
62
+ return sendSignal(deps, runId, name, clean);
63
+ }
64
+ async function sendSignal(deps, runId, name, value) {
65
+ await requireRun(deps, runId);
66
+ if (!name)
67
+ throw new PlicoError("request.invalid", "A signal name is required.");
68
+ return deps.engine.signal(runId, name, value);
69
+ }
70
+ /** Approval decisions are signals on the wait named `approval:<requestId>` (ADR 0008). */
71
+ export function decideApproval(deps, runId, requestId, approved, options = {}) {
72
+ const context = readMetadata(options.context, "context") ?? deps.context;
73
+ return sendSignal(deps, runId, `approval:${requestId}`, {
74
+ approved,
75
+ ...(context === undefined ? {} : { context }),
76
+ });
77
+ }
78
+ export async function listRunEvents(deps, runId, afterSequence) {
79
+ await requireRun(deps, runId);
80
+ return deps.eventStore.getEvents(runId, afterSequence === undefined ? {} : { afterSequence });
81
+ }
@@ -0,0 +1,8 @@
1
+ import type { Metadata } from "./metadata.js";
2
+ import type { AppDeps } from "./types.js";
3
+ /** True when the request's scope allows an item with this metadata. Without a scope, always. */
4
+ export declare function inScope(deps: Pick<AppDeps, "scope">, metadata: Metadata | undefined): boolean;
5
+ /** The metadata a new thread or run gets. A scope owns it; a scoped client cannot set its own. */
6
+ export declare function scopedMetadata(deps: Pick<AppDeps, "scope">, requested: Metadata | undefined): Metadata | undefined;
7
+ /** A list filter narrowed by the scope. The scope's keys win, so a client cannot widen it. */
8
+ export declare function scopedFilter(deps: Pick<AppDeps, "scope">, requested: Metadata | undefined): Metadata | undefined;
@@ -0,0 +1,18 @@
1
+ import { matchesMetadata } from "@plico-ai/runtime";
2
+ import { PlicoError } from "./errors.js";
3
+ /** True when the request's scope allows an item with this metadata. Without a scope, always. */
4
+ export function inScope(deps, metadata) {
5
+ return deps.scope === undefined || matchesMetadata(metadata, deps.scope);
6
+ }
7
+ /** The metadata a new thread or run gets. A scope owns it; a scoped client cannot set its own. */
8
+ export function scopedMetadata(deps, requested) {
9
+ if (deps.scope === undefined)
10
+ return requested;
11
+ if (requested !== undefined)
12
+ throw new PlicoError("request.invalid", "metadata is set by the host through scope.");
13
+ return deps.scope;
14
+ }
15
+ /** A list filter narrowed by the scope. The scope's keys win, so a client cannot widen it. */
16
+ export function scopedFilter(deps, requested) {
17
+ return deps.scope === undefined ? requested : { ...requested, ...deps.scope };
18
+ }
@@ -0,0 +1,15 @@
1
+ import type { Thread, ThreadArtifactWorkspace, ThreadMessage } from "@plico-ai/contracts";
2
+ import type { AppDeps, SendMessageOptions } from "./types.js";
3
+ export declare function requireThread(deps: AppDeps, threadId: string): Promise<Thread>;
4
+ export declare function createThread(deps: AppDeps, options?: {
5
+ metadata?: unknown;
6
+ }): Promise<Thread>;
7
+ export declare function getThread(deps: AppDeps, threadId: string): Promise<Thread | undefined>;
8
+ export declare function listThreads(deps: AppDeps, filter?: {
9
+ metadata?: unknown;
10
+ }): Promise<Thread[]>;
11
+ export declare function renameThread(deps: AppDeps, threadId: string, title: unknown): Promise<Thread>;
12
+ export declare function threadMessages(deps: AppDeps, threadId: string): Promise<ThreadMessage[]>;
13
+ export declare function threadWorkspace(deps: AppDeps, threadId: string): Promise<ThreadArtifactWorkspace>;
14
+ /** Records a user message and, unless told not to, starts the run that answers it. */
15
+ export declare function sendMessage(deps: AppDeps, threadId: string, content: unknown, options?: SendMessageOptions): Promise<ThreadMessage>;
@@ -0,0 +1,133 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { resolve } from "node:path";
3
+ import { buildArtifactWorkspace, runProject, ThreadBusyError } from "@plico-ai/runtime";
4
+ import { finishFailedThreadRun } from "../thread-failure.js";
5
+ import { PlicoError } from "./errors.js";
6
+ import { readMetadata } from "./metadata.js";
7
+ import { inScope, scopedFilter, scopedMetadata } from "./scope.js";
8
+ const maxTitleLength = 200;
9
+ function storeFor(deps) {
10
+ if (!deps.threadStore)
11
+ throw new PlicoError("threads.unavailable", "Thread storage is unavailable.");
12
+ return deps.threadStore;
13
+ }
14
+ export async function requireThread(deps, threadId) {
15
+ const thread = await storeFor(deps).getThread(threadId);
16
+ if (!thread || !inScope(deps, thread.metadata))
17
+ throw new PlicoError("thread.not_found", `Unknown thread ID: ${threadId}`);
18
+ return thread;
19
+ }
20
+ export async function createThread(deps, options = {}) {
21
+ return storeFor(deps).createThread(scopedMetadata(deps, readMetadata(options.metadata)));
22
+ }
23
+ export async function getThread(deps, threadId) {
24
+ const thread = await storeFor(deps).getThread(threadId);
25
+ return thread && inScope(deps, thread.metadata) ? thread : undefined;
26
+ }
27
+ export async function listThreads(deps, filter = {}) {
28
+ const metadata = scopedFilter(deps, readMetadata(filter.metadata));
29
+ return storeFor(deps).listThreads(metadata === undefined ? {} : { metadata });
30
+ }
31
+ export async function renameThread(deps, threadId, title) {
32
+ const thread = await requireThread(deps, threadId);
33
+ const trimmed = typeof title === "string" ? title.trim() : "";
34
+ if (!trimmed || trimmed.length > maxTitleLength)
35
+ throw new PlicoError("thread.invalid_title", `Title must be a nonempty string of at most ${maxTitleLength} characters.`);
36
+ const renamed = await storeFor(deps).renameThread(thread.id, trimmed);
37
+ if (!renamed)
38
+ throw new PlicoError("thread.not_found", `Unknown thread ID: ${threadId}`);
39
+ return renamed;
40
+ }
41
+ export async function threadMessages(deps, threadId) {
42
+ const thread = await requireThread(deps, threadId);
43
+ return storeFor(deps).getMessages(thread.id);
44
+ }
45
+ export async function threadWorkspace(deps, threadId) {
46
+ const thread = await requireThread(deps, threadId);
47
+ if (!deps.eventStore.getThreadRunEvents)
48
+ throw new PlicoError("workspace.unavailable", "Thread workspace projection is unavailable.");
49
+ const events = await deps.eventStore.getThreadRunEvents(thread.id);
50
+ const workspace = buildArtifactWorkspace(thread.id, events);
51
+ if (!workspace)
52
+ throw new PlicoError("workspace.not_found", `No artifact workspace for thread: ${thread.id}`);
53
+ const { runId: _runId, ...threadWorkspace } = workspace;
54
+ return { ...threadWorkspace, threadId: thread.id };
55
+ }
56
+ /** Records a user message and, unless told not to, starts the run that answers it. */
57
+ export async function sendMessage(deps, threadId, content, options = {}) {
58
+ const store = storeFor(deps);
59
+ const thread = await requireThread(deps, threadId);
60
+ if (typeof content !== "string" || !content.trim())
61
+ throw new PlicoError("message.invalid", "Message content must be a nonempty string.");
62
+ const startRun = options.startRun !== false;
63
+ const context = readMetadata(options.context, "context") ?? deps.context;
64
+ const { provider } = deps;
65
+ if (startRun && !provider)
66
+ throw new PlicoError("provider.unavailable", "Configure a model provider before sending a message.");
67
+ if (startRun &&
68
+ (!store.storageIdentity || store.storageIdentity !== deps.eventStore.storageIdentity))
69
+ throw new PlicoError("threads.store_mismatch", "Thread and run stores must use the same database.");
70
+ const runId = startRun ? `run-${randomUUID()}` : undefined;
71
+ const providerKey = deps.providerAccountKey ?? deps.providerRecoveryKey;
72
+ let message;
73
+ try {
74
+ message = await store.addMessage(thread.id, content, runId, providerKey
75
+ ? {
76
+ providerKey,
77
+ projectRoot: resolve(deps.projectRoot),
78
+ ...(context === undefined ? {} : { context }),
79
+ }
80
+ : undefined);
81
+ }
82
+ catch (error) {
83
+ if (error instanceof ThreadBusyError)
84
+ throw new PlicoError("thread.busy", error.message);
85
+ throw error;
86
+ }
87
+ if (!message)
88
+ throw new PlicoError("thread.not_found", `Unknown thread ID: ${thread.id}`);
89
+ if (provider && runId) {
90
+ const history = (await store.getMessages(thread.id)).filter((entry) => entry.id !== message.id);
91
+ await startThreadRun(deps, {
92
+ runId,
93
+ threadId: thread.id,
94
+ ...(thread.metadata === undefined ? {} : { metadata: thread.metadata }),
95
+ ...(context === undefined ? {} : { context }),
96
+ content,
97
+ history: history.map(({ role, content }) => ({ role, content })),
98
+ });
99
+ }
100
+ return message;
101
+ }
102
+ async function startThreadRun(deps, run) {
103
+ let resolveStarted;
104
+ let rejectStarted;
105
+ const started = new Promise((resolve, reject) => {
106
+ resolveStarted = resolve;
107
+ rejectStarted = reject;
108
+ });
109
+ void runProject(deps.projectRoot, {
110
+ runId: run.runId,
111
+ threadId: run.threadId,
112
+ ...(run.metadata === undefined ? {} : { metadata: run.metadata }),
113
+ ...(run.context === undefined ? {} : { context: run.context }),
114
+ message: run.content,
115
+ history: run.history,
116
+ ...(deps.provider ? { provider: deps.provider } : {}),
117
+ eventStore: deps.eventStore,
118
+ engine: deps.engine,
119
+ ...(deps.providerRecoveryKey ? { providerRecoveryKey: deps.providerRecoveryKey } : {}),
120
+ onStarted: resolveStarted,
121
+ }).catch(async (error) => {
122
+ try {
123
+ await finishFailedThreadRun(run.runId, run.threadId, deps.projectRoot, deps.engine, deps.eventStore, error, run.metadata);
124
+ }
125
+ catch (settleError) {
126
+ console.error("Could not record failed thread run", settleError);
127
+ }
128
+ finally {
129
+ rejectStarted(error);
130
+ }
131
+ });
132
+ await started;
133
+ }