@cogover/sdk 0.14.0 → 0.15.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.
- package/README.md +58 -3
- package/dist/action-schema.d.ts +86 -0
- package/dist/action-schema.js +52 -0
- package/dist/actions.d.ts +129 -0
- package/dist/actions.js +11 -0
- package/dist/agents.d.ts +75 -0
- package/dist/agents.js +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +2 -0
- package/dist/internal/action-config.js +94 -0
- package/dist/internal/action-runtime.js +143 -0
- package/dist/internal/action-schema-rules.js +33 -0
- package/dist/internal/agents-api.js +163 -0
- package/dist/internal/job-runtime.js +4 -0
- package/dist/internal/processes-api.js +74 -0
- package/dist/internal/schema-nodes.js +179 -0
- package/dist/internal/start-options.js +52 -0
- package/dist/internal/trigger-runtime.js +5 -0
- package/dist/jobs.d.ts +4 -0
- package/dist/processes.d.ts +52 -0
- package/dist/processes.js +1 -0
- package/dist/router.js +2 -0
- package/dist/script.d.ts +4 -0
- package/dist/script.js +4 -0
- package/dist/trigger.d.ts +6 -0
- package/docs/en/api-reference/actions.md +403 -0
- package/docs/en/api-reference/background-jobs.md +19 -8
- package/docs/en/api-reference/overview.md +31 -10
- package/docs/en/api-reference/processes-and-agents.md +357 -0
- package/docs/en/api-reference/record-triggers.md +9 -6
- package/docs/en/api-reference/scripts-and-routes.md +8 -4
- package/docs/en/usage-guide.md +142 -2
- package/package.json +1 -1
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { crypto } from "../crypto.js";
|
|
2
|
+
import { createDataApi } from "../data.js";
|
|
3
|
+
import { createEmailApi } from "../email.js";
|
|
4
|
+
import { ValidationError } from "../errors.js";
|
|
5
|
+
import { installCogoverFetch } from "../fetch.js";
|
|
6
|
+
import { limits } from "../limits.js";
|
|
7
|
+
import { createLocksApi } from "../locks.js";
|
|
8
|
+
import { SCRIPT_LOGGER } from "../logger.js";
|
|
9
|
+
import { createNotificationsApi } from "../notifications.js";
|
|
10
|
+
import { createOrgApi } from "../org.js";
|
|
11
|
+
import { createPushApi } from "../push.js";
|
|
12
|
+
import { createSchemaApi } from "../schema.js";
|
|
13
|
+
import { createSecretsApi } from "../secrets.js";
|
|
14
|
+
import { createStateApi } from "../state.js";
|
|
15
|
+
import { createAgentsApi } from "./agents-api.js";
|
|
16
|
+
import { invocationContext } from "./invocation.js";
|
|
17
|
+
import { createJobsApi } from "./jobs-api.js";
|
|
18
|
+
import { toJsonValue } from "./json.js";
|
|
19
|
+
import { runInvocation } from "./local-invocation.js";
|
|
20
|
+
import { createProcessesApi } from "./processes-api.js";
|
|
21
|
+
import { errorMessage, isRecord } from "./values.js";
|
|
22
|
+
/** Entry point Cogover calls with the host input JSON; it returns `{"output": ...}` or `{"outputError": "NOT_JSON"}`. */
|
|
23
|
+
export function createActionSandboxHandler(manifest, handler) {
|
|
24
|
+
return async (inputJson) => {
|
|
25
|
+
installCogoverFetch();
|
|
26
|
+
let input;
|
|
27
|
+
try {
|
|
28
|
+
input = JSON.parse(inputJson);
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
throw new ValidationError("Action input must be valid JSON", errorMessage(error));
|
|
32
|
+
}
|
|
33
|
+
if (!isRecord(input) || !isRecord(input.input)) {
|
|
34
|
+
throw new ValidationError("Action input must be a JSON object whose input member is an object");
|
|
35
|
+
}
|
|
36
|
+
const host = input;
|
|
37
|
+
const action = actionInfo(host, manifest);
|
|
38
|
+
let invocation;
|
|
39
|
+
const resolveInvocation = () => invocation ??= actionInvocationContext(host);
|
|
40
|
+
const result = await runInvocation("route", async () => handler(Object.freeze({
|
|
41
|
+
action,
|
|
42
|
+
get invocation() {
|
|
43
|
+
return resolveInvocation();
|
|
44
|
+
},
|
|
45
|
+
data: createDataApi(),
|
|
46
|
+
schema: createSchemaApi(),
|
|
47
|
+
log: SCRIPT_LOGGER,
|
|
48
|
+
state: createStateApi(),
|
|
49
|
+
locks: createLocksApi(),
|
|
50
|
+
push: createPushApi(),
|
|
51
|
+
notifications: createNotificationsApi(),
|
|
52
|
+
email: createEmailApi(),
|
|
53
|
+
jobs: createJobsApi(),
|
|
54
|
+
secrets: createSecretsApi(),
|
|
55
|
+
crypto,
|
|
56
|
+
org: createOrgApi(resolveInvocation),
|
|
57
|
+
limits,
|
|
58
|
+
processes: createProcessesApi(),
|
|
59
|
+
agents: createAgentsApi(),
|
|
60
|
+
}), host.input));
|
|
61
|
+
let output;
|
|
62
|
+
try {
|
|
63
|
+
output = toJsonValue(result === undefined ? null : result, "Action output");
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
// Expected for a handler that returns a value JSON cannot represent: the host reports it to the caller.
|
|
67
|
+
return JSON.stringify({ outputError: "NOT_JSON" });
|
|
68
|
+
}
|
|
69
|
+
return JSON.stringify({ output });
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
function actionInfo(input, manifest) {
|
|
73
|
+
const context = isRecord(input.__context) ? input.__context : undefined;
|
|
74
|
+
const raw = context !== undefined && isRecord(context.action) ? context.action : undefined;
|
|
75
|
+
if (raw === undefined) {
|
|
76
|
+
throw new ValidationError("Action metadata is unavailable outside Cogover Runtime");
|
|
77
|
+
}
|
|
78
|
+
const key = requiredString(raw.key, "Invalid action key metadata");
|
|
79
|
+
// A mismatch means the call was routed to a definition it was not registered for.
|
|
80
|
+
if (key !== manifest.key) {
|
|
81
|
+
throw new ValidationError(`Action input for '${key}' does not match the definition of '${manifest.key}'`);
|
|
82
|
+
}
|
|
83
|
+
const effect = raw.effect;
|
|
84
|
+
if (effect !== "read" && effect !== "write")
|
|
85
|
+
throw new ValidationError("Invalid action effect metadata");
|
|
86
|
+
return Object.freeze({
|
|
87
|
+
key,
|
|
88
|
+
runId: requiredString(raw.runId, "Invalid action runId metadata"),
|
|
89
|
+
effect: effect,
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
function actionInvocationContext(input) {
|
|
93
|
+
const base = invocationContext(input);
|
|
94
|
+
if (base.identity === "inbound")
|
|
95
|
+
throw new ValidationError("Invalid invocation identity metadata");
|
|
96
|
+
const context = input.__context;
|
|
97
|
+
return Object.freeze({ ...base, executionIdentity: base.identity, source: actionSource(context.actionSource) });
|
|
98
|
+
}
|
|
99
|
+
const PROCESS_RUN_AS = new Set(["PROCESS_STARTER", "PERSONNEL", "SYSTEM"]);
|
|
100
|
+
function actionSource(raw) {
|
|
101
|
+
const invalid = () => new ValidationError("Invalid action source metadata");
|
|
102
|
+
if (!isRecord(raw))
|
|
103
|
+
throw invalid();
|
|
104
|
+
const text = (value) => {
|
|
105
|
+
if (typeof value !== "string" || value === "")
|
|
106
|
+
throw invalid();
|
|
107
|
+
return value;
|
|
108
|
+
};
|
|
109
|
+
// A host that leaves out a null member is read as sending null.
|
|
110
|
+
const optionalText = (value) => value === undefined || value === null ? null : text(value);
|
|
111
|
+
// Only the documented keys are copied so that no other host metadata reaches project code.
|
|
112
|
+
if (raw.type === "process") {
|
|
113
|
+
const runAs = raw.runAs === undefined || raw.runAs === null ? null : raw.runAs;
|
|
114
|
+
if (runAs !== null && !PROCESS_RUN_AS.has(runAs))
|
|
115
|
+
throw invalid();
|
|
116
|
+
return Object.freeze({
|
|
117
|
+
type: "process",
|
|
118
|
+
processId: text(raw.processId),
|
|
119
|
+
processInfoId: text(raw.processInfoId),
|
|
120
|
+
instanceId: text(raw.instanceId),
|
|
121
|
+
nodeId: text(raw.nodeId),
|
|
122
|
+
runAs: runAs,
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
if (raw.type === "agent") {
|
|
126
|
+
if (typeof raw.interactive !== "boolean")
|
|
127
|
+
throw invalid();
|
|
128
|
+
return Object.freeze({
|
|
129
|
+
type: "agent",
|
|
130
|
+
agentId: text(raw.agentId),
|
|
131
|
+
sessionId: optionalText(raw.sessionId),
|
|
132
|
+
runId: optionalText(raw.runId),
|
|
133
|
+
interactive: raw.interactive,
|
|
134
|
+
initiatorPersonnelId: optionalText(raw.initiatorPersonnelId),
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
throw invalid();
|
|
138
|
+
}
|
|
139
|
+
function requiredString(value, message) {
|
|
140
|
+
if (typeof value !== "string" || value === "")
|
|
141
|
+
throw new ValidationError(message);
|
|
142
|
+
return value;
|
|
143
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { schemaNodeState } from "./schema-nodes.js";
|
|
2
|
+
import { utf8ByteLength } from "./utf8.js";
|
|
3
|
+
/** Largest JSON Schema, in UTF-8 bytes, of an action's input and output together or of an agent result. */
|
|
4
|
+
export const MAX_SCHEMA_BYTES = 16_384;
|
|
5
|
+
/** Levels of object and array nodes; the root object is the first level. */
|
|
6
|
+
export const MAX_SCHEMA_DEPTH = 3;
|
|
7
|
+
/**
|
|
8
|
+
* Checks a schema that is used as a root (an action's input or output, an agent's result schema) and returns its
|
|
9
|
+
* JSON Schema. `name` starts every message, for example "Action 'score_lead': input".
|
|
10
|
+
*/
|
|
11
|
+
export function rootSchemaJson(value, name, fail) {
|
|
12
|
+
const state = schemaNodeState(value);
|
|
13
|
+
if (state === undefined || state.kind !== "object") {
|
|
14
|
+
throw fail(`${name} must be an object schema created with s.object()`);
|
|
15
|
+
}
|
|
16
|
+
if (state.optional)
|
|
17
|
+
throw fail(`${name} must not be optional`);
|
|
18
|
+
if (depth(state) > MAX_SCHEMA_DEPTH) {
|
|
19
|
+
throw fail(`${name} must not nest objects and arrays more than ${MAX_SCHEMA_DEPTH} levels deep`);
|
|
20
|
+
}
|
|
21
|
+
return state.json;
|
|
22
|
+
}
|
|
23
|
+
/** UTF-8 size of the JSON encoding of a schema. */
|
|
24
|
+
export function schemaByteLength(json) {
|
|
25
|
+
return utf8ByteLength(JSON.stringify(json));
|
|
26
|
+
}
|
|
27
|
+
function depth(state) {
|
|
28
|
+
const own = state.kind === "object" || state.kind === "array" ? 1 : 0;
|
|
29
|
+
let deepest = 0;
|
|
30
|
+
for (const child of state.children)
|
|
31
|
+
deepest = Math.max(deepest, depth(child));
|
|
32
|
+
return own + deepest;
|
|
33
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { CogoverApiError, ValidationError } from "../errors.js";
|
|
2
|
+
import { MAX_SCHEMA_BYTES, rootSchemaJson, schemaByteLength } from "./action-schema-rules.js";
|
|
3
|
+
import { callBridge } from "./bridge.js";
|
|
4
|
+
import { deepFreeze } from "./json.js";
|
|
5
|
+
import { requireKnownKeys } from "./messaging.js";
|
|
6
|
+
import { OBJECT_SLUG, PROPERTY_NAME } from "./schema-nodes.js";
|
|
7
|
+
import { optionalBoundedText, optionalCompletion, optionalStartIdempotencyKey, requirePlatformId, } from "./start-options.js";
|
|
8
|
+
import { isRecord } from "./values.js";
|
|
9
|
+
const START_OPTIONS = new Set([
|
|
10
|
+
"instruction", "variables", "records", "resultSchema", "runAs", "approvalPolicy", "timeoutSeconds",
|
|
11
|
+
"idempotencyKey", "onResult",
|
|
12
|
+
]);
|
|
13
|
+
const RECORD_KEYS = new Set(["objectSlug", "recordId", "withActivities"]);
|
|
14
|
+
const RUN_AS = new Set(["caller", "agent"]);
|
|
15
|
+
const APPROVAL_POLICIES = new Set(["deny", "autoApprove"]);
|
|
16
|
+
const RUN_ID = /^[A-Za-z0-9:_.-]{1,160}$/u;
|
|
17
|
+
const RECORD_ID = /^[A-Za-z0-9_-]{1,128}$/u;
|
|
18
|
+
const MAX_INSTRUCTION_LENGTH = 20_000;
|
|
19
|
+
const MAX_VARIABLES = 50;
|
|
20
|
+
const MAX_VARIABLE_LENGTH = 4000;
|
|
21
|
+
const MAX_RECORDS = 20;
|
|
22
|
+
const MIN_TIMEOUT_SECONDS = 10;
|
|
23
|
+
const MAX_TIMEOUT_SECONDS = 1800;
|
|
24
|
+
const DEFAULT_TIMEOUT_SECONDS = 300;
|
|
25
|
+
/** @internal */
|
|
26
|
+
export function createAgentsApi() {
|
|
27
|
+
return Object.freeze({
|
|
28
|
+
async start(agentId, options) {
|
|
29
|
+
const result = await callBridge("agents.start", startPayload(agentId, options));
|
|
30
|
+
if (!isRecord(result) || typeof result.runId !== "string" || typeof result.duplicate !== "boolean") {
|
|
31
|
+
throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Agent start result is invalid");
|
|
32
|
+
}
|
|
33
|
+
return Object.freeze({ runId: result.runId, duplicate: result.duplicate });
|
|
34
|
+
},
|
|
35
|
+
async get(runId) {
|
|
36
|
+
if (typeof runId !== "string" || !RUN_ID.test(runId)) {
|
|
37
|
+
throw new ValidationError("agents.get() runId must contain 1 to 160 letters, digits, ':', '_', '.' or '-'");
|
|
38
|
+
}
|
|
39
|
+
const result = await callBridge("agents.get", { runId });
|
|
40
|
+
return runState(result);
|
|
41
|
+
},
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
function startPayload(agentId, options) {
|
|
45
|
+
const payload = { agentId: requirePlatformId(agentId, "agents.start() agentId") };
|
|
46
|
+
if (!isRecord(options))
|
|
47
|
+
throw new ValidationError("agents.start() options must be an object with an instruction");
|
|
48
|
+
const settings = requireKnownKeys(options, START_OPTIONS, "agents.start() options");
|
|
49
|
+
const instruction = optionalBoundedText(settings.instruction, "agents.start() instruction", MAX_INSTRUCTION_LENGTH);
|
|
50
|
+
if (instruction === undefined) {
|
|
51
|
+
throw new ValidationError(`agents.start() instruction must be a non-empty string of at most ${MAX_INSTRUCTION_LENGTH} characters`);
|
|
52
|
+
}
|
|
53
|
+
payload.instruction = instruction;
|
|
54
|
+
if (settings.variables !== undefined)
|
|
55
|
+
payload.variables = variables(settings.variables);
|
|
56
|
+
if (settings.records !== undefined)
|
|
57
|
+
payload.records = records(settings.records);
|
|
58
|
+
if (settings.resultSchema !== undefined) {
|
|
59
|
+
const schema = rootSchemaJson(settings.resultSchema, "agents.start() resultSchema", message => new ValidationError(message));
|
|
60
|
+
if (schemaByteLength(schema) > MAX_SCHEMA_BYTES) {
|
|
61
|
+
throw new ValidationError(`agents.start() resultSchema must not exceed ${MAX_SCHEMA_BYTES} UTF-8 bytes once JSON-encoded`);
|
|
62
|
+
}
|
|
63
|
+
payload.resultSchema = schema;
|
|
64
|
+
}
|
|
65
|
+
payload.runAs = choice(settings.runAs, "runAs", RUN_AS, "caller");
|
|
66
|
+
payload.approvalPolicy = choice(settings.approvalPolicy, "approvalPolicy", APPROVAL_POLICIES, "deny");
|
|
67
|
+
payload.timeoutSeconds = timeoutSeconds(settings.timeoutSeconds);
|
|
68
|
+
const idempotencyKey = optionalStartIdempotencyKey(settings.idempotencyKey, "agents.start()");
|
|
69
|
+
if (idempotencyKey !== undefined)
|
|
70
|
+
payload.idempotencyKey = idempotencyKey;
|
|
71
|
+
const onResult = optionalCompletion(settings.onResult, "agents.start() onResult");
|
|
72
|
+
if (onResult !== undefined)
|
|
73
|
+
payload.onResult = onResult;
|
|
74
|
+
return payload;
|
|
75
|
+
}
|
|
76
|
+
function variables(value) {
|
|
77
|
+
if (!isRecord(value) || Object.keys(value).length > MAX_VARIABLES) {
|
|
78
|
+
throw new ValidationError(`agents.start() variables must be an object of at most ${MAX_VARIABLES} entries`);
|
|
79
|
+
}
|
|
80
|
+
const result = {};
|
|
81
|
+
for (const [name, item] of Object.entries(value)) {
|
|
82
|
+
if (!PROPERTY_NAME.test(name)) {
|
|
83
|
+
throw new ValidationError(`agents.start() variable name '${name}' must start with a letter and contain `
|
|
84
|
+
+ "at most 64 letters, digits or underscores");
|
|
85
|
+
}
|
|
86
|
+
const valid = typeof item === "boolean"
|
|
87
|
+
|| (typeof item === "number" && Number.isFinite(item))
|
|
88
|
+
|| (typeof item === "string" && item.length <= MAX_VARIABLE_LENGTH);
|
|
89
|
+
if (!valid) {
|
|
90
|
+
throw new ValidationError(`agents.start() variable '${name}' must be a string of at most `
|
|
91
|
+
+ `${MAX_VARIABLE_LENGTH} characters, a finite number or a boolean`);
|
|
92
|
+
}
|
|
93
|
+
result[name] = item;
|
|
94
|
+
}
|
|
95
|
+
return result;
|
|
96
|
+
}
|
|
97
|
+
function records(value) {
|
|
98
|
+
if (!Array.isArray(value) || value.length > MAX_RECORDS) {
|
|
99
|
+
throw new ValidationError(`agents.start() records must be a list of at most ${MAX_RECORDS} records`);
|
|
100
|
+
}
|
|
101
|
+
return value.map(entry => {
|
|
102
|
+
const record = requireKnownKeys(entry, RECORD_KEYS, "agents.start() records entry");
|
|
103
|
+
if (typeof record.objectSlug !== "string" || !OBJECT_SLUG.test(record.objectSlug)) {
|
|
104
|
+
throw new ValidationError("agents.start() records objectSlug must start with a letter or underscore and "
|
|
105
|
+
+ "contain at most 128 letters, digits or underscores");
|
|
106
|
+
}
|
|
107
|
+
if (typeof record.recordId !== "string" || !RECORD_ID.test(record.recordId)) {
|
|
108
|
+
throw new ValidationError("agents.start() records recordId must contain 1 to 128 letters, digits, "
|
|
109
|
+
+ "'_' or '-'");
|
|
110
|
+
}
|
|
111
|
+
if (record.withActivities !== undefined && typeof record.withActivities !== "boolean") {
|
|
112
|
+
throw new ValidationError("agents.start() records withActivities must be a boolean");
|
|
113
|
+
}
|
|
114
|
+
return {
|
|
115
|
+
objectSlug: record.objectSlug,
|
|
116
|
+
recordId: record.recordId,
|
|
117
|
+
...(record.withActivities === undefined ? {} : { withActivities: record.withActivities }),
|
|
118
|
+
};
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
function choice(value, option, allowed, fallback) {
|
|
122
|
+
if (value === undefined)
|
|
123
|
+
return fallback;
|
|
124
|
+
if (typeof value !== "string" || !allowed.has(value)) {
|
|
125
|
+
throw new ValidationError(`agents.start() ${option} must be one of ${[...allowed].map(item => `"${item}"`)
|
|
126
|
+
.join(", ")}`);
|
|
127
|
+
}
|
|
128
|
+
return value;
|
|
129
|
+
}
|
|
130
|
+
function timeoutSeconds(value) {
|
|
131
|
+
if (value === undefined)
|
|
132
|
+
return DEFAULT_TIMEOUT_SECONDS;
|
|
133
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value)
|
|
134
|
+
|| value < MIN_TIMEOUT_SECONDS || value > MAX_TIMEOUT_SECONDS) {
|
|
135
|
+
throw new ValidationError(`agents.start() timeoutSeconds must be an integer between ${MIN_TIMEOUT_SECONDS} `
|
|
136
|
+
+ `and ${MAX_TIMEOUT_SECONDS}`);
|
|
137
|
+
}
|
|
138
|
+
return value;
|
|
139
|
+
}
|
|
140
|
+
// A host that leaves out a null member is read as sending null.
|
|
141
|
+
function runState(value) {
|
|
142
|
+
const invalid = () => new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Agent run state is invalid");
|
|
143
|
+
if (!isRecord(value) || typeof value.runId !== "string" || typeof value.status !== "string")
|
|
144
|
+
throw invalid();
|
|
145
|
+
const text = value.text ?? null;
|
|
146
|
+
if (text !== null && typeof text !== "string")
|
|
147
|
+
throw invalid();
|
|
148
|
+
const rawError = value.error ?? null;
|
|
149
|
+
let error = null;
|
|
150
|
+
if (rawError !== null) {
|
|
151
|
+
if (!isRecord(rawError) || typeof rawError.code !== "string" || typeof rawError.message !== "string") {
|
|
152
|
+
throw invalid();
|
|
153
|
+
}
|
|
154
|
+
error = Object.freeze({ code: rawError.code, message: rawError.message });
|
|
155
|
+
}
|
|
156
|
+
return Object.freeze({
|
|
157
|
+
runId: value.runId,
|
|
158
|
+
status: value.status,
|
|
159
|
+
text,
|
|
160
|
+
result: deepFreeze(value.result ?? null),
|
|
161
|
+
error,
|
|
162
|
+
});
|
|
163
|
+
}
|
|
@@ -15,6 +15,8 @@ import { createStateApi } from "../state.js";
|
|
|
15
15
|
import { invocationContext } from "./invocation.js";
|
|
16
16
|
import { createJobsApi } from "./jobs-api.js";
|
|
17
17
|
import { errorMessage, isRecord } from "./values.js";
|
|
18
|
+
import { createProcessesApi } from "./processes-api.js";
|
|
19
|
+
import { createAgentsApi } from "./agents-api.js";
|
|
18
20
|
// Both spellings of a source are accepted; project code only ever sees the SDK literals.
|
|
19
21
|
const SOURCES = new Map([
|
|
20
22
|
["enqueue", "enqueue"],
|
|
@@ -54,6 +56,8 @@ export function createJobSandboxHandler(manifest, handler) {
|
|
|
54
56
|
crypto,
|
|
55
57
|
org: createOrgApi(() => invocation ??= invocationContext(input)),
|
|
56
58
|
limits,
|
|
59
|
+
processes: createProcessesApi(),
|
|
60
|
+
agents: createAgentsApi(),
|
|
57
61
|
})));
|
|
58
62
|
// The result of a job is not delivered anywhere, so nothing is serialized.
|
|
59
63
|
return null;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { CogoverApiError, ValidationError } from "../errors.js";
|
|
2
|
+
import { callBridge } from "./bridge.js";
|
|
3
|
+
import { toJsonValue } from "./json.js";
|
|
4
|
+
import { requireKnownKeys } from "./messaging.js";
|
|
5
|
+
import { optionalBoundedText, optionalCompletion, optionalStartIdempotencyKey, requirePlatformId, } from "./start-options.js";
|
|
6
|
+
import { utf8ByteLength } from "./utf8.js";
|
|
7
|
+
import { isRecord } from "./values.js";
|
|
8
|
+
const START_OPTIONS = new Set(["input", "instanceName", "idempotencyKey", "onComplete"]);
|
|
9
|
+
const MAX_INPUT_BYTES = 65_536;
|
|
10
|
+
const MAX_INSTANCE_NAME_LENGTH = 255;
|
|
11
|
+
/** @internal */
|
|
12
|
+
export function createProcessesApi() {
|
|
13
|
+
return Object.freeze({
|
|
14
|
+
async start(processInfoId, options) {
|
|
15
|
+
const request = {
|
|
16
|
+
processInfoId: requirePlatformId(processInfoId, "processes.start() processInfoId"),
|
|
17
|
+
};
|
|
18
|
+
const settings = options === undefined
|
|
19
|
+
? {}
|
|
20
|
+
: requireKnownKeys(options, START_OPTIONS, "processes.start() options");
|
|
21
|
+
if (settings.input !== undefined) {
|
|
22
|
+
if (!isRecord(settings.input))
|
|
23
|
+
throw new ValidationError("processes.start() input must be a JSON object");
|
|
24
|
+
const input = toJsonValue(settings.input, "processes.start() input");
|
|
25
|
+
if (utf8ByteLength(JSON.stringify(input)) > MAX_INPUT_BYTES) {
|
|
26
|
+
throw new ValidationError(`processes.start() input must not exceed ${MAX_INPUT_BYTES} UTF-8 bytes`);
|
|
27
|
+
}
|
|
28
|
+
request.input = input;
|
|
29
|
+
}
|
|
30
|
+
const instanceName = optionalBoundedText(settings.instanceName, "processes.start() instanceName", MAX_INSTANCE_NAME_LENGTH);
|
|
31
|
+
if (instanceName !== undefined)
|
|
32
|
+
request.instanceName = instanceName;
|
|
33
|
+
const idempotencyKey = optionalStartIdempotencyKey(settings.idempotencyKey, "processes.start()");
|
|
34
|
+
if (idempotencyKey !== undefined)
|
|
35
|
+
request.idempotencyKey = idempotencyKey;
|
|
36
|
+
const onComplete = optionalCompletion(settings.onComplete, "processes.start() onComplete");
|
|
37
|
+
if (onComplete !== undefined)
|
|
38
|
+
request.onComplete = onComplete;
|
|
39
|
+
const result = await callBridge("processes.start", request);
|
|
40
|
+
if (!isRecord(result) || typeof result.instanceId !== "string" || typeof result.duplicate !== "boolean") {
|
|
41
|
+
throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Process start result is invalid");
|
|
42
|
+
}
|
|
43
|
+
return Object.freeze({ instanceId: result.instanceId, duplicate: result.duplicate });
|
|
44
|
+
},
|
|
45
|
+
async get(instanceId) {
|
|
46
|
+
const id = requirePlatformId(instanceId, "processes.get() instanceId");
|
|
47
|
+
const result = await callBridge("processes.get", { instanceId: id });
|
|
48
|
+
const invalid = () => new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Process instance state is invalid");
|
|
49
|
+
if (!isRecord(result))
|
|
50
|
+
throw invalid();
|
|
51
|
+
const { instanceId: resultId, processId, processInfoId, state } = result;
|
|
52
|
+
if (typeof resultId !== "string" || typeof processId !== "string" || typeof processInfoId !== "string"
|
|
53
|
+
|| typeof state !== "string") {
|
|
54
|
+
throw invalid();
|
|
55
|
+
}
|
|
56
|
+
return Object.freeze({
|
|
57
|
+
instanceId: resultId,
|
|
58
|
+
processId,
|
|
59
|
+
processInfoId,
|
|
60
|
+
state,
|
|
61
|
+
startedAt: optionalTime(result.startedAt, invalid),
|
|
62
|
+
finishedAt: optionalTime(result.finishedAt, invalid),
|
|
63
|
+
});
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
// A host that leaves out a null member is read as sending null.
|
|
68
|
+
function optionalTime(value, invalid) {
|
|
69
|
+
if (value === undefined || value === null)
|
|
70
|
+
return null;
|
|
71
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
72
|
+
throw invalid();
|
|
73
|
+
return value;
|
|
74
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { ValidationError } from "../errors.js";
|
|
2
|
+
import { deepFreeze } from "./json.js";
|
|
3
|
+
import { isRecord } from "./values.js";
|
|
4
|
+
export const OBJECT_SLUG = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/u;
|
|
5
|
+
export const PROPERTY_NAME = /^[A-Za-z][A-Za-z0-9_]{0,63}$/u;
|
|
6
|
+
const DEFAULT_MAX_LENGTH = 10_000;
|
|
7
|
+
const MAX_MAX_LENGTH = 100_000;
|
|
8
|
+
const MAX_ENUM_VALUES = 100;
|
|
9
|
+
const MAX_ENUM_VALUE_LENGTH = 200;
|
|
10
|
+
const DEFAULT_MAX_ITEMS = 1000;
|
|
11
|
+
const MAX_MAX_ITEMS = 10_000;
|
|
12
|
+
const MAX_PROPERTIES = 50;
|
|
13
|
+
const MAX_DESCRIPTION_LENGTH = 500;
|
|
14
|
+
// No `pattern`: the host would evaluate it with another regular expression engine. Check formats in the handler.
|
|
15
|
+
const STRING_OPTIONS = new Set(["minLength", "maxLength"]);
|
|
16
|
+
const RANGE_OPTIONS = new Set(["minimum", "maximum"]);
|
|
17
|
+
const ARRAY_OPTIONS = new Set(["maxItems"]);
|
|
18
|
+
// Only nodes created by the builder are schemas; a hand-written JSON object is not accepted anywhere.
|
|
19
|
+
const NODES = new WeakMap();
|
|
20
|
+
export function schemaNodeState(value) {
|
|
21
|
+
return typeof value === "object" && value !== null ? NODES.get(value) : undefined;
|
|
22
|
+
}
|
|
23
|
+
function createNode(state) {
|
|
24
|
+
// The methods close over the state instead of using `this`, so they also work when detached from the node.
|
|
25
|
+
const node = Object.freeze({
|
|
26
|
+
optional() {
|
|
27
|
+
return state.optional ? node : createNode({ ...state, optional: true });
|
|
28
|
+
},
|
|
29
|
+
describe(text) {
|
|
30
|
+
if (typeof text !== "string" || text.trim().length === 0 || text.trim().length > MAX_DESCRIPTION_LENGTH) {
|
|
31
|
+
throw new ValidationError(`describe() text must be a non-empty string of at most ${MAX_DESCRIPTION_LENGTH} characters`);
|
|
32
|
+
}
|
|
33
|
+
// "description" is always the last keyword, also when an earlier description is replaced.
|
|
34
|
+
const { description: _previous, ...keywords } = state.json;
|
|
35
|
+
return createNode({ ...state, json: deepFreeze({ ...keywords, description: text.trim() }) });
|
|
36
|
+
},
|
|
37
|
+
toJSON() {
|
|
38
|
+
return state.json;
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
NODES.set(node, state);
|
|
42
|
+
return node;
|
|
43
|
+
}
|
|
44
|
+
function leaf(kind, json) {
|
|
45
|
+
return createNode({ kind, optional: false, json: deepFreeze(json), children: [] });
|
|
46
|
+
}
|
|
47
|
+
/** Returns the options object, or an empty one when the options are absent. */
|
|
48
|
+
function options(value, method, allowed) {
|
|
49
|
+
if (value === undefined)
|
|
50
|
+
return {};
|
|
51
|
+
if (!isRecord(value))
|
|
52
|
+
throw new ValidationError(`${method} options must be an object`);
|
|
53
|
+
for (const option of Object.keys(value)) {
|
|
54
|
+
if (!allowed.has(option))
|
|
55
|
+
throw new ValidationError(`${method} has the unknown option '${option}'`);
|
|
56
|
+
}
|
|
57
|
+
return value;
|
|
58
|
+
}
|
|
59
|
+
function integerOption(value, label, minimum, maximum) {
|
|
60
|
+
if (value === undefined)
|
|
61
|
+
return undefined;
|
|
62
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < minimum || value > maximum) {
|
|
63
|
+
throw new ValidationError(`${label} must be an integer between ${minimum} and ${maximum}`);
|
|
64
|
+
}
|
|
65
|
+
return value;
|
|
66
|
+
}
|
|
67
|
+
export function stringSchema(value) {
|
|
68
|
+
const settings = options(value, "s.string()", STRING_OPTIONS);
|
|
69
|
+
const maxLength = integerOption(settings.maxLength, "s.string() maxLength", 1, MAX_MAX_LENGTH)
|
|
70
|
+
?? DEFAULT_MAX_LENGTH;
|
|
71
|
+
const minLength = integerOption(settings.minLength, "s.string() minLength", 0, maxLength);
|
|
72
|
+
return leaf("string", {
|
|
73
|
+
type: "string",
|
|
74
|
+
...(minLength === undefined ? {} : { minLength }),
|
|
75
|
+
maxLength,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
export function enumSchema(values) {
|
|
79
|
+
if (!Array.isArray(values) || values.length === 0 || values.length > MAX_ENUM_VALUES) {
|
|
80
|
+
throw new ValidationError(`s.enum() requires a list of 1 to ${MAX_ENUM_VALUES} values`);
|
|
81
|
+
}
|
|
82
|
+
const unique = new Set();
|
|
83
|
+
for (const item of values) {
|
|
84
|
+
if (typeof item !== "string" || item.length === 0 || item.length > MAX_ENUM_VALUE_LENGTH) {
|
|
85
|
+
throw new ValidationError(`s.enum() values must be non-empty strings of at most ${MAX_ENUM_VALUE_LENGTH} characters`);
|
|
86
|
+
}
|
|
87
|
+
if (unique.has(item))
|
|
88
|
+
throw new ValidationError(`s.enum() lists the value '${item}' more than once`);
|
|
89
|
+
unique.add(item);
|
|
90
|
+
}
|
|
91
|
+
return leaf("enum", { type: "string", enum: [...unique] });
|
|
92
|
+
}
|
|
93
|
+
export function numberSchema(value, integer) {
|
|
94
|
+
const method = integer ? "s.integer()" : "s.number()";
|
|
95
|
+
const settings = options(value, method, RANGE_OPTIONS);
|
|
96
|
+
const bound = (name) => {
|
|
97
|
+
const raw = settings[name];
|
|
98
|
+
if (raw === undefined)
|
|
99
|
+
return undefined;
|
|
100
|
+
const valid = typeof raw === "number" && (integer ? Number.isSafeInteger(raw) : Number.isFinite(raw));
|
|
101
|
+
if (!valid) {
|
|
102
|
+
throw new ValidationError(`${method} ${name} must be ${integer ? "a safe integer" : "a finite number"}`);
|
|
103
|
+
}
|
|
104
|
+
return raw;
|
|
105
|
+
};
|
|
106
|
+
const minimum = bound("minimum");
|
|
107
|
+
const maximum = bound("maximum");
|
|
108
|
+
if (minimum !== undefined && maximum !== undefined && minimum > maximum) {
|
|
109
|
+
throw new ValidationError(`${method} minimum must not be greater than maximum`);
|
|
110
|
+
}
|
|
111
|
+
return leaf(integer ? "integer" : "number", {
|
|
112
|
+
type: integer ? "integer" : "number",
|
|
113
|
+
...(minimum === undefined ? {} : { minimum }),
|
|
114
|
+
...(maximum === undefined ? {} : { maximum }),
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
export function booleanSchema() {
|
|
118
|
+
return leaf("boolean", { type: "boolean" });
|
|
119
|
+
}
|
|
120
|
+
export function dateSchema() {
|
|
121
|
+
return leaf("date", { type: "string", format: "date" });
|
|
122
|
+
}
|
|
123
|
+
export function dateTimeSchema() {
|
|
124
|
+
return leaf("dateTime", { type: "integer", format: "x-epoch-ms" });
|
|
125
|
+
}
|
|
126
|
+
export function recordIdSchema(objectSlug) {
|
|
127
|
+
if (typeof objectSlug !== "string" || !OBJECT_SLUG.test(objectSlug)) {
|
|
128
|
+
throw new ValidationError("s.recordId() object slug must start with a letter or underscore and contain "
|
|
129
|
+
+ "at most 128 letters, digits or underscores");
|
|
130
|
+
}
|
|
131
|
+
return leaf("recordId", { type: "string", "x-cogover-object": objectSlug });
|
|
132
|
+
}
|
|
133
|
+
export function arraySchema(item, value) {
|
|
134
|
+
const itemState = schemaNodeState(item);
|
|
135
|
+
if (itemState === undefined)
|
|
136
|
+
throw new ValidationError("s.array() item must be a schema created with s");
|
|
137
|
+
if (itemState.optional)
|
|
138
|
+
throw new ValidationError("s.array() item must not be optional");
|
|
139
|
+
const settings = options(value, "s.array()", ARRAY_OPTIONS);
|
|
140
|
+
const maxItems = integerOption(settings.maxItems, "s.array() maxItems", 1, MAX_MAX_ITEMS) ?? DEFAULT_MAX_ITEMS;
|
|
141
|
+
return createNode({
|
|
142
|
+
kind: "array",
|
|
143
|
+
optional: false,
|
|
144
|
+
json: deepFreeze({ type: "array", items: itemState.json, maxItems }),
|
|
145
|
+
children: [itemState],
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
export function objectSchema(shape) {
|
|
149
|
+
if (!isRecord(shape) || schemaNodeState(shape) !== undefined) {
|
|
150
|
+
throw new ValidationError("s.object() requires an object that maps property names to schemas");
|
|
151
|
+
}
|
|
152
|
+
const names = Object.keys(shape);
|
|
153
|
+
if (names.length > MAX_PROPERTIES) {
|
|
154
|
+
throw new ValidationError(`s.object() must not declare more than ${MAX_PROPERTIES} properties`);
|
|
155
|
+
}
|
|
156
|
+
const properties = {};
|
|
157
|
+
const required = [];
|
|
158
|
+
const children = [];
|
|
159
|
+
for (const name of names) {
|
|
160
|
+
if (!PROPERTY_NAME.test(name)) {
|
|
161
|
+
throw new ValidationError(`s.object() property name '${name}' must start with a letter and contain `
|
|
162
|
+
+ "at most 64 letters, digits or underscores");
|
|
163
|
+
}
|
|
164
|
+
const property = schemaNodeState(shape[name]);
|
|
165
|
+
if (property === undefined) {
|
|
166
|
+
throw new ValidationError(`s.object() property '${name}' must be a schema created with s`);
|
|
167
|
+
}
|
|
168
|
+
properties[name] = property.json;
|
|
169
|
+
if (!property.optional)
|
|
170
|
+
required.push(name);
|
|
171
|
+
children.push(property);
|
|
172
|
+
}
|
|
173
|
+
return createNode({
|
|
174
|
+
kind: "object",
|
|
175
|
+
optional: false,
|
|
176
|
+
json: deepFreeze({ type: "object", properties, required, additionalProperties: false }),
|
|
177
|
+
children,
|
|
178
|
+
});
|
|
179
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { ValidationError } from "../errors.js";
|
|
2
|
+
import { JOB_KEY } from "./job-config.js";
|
|
3
|
+
import { toJsonValue } from "./json.js";
|
|
4
|
+
import { requireKnownKeys } from "./messaging.js";
|
|
5
|
+
import { utf8ByteLength } from "./utf8.js";
|
|
6
|
+
/** ID of a Process definition, a Process instance or an AI Agent. */
|
|
7
|
+
export const PLATFORM_ID = /^[A-Za-z0-9_-]{1,64}$/u;
|
|
8
|
+
const IDEMPOTENCY_KEY = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/u;
|
|
9
|
+
const COMPLETION_KEYS = new Set(["job", "payload"]);
|
|
10
|
+
const MAX_COMPLETION_PAYLOAD_BYTES = 8192;
|
|
11
|
+
export function requirePlatformId(value, label) {
|
|
12
|
+
if (typeof value !== "string" || !PLATFORM_ID.test(value)) {
|
|
13
|
+
throw new ValidationError(`${label} must contain 1 to 64 letters, digits, '_' or '-'`);
|
|
14
|
+
}
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
export function optionalStartIdempotencyKey(value, method) {
|
|
18
|
+
if (value === undefined)
|
|
19
|
+
return undefined;
|
|
20
|
+
if (typeof value !== "string" || !IDEMPOTENCY_KEY.test(value)) {
|
|
21
|
+
throw new ValidationError(`${method} idempotencyKey must start with a letter or digit and contain at most `
|
|
22
|
+
+ "200 letters, digits, '.', '_', ':' or '-'");
|
|
23
|
+
}
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
/** Validates an `onComplete` / `onResult` option; `null` and `undefined` payloads are left out. */
|
|
27
|
+
export function optionalCompletion(value, label) {
|
|
28
|
+
if (value === undefined)
|
|
29
|
+
return undefined;
|
|
30
|
+
const completion = requireKnownKeys(value, COMPLETION_KEYS, label);
|
|
31
|
+
if (typeof completion.job !== "string" || !JOB_KEY.test(completion.job)) {
|
|
32
|
+
throw new ValidationError(`${label}.job must start with a letter and contain at most 100 letters, digits or underscores`);
|
|
33
|
+
}
|
|
34
|
+
const result = { job: completion.job };
|
|
35
|
+
if (completion.payload !== undefined && completion.payload !== null) {
|
|
36
|
+
const payload = toJsonValue(completion.payload, `${label}.payload`);
|
|
37
|
+
if (utf8ByteLength(JSON.stringify(payload)) > MAX_COMPLETION_PAYLOAD_BYTES) {
|
|
38
|
+
throw new ValidationError(`${label}.payload must not exceed ${MAX_COMPLETION_PAYLOAD_BYTES} UTF-8 bytes`);
|
|
39
|
+
}
|
|
40
|
+
result.payload = payload;
|
|
41
|
+
}
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
44
|
+
/** A string that is not blank and has at most `maximum` characters; returned unchanged. */
|
|
45
|
+
export function optionalBoundedText(value, label, maximum) {
|
|
46
|
+
if (value === undefined)
|
|
47
|
+
return undefined;
|
|
48
|
+
if (typeof value !== "string" || value.trim().length === 0 || value.length > maximum) {
|
|
49
|
+
throw new ValidationError(`${label} must be a non-empty string of at most ${maximum} characters`);
|
|
50
|
+
}
|
|
51
|
+
return value;
|
|
52
|
+
}
|