@plico-ai/server 0.0.0-stage → 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 (78) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +10 -2
  4. package/dist/api.d.ts +32 -0
  5. package/dist/api.js +87 -0
  6. package/dist/app/assemble.d.ts +10 -0
  7. package/dist/app/assemble.js +49 -0
  8. package/dist/app/errors.d.ts +6 -0
  9. package/dist/app/errors.js +24 -0
  10. package/dist/app/events.d.ts +9 -0
  11. package/dist/app/events.js +52 -0
  12. package/dist/app/metadata.d.ts +4 -0
  13. package/dist/app/metadata.js +24 -0
  14. package/dist/app/runs.d.ts +31 -0
  15. package/dist/app/runs.js +81 -0
  16. package/dist/app/scope.d.ts +8 -0
  17. package/dist/app/scope.js +18 -0
  18. package/dist/app/threads.d.ts +15 -0
  19. package/dist/app/threads.js +133 -0
  20. package/dist/app/types.d.ts +103 -0
  21. package/dist/app/types.js +1 -0
  22. package/dist/body.d.ts +4 -0
  23. package/dist/body.js +54 -0
  24. package/dist/create-plico.d.ts +18 -0
  25. package/dist/create-plico.js +75 -0
  26. package/dist/errors.d.ts +7 -0
  27. package/dist/errors.js +19 -0
  28. package/dist/index.d.ts +6 -0
  29. package/dist/index.js +3 -0
  30. package/dist/listener.d.ts +6 -0
  31. package/dist/listener.js +8 -0
  32. package/dist/mount.d.ts +32 -0
  33. package/dist/mount.js +34 -0
  34. package/dist/origin-guard.d.ts +15 -0
  35. package/dist/origin-guard.js +39 -0
  36. package/dist/project.d.ts +2 -0
  37. package/dist/project.js +10 -0
  38. package/dist/recovery.d.ts +19 -0
  39. package/dist/recovery.js +84 -0
  40. package/dist/responses.d.ts +1 -0
  41. package/dist/responses.js +6 -0
  42. package/dist/routes/artifacts.d.ts +2 -0
  43. package/dist/routes/artifacts.js +165 -0
  44. package/dist/routes/eval.d.ts +2 -0
  45. package/dist/routes/eval.js +38 -0
  46. package/dist/routes/health.d.ts +2 -0
  47. package/dist/routes/health.js +8 -0
  48. package/dist/routes/index.d.ts +11 -0
  49. package/dist/routes/index.js +72 -0
  50. package/dist/routes/metadata-query.d.ts +4 -0
  51. package/dist/routes/metadata-query.js +13 -0
  52. package/dist/routes/project.d.ts +2 -0
  53. package/dist/routes/project.js +23 -0
  54. package/dist/routes/readiness.d.ts +2 -0
  55. package/dist/routes/readiness.js +17 -0
  56. package/dist/routes/runs.d.ts +2 -0
  57. package/dist/routes/runs.js +82 -0
  58. package/dist/routes/threads.d.ts +2 -0
  59. package/dist/routes/threads.js +60 -0
  60. package/dist/routes/types.d.ts +30 -0
  61. package/dist/routes/types.js +1 -0
  62. package/dist/script.d.ts +8 -0
  63. package/dist/script.js +35 -0
  64. package/dist/serve-static.d.ts +2 -0
  65. package/dist/serve-static.js +37 -0
  66. package/dist/server.d.ts +4 -0
  67. package/dist/server.js +25 -0
  68. package/dist/sse.d.ts +3 -0
  69. package/dist/sse.js +12 -0
  70. package/dist/stream.d.ts +13 -0
  71. package/dist/stream.js +58 -0
  72. package/dist/thread-failure.d.ts +7 -0
  73. package/dist/thread-failure.js +42 -0
  74. package/dist/thread-titles.d.ts +11 -0
  75. package/dist/thread-titles.js +37 -0
  76. package/dist/types.d.ts +12 -0
  77. package/dist/types.js +1 -0
  78. package/package.json +47 -3
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
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,3 +1,11 @@
1
- # Temporary Holding Version
1
+ # @plico-ai/server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The thin native HTTP API over the Plico runtime and event store: runs, threads, signals, approvals, cancel, artifacts, events and readiness.
4
+
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;