@openlegion/platform 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 (120) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +1189 -2
  3. package/dist/body.d.ts +9 -0
  4. package/dist/body.js +28 -0
  5. package/dist/chat-history.d.ts +53 -0
  6. package/dist/chat-history.js +11 -0
  7. package/dist/client.d.ts +217 -0
  8. package/dist/client.js +367 -0
  9. package/dist/core.d.ts +47 -0
  10. package/dist/core.js +1 -0
  11. package/dist/crypto.d.ts +25 -0
  12. package/dist/crypto.js +81 -0
  13. package/dist/errors.d.ts +111 -0
  14. package/dist/errors.js +134 -0
  15. package/dist/events.d.ts +131 -0
  16. package/dist/events.js +5 -0
  17. package/dist/generated/api.d.ts +5505 -0
  18. package/dist/generated/api.js +446 -0
  19. package/dist/handler.d.ts +201 -0
  20. package/dist/handler.js +682 -0
  21. package/dist/index.d.ts +24 -0
  22. package/dist/index.js +12 -0
  23. package/dist/kit-agents.d.ts +95 -0
  24. package/dist/kit-agents.js +280 -0
  25. package/dist/kit-codes.d.ts +279 -0
  26. package/dist/kit-codes.js +44 -0
  27. package/dist/kit-connections.d.ts +21 -0
  28. package/dist/kit-connections.js +189 -0
  29. package/dist/kit-files.d.ts +8 -0
  30. package/dist/kit-files.js +117 -0
  31. package/dist/kit-model-keys.d.ts +8 -0
  32. package/dist/kit-model-keys.js +86 -0
  33. package/dist/kit-threads.d.ts +3 -0
  34. package/dist/kit-threads.js +92 -0
  35. package/dist/kit-tools.d.ts +21 -0
  36. package/dist/kit-tools.js +47 -0
  37. package/dist/kit.d.ts +130 -0
  38. package/dist/kit.js +155 -0
  39. package/dist/mcp-server.d.ts +27 -0
  40. package/dist/mcp-server.js +166 -0
  41. package/dist/next.d.ts +24 -0
  42. package/dist/next.js +6 -0
  43. package/dist/ol-signed.d.ts +82 -0
  44. package/dist/ol-signed.js +115 -0
  45. package/dist/react/add-server.d.ts +90 -0
  46. package/dist/react/add-server.js +183 -0
  47. package/dist/react/agent-chat.d.ts +925 -0
  48. package/dist/react/agent-chat.js +1917 -0
  49. package/dist/react/agent-editor.d.ts +133 -0
  50. package/dist/react/agent-editor.js +222 -0
  51. package/dist/react/agent-kit.d.ts +160 -0
  52. package/dist/react/agent-kit.js +279 -0
  53. package/dist/react/agent-list.d.ts +247 -0
  54. package/dist/react/agent-list.js +248 -0
  55. package/dist/react/approval-card.d.ts +272 -0
  56. package/dist/react/approval-card.js +372 -0
  57. package/dist/react/artifact-card.d.ts +38 -0
  58. package/dist/react/artifact-card.js +39 -0
  59. package/dist/react/avatar.d.ts +21 -0
  60. package/dist/react/avatar.js +33 -0
  61. package/dist/react/card-ledger.d.ts +30 -0
  62. package/dist/react/card-ledger.js +49 -0
  63. package/dist/react/chat-timing.d.ts +121 -0
  64. package/dist/react/chat-timing.js +229 -0
  65. package/dist/react/computer-view.d.ts +309 -0
  66. package/dist/react/computer-view.js +543 -0
  67. package/dist/react/computer-viewer.d.ts +175 -0
  68. package/dist/react/computer-viewer.js +555 -0
  69. package/dist/react/computer-wire.d.ts +178 -0
  70. package/dist/react/computer-wire.js +244 -0
  71. package/dist/react/connect-button.d.ts +145 -0
  72. package/dist/react/connect-button.js +212 -0
  73. package/dist/react/connection-request.d.ts +16 -0
  74. package/dist/react/connection-request.js +18 -0
  75. package/dist/react/connections-list.d.ts +90 -0
  76. package/dist/react/connections-list.js +76 -0
  77. package/dist/react/errors.d.ts +250 -0
  78. package/dist/react/errors.js +146 -0
  79. package/dist/react/files.d.ts +41 -0
  80. package/dist/react/files.js +78 -0
  81. package/dist/react/index.d.ts +35 -0
  82. package/dist/react/index.js +26 -0
  83. package/dist/react/limit-words.d.ts +80 -0
  84. package/dist/react/limit-words.js +53 -0
  85. package/dist/react/markdown.d.ts +42 -0
  86. package/dist/react/markdown.js +56 -0
  87. package/dist/react/md-parse.d.ts +106 -0
  88. package/dist/react/md-parse.js +638 -0
  89. package/dist/react/model-keys-card.d.ts +94 -0
  90. package/dist/react/model-keys-card.js +123 -0
  91. package/dist/react/reload.d.ts +211 -0
  92. package/dist/react/reload.js +339 -0
  93. package/dist/react/reveal.d.ts +17 -0
  94. package/dist/react/reveal.js +22 -0
  95. package/dist/react/schedule-editor.d.ts +107 -0
  96. package/dist/react/schedule-editor.js +172 -0
  97. package/dist/react/schedule-time.d.ts +66 -0
  98. package/dist/react/schedule-time.js +90 -0
  99. package/dist/react/styles.css +1274 -0
  100. package/dist/react/transport.d.ts +49 -0
  101. package/dist/react/transport.js +380 -0
  102. package/dist/react/use-connections.d.ts +155 -0
  103. package/dist/react/use-connections.js +231 -0
  104. package/dist/react/use-model-keys.d.ts +47 -0
  105. package/dist/react/use-model-keys.js +57 -0
  106. package/dist/react/use-threads.d.ts +63 -0
  107. package/dist/react/use-threads.js +73 -0
  108. package/dist/react/vault-form.d.ts +92 -0
  109. package/dist/react/vault-form.js +151 -0
  110. package/dist/schema.d.ts +47 -0
  111. package/dist/schema.js +16 -0
  112. package/dist/secrets.d.ts +15 -0
  113. package/dist/secrets.js +18 -0
  114. package/dist/stream.d.ts +129 -0
  115. package/dist/stream.js +192 -0
  116. package/dist/testing.d.ts +33 -0
  117. package/dist/testing.js +40 -0
  118. package/dist/webhooks.d.ts +31 -0
  119. package/dist/webhooks.js +72 -0
  120. package/package.json +85 -3
@@ -0,0 +1,117 @@
1
+ import { readCapped } from "./body.js";
2
+ export const MAX_KIT_ARTIFACT_TEXT_BYTES = 256 * 1024;
3
+ const TEXT_PREVIEW_TYPES = new Set(["text/markdown", "text/plain"]);
4
+ export const MAX_KIT_FILE_BYTES = 4 * 1024 * 1024;
5
+ const THREAD = /^thr_[0-9A-Za-z]{1,64}$/;
6
+ const ARTIFACT = /^art_[0-9A-Za-z]{1,64}$/;
7
+ const MIME = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,63}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,63}$/;
8
+ export function createKitFileRoutes(ctx) {
9
+ const { error } = ctx;
10
+ const json = (body, status = 200) => Response.json(body, { status, headers: { "cache-control": "no-store" } });
11
+ async function withScope(req, where, run) {
12
+ const s = await ctx.scope(req);
13
+ if (s instanceof Response)
14
+ return s;
15
+ try {
16
+ return await run(ctx.client(s));
17
+ }
18
+ catch (err) {
19
+ return ctx.upstream(err, where);
20
+ }
21
+ }
22
+ async function upload(req) {
23
+ const q = new URL(req.url).searchParams;
24
+ const thread = q.get("thread") ?? "";
25
+ const name = (q.get("name") ?? "").trim();
26
+ if (!THREAD.test(thread))
27
+ return error(400, "invalid_thread", "thread must be the thread's id (thr_…).");
28
+ if (name === "" || name.length > 200)
29
+ return error(400, "invalid_file_name", "name is the file's name, 1 to 200 characters.");
30
+ const type = (req.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
31
+ if (!MIME.test(type))
32
+ return error(400, "invalid_file_type", "Content-Type must name the file's type.");
33
+ return withScope(req, "files", async (ol) => {
34
+ const bytes = await readCapped(req, MAX_KIT_FILE_BYTES);
35
+ if (bytes === null)
36
+ return error(413, "body_too_large", "A file can be at most 4 MB.");
37
+ const f = await ol.files.create({ thread, name, type, body: bytes }, { maxRetries: 0 });
38
+ return json({ object: "file", id: f.id, name: f.name, mime: f.mime, size_bytes: f.size_bytes }, 201);
39
+ });
40
+ }
41
+ async function listed(ol, thread) {
42
+ const page = await ol.artifacts.list({ thread, limit: 100 });
43
+ return page.data.map((a) => ({ object: "artifact", id: a.id, name: a.name, mime: a.mime, size_bytes: a.size_bytes, created: a.created, tainted: a.tainted }));
44
+ }
45
+ async function list(req) {
46
+ const thread = new URL(req.url).searchParams.get("thread") ?? "";
47
+ if (!THREAD.test(thread))
48
+ return error(400, "invalid_thread", "thread must be the thread's id (thr_…).");
49
+ return withScope(req, "artifacts", async (ol) => json({ object: "list", data: await listed(ol, thread), has_more: false }));
50
+ }
51
+ async function download(req, id) {
52
+ const thread = new URL(req.url).searchParams.get("thread") ?? "";
53
+ if (!THREAD.test(thread))
54
+ return error(400, "invalid_thread", "thread must be the thread's id (thr_…).");
55
+ return withScope(req, "artifact download", async (ol) => {
56
+ if (!(await listed(ol, thread)).some((a) => a.id === id))
57
+ return error(404, "resource_missing", "No such file in this conversation.");
58
+ const a = await ol.artifacts.retrieve(id);
59
+ if (!a.url)
60
+ return error(503, "download_unavailable", "The file can't be downloaded right now. Try again in a moment.");
61
+ return new Response(null, { status: 302, headers: { location: a.url, "cache-control": "no-store" } });
62
+ });
63
+ }
64
+ async function text(req, id) {
65
+ const thread = new URL(req.url).searchParams.get("thread") ?? "";
66
+ if (!THREAD.test(thread))
67
+ return error(400, "invalid_thread", "thread must be the thread's id (thr_…).");
68
+ return withScope(req, "artifact text", async (ol) => {
69
+ const listedOne = (await listed(ol, thread)).find((a) => a.id === id);
70
+ if (!listedOne)
71
+ return error(404, "resource_missing", "No such file in this conversation.");
72
+ if (!TEXT_PREVIEW_TYPES.has(listedOne.mime.split(";")[0].trim().toLowerCase()))
73
+ return error(415, "preview_not_text", "Only a Markdown or plain-text file has a text preview.");
74
+ const tooLarge = () => error(413, "preview_too_large", "The file is too large to preview. Download it instead.");
75
+ if (listedOne.size_bytes > MAX_KIT_ARTIFACT_TEXT_BYTES)
76
+ return tooLarge();
77
+ const a = await ol.artifacts.retrieve(id);
78
+ const unavailable = () => error(503, "download_unavailable", "The file can't be read right now. Try again in a moment.");
79
+ if (!a.url)
80
+ return unavailable();
81
+ let stored;
82
+ try {
83
+ stored = await ol.transport.config.fetch(a.url, { method: "GET" });
84
+ }
85
+ catch {
86
+ return unavailable();
87
+ }
88
+ if (!stored.ok) {
89
+ await stored.body?.cancel().catch(() => undefined);
90
+ return unavailable();
91
+ }
92
+ const bytes = await readCapped(stored, MAX_KIT_ARTIFACT_TEXT_BYTES);
93
+ if (bytes === null)
94
+ return tooLarge();
95
+ return new Response(bytes, { status: 200, headers: { "content-type": "text/plain; charset=utf-8", "x-content-type-options": "nosniff", "cache-control": "no-store" } });
96
+ });
97
+ }
98
+ return async (route, req) => {
99
+ if (route === "/files")
100
+ return req.method === "POST" ? upload(req) : error(405, "method_not_allowed", "POST only.");
101
+ if (route === "/artifacts")
102
+ return req.method === "GET" ? list(req) : error(405, "method_not_allowed", "GET only.");
103
+ const words = /^\/artifacts\/([^/]+)\/text$/.exec(route);
104
+ if (words) {
105
+ if (req.method !== "GET")
106
+ return error(405, "method_not_allowed", "GET only.");
107
+ return ARTIFACT.test(words[1]) ? text(req, words[1]) : error(400, "invalid_artifact", "Not an artifact id (art_…).");
108
+ }
109
+ const dl = /^\/artifacts\/([^/]+)\/download$/.exec(route);
110
+ if (dl) {
111
+ if (req.method !== "GET")
112
+ return error(405, "method_not_allowed", "GET only.");
113
+ return ARTIFACT.test(dl[1]) ? download(req, dl[1]) : error(400, "invalid_artifact", "Not an artifact id (art_…).");
114
+ }
115
+ return null;
116
+ };
117
+ }
@@ -0,0 +1,8 @@
1
+ import type { KitRouteContext } from "./kit-agents.ts";
2
+ /** The routes, as one dispatcher: the response for `route`, or null when the route isn't one of these. */
3
+ export declare function createKitModelKeyRoutes<Scope extends {
4
+ workspace: string;
5
+ }>(ctx: KitRouteContext<Scope>, opts?: {
6
+ allow?: (who: Scope, req: Request) => boolean | Promise<boolean>;
7
+ onError?: (err: unknown, where: string) => void;
8
+ }): (route: string, req: Request) => Promise<Response | null>;
@@ -0,0 +1,86 @@
1
+ import { OpenLegionError } from "./errors.js";
2
+ const VENDORS = ["anthropic", "openai"];
3
+ const isVendor = (v) => typeof v === "string" && VENDORS.includes(v);
4
+ const MAX_BODY_BYTES = 2 * 1024;
5
+ const PASSED = new Set(["model_keys_not_allowed", "model_key_malformed", "model_key_invalid", "model_key_model_missing", "model_key_unchecked", "model_key_checks_exceeded", "insufficient_role"]);
6
+ function retryAfter(err) {
7
+ const v = err.headers?.get("retry-after");
8
+ return v && /^\d{1,6}$/.test(v) ? { retry_after: Number(v) } : {};
9
+ }
10
+ function keyForBrowser(k) {
11
+ return { object: "model_key", vendor: k.vendor, tail: k.tail, checked_at: k.checked_at, in_use: k.in_use };
12
+ }
13
+ const json = (body, status = 200) => Response.json(body, { status, headers: { "cache-control": "no-store" } });
14
+ export function createKitModelKeyRoutes(ctx, opts = {}) {
15
+ const { error } = ctx;
16
+ async function gate(req) {
17
+ if (!opts.allow)
18
+ return "open";
19
+ const s = await ctx.scope(req);
20
+ if (s instanceof Response)
21
+ return null;
22
+ try {
23
+ return (await opts.allow(s, req)) === true ? s : null;
24
+ }
25
+ catch (err) {
26
+ opts.onError?.(err, "allowModelKeys");
27
+ return null;
28
+ }
29
+ }
30
+ async function withScope(req, where, run, known) {
31
+ const s = known === "open" ? await ctx.scope(req) : known;
32
+ if (s instanceof Response)
33
+ return s;
34
+ try {
35
+ return await run(ctx.client(s));
36
+ }
37
+ catch (err) {
38
+ if (err instanceof OpenLegionError && err.code !== null && err.code !== undefined && PASSED.has(err.code)) {
39
+ return error(err.status ?? 400, err.code, err.message, { type: err.type, ...(err.param ? { param: err.param } : {}), ...retryAfter(err) });
40
+ }
41
+ return ctx.upstream(err, where);
42
+ }
43
+ }
44
+ return async (route, req) => {
45
+ const one = /^\/model_keys\/([^/]+)$/.exec(route);
46
+ if (route !== "/model_keys" && !one)
47
+ return null;
48
+ const who = await gate(req);
49
+ if (who === null)
50
+ return null;
51
+ if (route === "/model_keys") {
52
+ if (req.method === "GET") {
53
+ return withScope(req, "model_keys", async (ol) => {
54
+ const r = await ol.modelKeys.list();
55
+ return json({ object: "model_keys", allowed: r.allowed, keys: r.data.map(keyForBrowser) });
56
+ }, who);
57
+ }
58
+ if (req.method !== "POST")
59
+ return error(405, "method_not_allowed", "GET or POST only.");
60
+ return withScope(req, "model_keys", async (ol) => {
61
+ const parsed = await ctx.readJson(req, MAX_BODY_BYTES);
62
+ if (!parsed.ok)
63
+ return parsed.response;
64
+ const b = parsed.value;
65
+ if (!b || typeof b !== "object" || Array.isArray(b))
66
+ return error(400, "invalid_body", "The body must be a JSON object.");
67
+ if (!isVendor(b["vendor"]))
68
+ return error(400, "invalid_body", "vendor is anthropic or openai.");
69
+ const key = b["key"];
70
+ if (typeof key !== "string" || key.trim().length === 0 || key.length > 1024)
71
+ return error(400, "invalid_body", "key is the key, a string of at most 1,024 characters.");
72
+ const saved = await ol.modelKeys.create({ vendor: b["vendor"], key: key.trim() }, { maxRetries: 0 });
73
+ return json({ ...keyForBrowser(saved), replaced: saved.replaced ? { vendor: saved.replaced.vendor, tail: saved.replaced.tail } : null });
74
+ }, who);
75
+ }
76
+ const vendor = one[1];
77
+ if (!isVendor(vendor))
78
+ return error(400, "invalid_vendor", "vendor is anthropic or openai.");
79
+ if (req.method !== "DELETE")
80
+ return error(405, "method_not_allowed", "DELETE only.");
81
+ return withScope(req, "model_key", async (ol) => {
82
+ await ol.modelKeys.delete(vendor);
83
+ return json({ object: "model_key", vendor, deleted: true });
84
+ }, who);
85
+ };
86
+ }
@@ -0,0 +1,3 @@
1
+ import { type KitRouteContext } from "./kit-agents.ts";
2
+ /** The routes, as one dispatcher: the response for `route`, or null when the route isn't one of these. */
3
+ export declare function createKitThreadRoutes<Scope>(ctx: KitRouteContext<Scope>): (route: string, req: Request) => Promise<Response | null>;
@@ -0,0 +1,92 @@
1
+ import { OpenLegionError } from "./errors.js";
2
+ import { forBrowser, idempotencyFor } from "./kit-agents.js";
3
+ const MAX_THREAD_BODY_BYTES = 1024;
4
+ const AGENT_ID = /^agt_[0-9A-Za-z]{1,64}$/;
5
+ const THREAD_ID = /^thr_[0-9A-Za-z]{1,64}$/;
6
+ const MESSAGE_ID = /^msg_[0-9A-Za-z]{1,64}$/;
7
+ function withSeen(body) {
8
+ if (!body || typeof body !== "object" || Array.isArray(body))
9
+ return body;
10
+ const o = body;
11
+ if (o["object"] === "thread")
12
+ return { ...o, seen_through: typeof o["seen_through"] === "string" ? o["seen_through"] : null, unseen: typeof o["unseen"] === "number" && Number.isFinite(o["unseen"]) ? o["unseen"] : null };
13
+ if (o["object"] === "list" && Array.isArray(o["data"]))
14
+ return { ...o, data: o["data"].map(withSeen) };
15
+ return body;
16
+ }
17
+ const json = (body, status = 200) => Response.json(withSeen(forBrowser(body)), { status, headers: { "cache-control": "no-store" } });
18
+ export function createKitThreadRoutes(ctx) {
19
+ const { error } = ctx;
20
+ async function withScope(req, run) {
21
+ const s = await ctx.scope(req);
22
+ if (s instanceof Response)
23
+ return s;
24
+ try {
25
+ return await run(ctx.client(s), s);
26
+ }
27
+ catch (err) {
28
+ const status = err instanceof OpenLegionError ? err.status : null;
29
+ if (err instanceof OpenLegionError && status !== null && status >= 400 && status < 500 && status !== 401 && (status !== 403 || err.code === "insufficient_role")) {
30
+ return error(status, err.code, err.message, { type: err.type, param: err.param });
31
+ }
32
+ return ctx.upstream(err, "threads");
33
+ }
34
+ }
35
+ return async (route, req) => {
36
+ const seen = /^\/threads\/([^/]+)\/seen$/.exec(route);
37
+ if (seen) {
38
+ if (req.method !== "POST")
39
+ return error(405, "method_not_allowed", "POST only.");
40
+ const thread = seen[1];
41
+ if (!THREAD_ID.test(thread))
42
+ return error(400, "invalid_thread", "Not a thread id (thr_…).");
43
+ return withScope(req, async (ol) => {
44
+ const parsed = await ctx.readJson(req, MAX_THREAD_BODY_BYTES);
45
+ if (!parsed.ok)
46
+ return parsed.response;
47
+ const b = parsed.value;
48
+ if (!b || typeof b !== "object" || Array.isArray(b) || typeof b["message"] !== "string" || !MESSAGE_ID.test(b["message"])) {
49
+ return error(400, "invalid_body", "message is the id of the newest message the person has seen (msg_…).");
50
+ }
51
+ return json(await ol.threads.seen(thread, { message: b["message"] }));
52
+ });
53
+ }
54
+ if (route !== "/threads")
55
+ return null;
56
+ if (req.method === "GET") {
57
+ const url = new URL(req.url);
58
+ const q = { order: "last_message_at" };
59
+ const agent = url.searchParams.get("agent");
60
+ if (agent !== null) {
61
+ if (!AGENT_ID.test(agent))
62
+ return error(400, "invalid_agent", "agent must be an agent id (agt_…).");
63
+ q.agent = agent;
64
+ }
65
+ const limit = Number(url.searchParams.get("limit"));
66
+ if (Number.isInteger(limit) && limit >= 1 && limit <= 100)
67
+ q.limit = limit;
68
+ const after = url.searchParams.get("starting_after");
69
+ if (after !== null && THREAD_ID.test(after))
70
+ q.starting_after = after;
71
+ return withScope(req, async (ol) => json(await ol.threads.list(q)));
72
+ }
73
+ if (req.method !== "POST")
74
+ return error(405, "method_not_allowed", "GET or POST only.");
75
+ return withScope(req, async (ol, s) => {
76
+ const parsed = await ctx.readJson(req, MAX_THREAD_BODY_BYTES);
77
+ if (!parsed.ok)
78
+ return parsed.response;
79
+ const b = parsed.value;
80
+ if (!b || typeof b !== "object" || Array.isArray(b))
81
+ return error(400, "invalid_body", "The body must be a JSON object.");
82
+ if (typeof b["agent"] !== "string" || !AGENT_ID.test(b["agent"]))
83
+ return error(400, "invalid_agent", "agent is the agent's id (agt_…).");
84
+ if (b["home"] !== undefined && typeof b["home"] !== "boolean")
85
+ return error(400, "invalid_body", "home is true or false.");
86
+ if (b["ongoing"] !== undefined && typeof b["ongoing"] !== "boolean")
87
+ return error(400, "invalid_body", "ongoing is true or false.");
88
+ const created = await ol.threads.create({ agent: b["agent"], ...(typeof b["home"] === "boolean" ? { home: b["home"] } : {}), ...(typeof b["ongoing"] === "boolean" ? { ongoing: b["ongoing"] } : {}) }, await idempotencyFor(req, ctx.subjectOf(s)));
89
+ return json(created, created.lastResponse.status === 200 ? 200 : 201);
90
+ });
91
+ };
92
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * THE BUILT-IN TOOLS AN END USER CAN MEET, IN WORDS: what `<AgentChat>` writes while one of OpenLegion's own tools
3
+ * runs, once it has, and when it could not but the reply went on (a quiet step, not an alarm: "Couldn't open a
4
+ * page"). Keyed by the name the model uses (the tool's id with `_` for `.`). A label of yours for one
5
+ * (`labels.tools`) goes through your `toolCalling`/`toolDone`/`toolSkipped`/… sentences instead. EVERY TOOL A
6
+ * TEMPLATE MAY LIST IS HERE (the docs' tools page test holds the two equal), so none is drawn as its id in words. A
7
+ * tool that is not here, which is one of yours, is drawn as its name in words, in those same sentences.
8
+ *
9
+ * One list, read by the chat and printed by the docs' platform tools page.
10
+ */
11
+ export declare const KIT_TOOL_LINES: Readonly<Record<string, readonly [doing: string, done: string, couldNot: string]>>;
12
+ /**
13
+ * `agent.schedule` once it is done, by what the call says: once, or again and again (a cron). A one-off can be a
14
+ * reminder or work ("send the report tomorrow at 9"), so the words claim neither.
15
+ */
16
+ export declare const KIT_SCHEDULE_DONE: Readonly<Record<"once" | "repeats", string>>;
17
+ /**
18
+ * The tools whose call draws a card in the chat, whatever `showToolCalls` says, and which card. The card is the
19
+ * step: it is drawn in place of the call's second line, which is written only when there is no card.
20
+ */
21
+ export declare const KIT_TOOL_CARDS: Readonly<Record<string, string>>;
@@ -0,0 +1,47 @@
1
+ export const KIT_TOOL_LINES = {
2
+ web_search: ["Searching the web", "Searched the web", "Couldn't search the web"],
3
+ web_fetch: ["Reading a page", "Read a page", "Couldn't open a page"],
4
+ files_read: ["Reading a file", "Read a file", "Couldn't read a file"],
5
+ files_read_attachment: ["Reading your attachment", "Read your attachment", "Couldn't read your attachment"],
6
+ files_write: ["Writing a file", "Wrote a file", "Couldn't write a file"],
7
+ files_list: ["Listing files", "Listed files", "Couldn't list files"],
8
+ files_delete: ["Deleting a file", "Deleted a file", "Couldn't delete a file"],
9
+ files_deliver: ["Delivering a file", "Delivered a file", "Couldn't deliver a file"],
10
+ sandbox_run: ["Computing with code", "Ran code", "Couldn't run code"],
11
+ sandbox_code_run: ["Computing with code", "Ran code", "Couldn't run code"],
12
+ email_send: ["Sending an email", "Sent an email", "Couldn't send an email"],
13
+ memory_search: ["Searching its memory", "Searched its memory", "Couldn't search its memory"],
14
+ browser_open: ["Opening a website", "Opened a website", "Couldn't open a website"],
15
+ browser_act: ["Using a website", "Used a website", "Couldn't use a website"],
16
+ browser_snapshot: ["Reading the page", "Read the page", "Couldn't read the page"],
17
+ browser_close: ["Closing the browser", "Closed the browser", "Couldn't close the browser"],
18
+ browser_fill_credential: ["Filling in your saved login", "Filled in your saved login", "Couldn't fill in your saved login"],
19
+ agent_schedule: ["Scheduling it", "Scheduled", "Couldn't schedule it"],
20
+ agent_note_to_user: ["Leaving you a note", "Left you a note", "Couldn't leave you a note"],
21
+ agent_wait: ["Pausing briefly", "Paused briefly", "Couldn't pause"],
22
+ agent_learn: ["Noting a lesson for next time", "Noted a lesson for next time", "Couldn't note a lesson"],
23
+ memory_timeline: ["Looking back through its memory", "Looked back through its memory", "Couldn't look back through its memory"],
24
+ memory_write_candidate: ["Noting something to remember", "Noted something to remember", "Couldn't note something to remember"],
25
+ artifacts_list: ["Listing delivered files", "Listed delivered files", "Couldn't list delivered files"],
26
+ artifacts_read: ["Reading a delivered file", "Read a delivered file", "Couldn't read a delivered file"],
27
+ team_hand_off: ["Handing a task to another agent", "Handed a task to another agent", "Couldn't hand the task to another agent"],
28
+ team_ask: ["Asking another agent", "Asked another agent", "Couldn't ask another agent"],
29
+ team_answer: ["Answering another agent", "Answered another agent", "Couldn't answer another agent"],
30
+ team_status: ["Sending a progress update", "Sent a progress update", "Couldn't send a progress update"],
31
+ team_complete: ["Reporting the task done", "Reported the task done", "Couldn't report the task done"],
32
+ team_delegate: ["Starting a helper for one task", "Started a helper for one task", "Couldn't start a helper"],
33
+ vault_request_credential: ["Asking to use a saved key", "Asked to use a saved key", "Couldn't use a saved key"],
34
+ vault_list: ["Checking which saved keys it may use", "Checked which saved keys it may use", "Couldn't check its saved keys"],
35
+ schedule_admin_list: ["Checking its schedules", "Checked its schedules", "Couldn't check its schedules"],
36
+ schedule_admin_cancel: ["Cancelling a schedule", "Cancelled a schedule", "Couldn't cancel a schedule"],
37
+ skills_read: ["Reading one of its skills", "Read one of its skills", "Couldn't read one of its skills"],
38
+ skills_read_file: ["Reading a skill's file", "Read a skill's file", "Couldn't read a skill's file"],
39
+ skills_draft: ["Drafting a skill", "Drafted a skill", "Couldn't draft a skill"],
40
+ connections_request: ["Checking your connected apps", "Checked your connected apps", "Couldn't check your connected apps"],
41
+ vault_ask_user: ["Asking you to save a key", "Asked you to save a key", "Couldn't ask you to save a key"],
42
+ };
43
+ export const KIT_SCHEDULE_DONE = { once: "Scheduled for later", repeats: "Scheduled to repeat" };
44
+ export const KIT_TOOL_CARDS = {
45
+ vault_ask_user: "A secure form for the login or key (<VaultSecretForm>), in place of the second line until it is saved.",
46
+ connections_request: "A Connect button for the app (<ConnectButton>), in place of the second line when the app is not connected yet.",
47
+ };
package/dist/kit.d.ts ADDED
@@ -0,0 +1,130 @@
1
+ import type { TemplateSpec } from "./generated/api.ts";
2
+ import type { OpenLegionContext } from "./ol-signed.ts";
3
+ import { type InferOutput, type StandardSchemaWithJSON } from "./schema.ts";
4
+ export type Trust = "tool_verified" | "web_low";
5
+ export type Effect = "read" | "draft" | "write" | "egress";
6
+ /** What a tool knows about the call: the signed context, with the customer and the action always set. */
7
+ export interface ToolContext extends OpenLegionContext {
8
+ /** Your customer id for the workspace: scope every read and write by it. */
9
+ external_ref: string;
10
+ workspace: string;
11
+ /** `act_…`: the same when OpenLegion retries the same action. Use it as your idempotency key. */
12
+ action: string;
13
+ /** The verified request. */
14
+ request: Request;
15
+ /** Aborts when OpenLegion gives up on the call. */
16
+ signal: AbortSignal;
17
+ }
18
+ export interface ToolDefinition<S extends StandardSchemaWithJSON = StandardSchemaWithJSON, R = unknown> {
19
+ /** What the tool does, for the model. Frozen when the connector is pinned. At most 8 KB. */
20
+ description: string;
21
+ /** The arguments, e.g. `z.object({ order: z.string() })`. Any Standard Schema with JSON Schema. */
22
+ input: S;
23
+ trust: Trust;
24
+ effect: Effect;
25
+ /**
26
+ * The tool's name in a person's words, e.g. "Email you". It is what a person sees for this tool: the title of
27
+ * the approval card when a call waits for them (with a "?"), unless you give `approvalTitle`. Not for the
28
+ * model: that is `description`. Frozen when the connector is pinned.
29
+ */
30
+ title?: string;
31
+ /** Hold every call for a person's approval (the template's policy envelope says `held`). Default false. */
32
+ requiresApproval?: boolean;
33
+ /**
34
+ * The sentence a person reads as the approval card's title when a call waits for them, e.g.
35
+ * `Email you "{subject}"?`. Each `{name}` is replaced by that field of the call's input (text or a number, at
36
+ * most 80 characters); a field the call left out is replaced by nothing. At most 200 characters. Without it
37
+ * the title is `title` with a "?", or the tool's name in words.
38
+ */
39
+ approvalTitle?: string;
40
+ /**
41
+ * The fields of the input a person sees first on the approval card, in this order, e.g. `["message"]` when
42
+ * `approvalTitle` already says the subject. Every other field stays on the card, behind its details: nothing the
43
+ * agent chose is hidden. `[]` leaves the sentence alone up front. Each name must be a property of `input`.
44
+ * Without it every field is up front, in the input's order.
45
+ */
46
+ approvalFields?: readonly string[];
47
+ /**
48
+ * Who may approve or reject a held call of this tool, besides the workspace's owners and admins (the
49
+ * template's policy envelope says `approver`). `"requester"`, the default: the member whose conversation
50
+ * asked for it. `"admin"`: only an owner or admin, so a member sees "Waiting for an admin to decide this."
51
+ */
52
+ approver?: "requester" | "admin";
53
+ /** Your function. Return a value (sent as JSON), a string, or `refuse(...)`. A throw is an error result. */
54
+ run(args: InferOutput<S>, ctx: ToolContext): R | Promise<R>;
55
+ }
56
+ export interface Tool<S extends StandardSchemaWithJSON = StandardSchemaWithJSON, R = unknown> extends ToolDefinition<S, R> {
57
+ readonly kind: "openlegion.tool";
58
+ /** The input as JSON Schema 2020-12, as tools/list sends it. */
59
+ readonly inputSchema: Record<string, unknown>;
60
+ }
61
+ export declare function defineTool<S extends StandardSchemaWithJSON, R>(def: ToolDefinition<S, R>): Tool<S, R>;
62
+ declare const REFUSAL: unique symbol;
63
+ /** A tool's refusal: the call is answered as an error result the model reads. A refusal is a result, not a throw. */
64
+ export interface ToolRefusal {
65
+ readonly [REFUSAL]: true;
66
+ readonly message: string;
67
+ readonly code: string | null;
68
+ }
69
+ export declare function refuse(message: string, code?: string): ToolRefusal;
70
+ /** What `refuseIfTainted` says when you pass no message: plain words the agent can act on. */
71
+ export declare const TAINTED_REFUSAL_MESSAGE = "This run has read other people's words, so this action can't run from it. Ask the person to start it from their own request.";
72
+ /**
73
+ * Your rule for a tainted call: a refusal when the signed
74
+ * context says the run read untrusted content, else `null`. Every declared tool runs on a tainted run
75
+ * unless it is held, so a tool that must not act on other people's words unattended checks here:
76
+ * `const no = refuseIfTainted(ctx); if (no) return no;`. The code is `tainted`.
77
+ */
78
+ export declare function refuseIfTainted(ctx: Pick<OpenLegionContext, "tainted">, message?: string): ToolRefusal | null;
79
+ export declare function isRefusal(value: unknown): value is ToolRefusal;
80
+ /**
81
+ * Mark an item that holds other people's words (anything you stored from a call whose context was
82
+ * `tainted: true`). The platform taints the run that reads it.
83
+ */
84
+ export declare function markUntrusted<T extends object>(item: T): T & {
85
+ trust_tier: "web_low";
86
+ };
87
+ /** Throws for a set of tools the platform could not pin. */
88
+ export declare function checkToolSet(tools: Readonly<Record<string, Tool>>): void;
89
+ export interface ConnectorRefInput {
90
+ /** con_… (POST /connectors). */
91
+ id: string;
92
+ /** The connector's slug: tools are mcp.<slug>.<name>. */
93
+ slug: string;
94
+ }
95
+ export interface TemplateDefinition<T extends Record<string, Tool> = Record<string, Tool>> {
96
+ /** The template's slug (POST /templates): your handle for the product line. */
97
+ slug: string;
98
+ /** The template's name. */
99
+ name: string;
100
+ /** YOUR functions, by tool name. Served by createHandler, granted to the agent through your connector. */
101
+ tools?: T;
102
+ /**
103
+ * Which of the template's agents get one of your tools, by tool name: `{ email_me: ["assistant"] }` gives
104
+ * `email_me` to the agent whose key is `assistant` (and to agents your users make from it) and to no other.
105
+ * A tool you leave out is every agent's. Keys are `spec.agents[].key`; a one-agent template's agent is `main`.
106
+ */
107
+ toolAgents?: {
108
+ readonly [K in keyof T]?: readonly string[];
109
+ };
110
+ /** The rest of the template version (the published JSON Schema): name, role, instructions, model_tier, platform `tools`, schedules, … */
111
+ spec?: Omit<TemplateSpec, "connectors">;
112
+ }
113
+ export interface Template<T extends Record<string, Tool> = Record<string, Tool>> {
114
+ readonly kind: "openlegion.template";
115
+ readonly slug: string;
116
+ readonly name: string;
117
+ readonly tools: Readonly<T>;
118
+ readonly spec: Omit<TemplateSpec, "connectors">;
119
+ /**
120
+ * The template version to push (POST /templates/{slug}/versions): your spec, plus your connector with
121
+ * each of your tools declared (trust, effect). When the spec has a policy envelope, or a tool requires
122
+ * approval, every tool is placed in the envelope (an envelope is the outer bound): `held` for a tool with
123
+ * requiresApproval, else what your envelope says, else `allowed`; `approver: "admin"` for a tool that says
124
+ * so, or whose envelope entry already does. A new envelope also lists your platform `tools` as allowed, so
125
+ * adding one changes nothing else.
126
+ */
127
+ toTemplateSpec(connector: ConnectorRefInput): TemplateSpec;
128
+ }
129
+ export declare function defineTemplate<T extends Record<string, Tool>>(def: TemplateDefinition<T>): Template<T>;
130
+ export {};