@composable-os/cli 0.0.0-stage → 0.1.0-beta.11
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/LICENSE +109 -0
- package/README.md +24 -2
- package/dist/accounts-UHYLCLEY.js +45 -0
- package/dist/blocks-5IFU25J6.js +233 -0
- package/dist/chunk-2ABSVMGB.js +13 -0
- package/dist/chunk-2IVEVPMY.js +669 -0
- package/dist/chunk-2TWV3SVB.js +349 -0
- package/dist/chunk-2XC5JLBO.js +1931 -0
- package/dist/chunk-324WJXNP.js +320 -0
- package/dist/chunk-5KSXSK7Y.js +47 -0
- package/dist/chunk-6ELZRNUU.js +116 -0
- package/dist/chunk-6UWRT4VM.js +220 -0
- package/dist/chunk-6WGFA2IV.js +643 -0
- package/dist/chunk-6XTU2MTP.js +11278 -0
- package/dist/chunk-7CQGMVDO.js +63 -0
- package/dist/chunk-7D4GKZOX.js +615 -0
- package/dist/chunk-7OGCMQXG.js +284 -0
- package/dist/chunk-DHS2CV2M.js +139 -0
- package/dist/chunk-DU6OIFOU.js +2358 -0
- package/dist/chunk-E4WCYTCT.js +347 -0
- package/dist/chunk-E64SG24J.js +88 -0
- package/dist/chunk-FJIZGS5Q.js +698 -0
- package/dist/chunk-GYTEW66E.js +50 -0
- package/dist/chunk-HDIOVFAZ.js +544 -0
- package/dist/chunk-K34UKWEI.js +298 -0
- package/dist/chunk-KGHA67HG.js +765 -0
- package/dist/chunk-LAAL4YGR.js +365 -0
- package/dist/chunk-LO6WGU5Y.js +26189 -0
- package/dist/chunk-MBIKVRAC.js +1425 -0
- package/dist/chunk-P6UWZ6QQ.js +426 -0
- package/dist/chunk-PDD2ETVF.js +1302 -0
- package/dist/chunk-UB4I2QKR.js +31575 -0
- package/dist/chunk-WHKJGF36.js +2418 -0
- package/dist/chunk-XIDLW3EP.js +15471 -0
- package/dist/chunk-YFTLIEWU.js +504 -0
- package/dist/chunk-YNUZRTPH.js +182 -0
- package/dist/chunk-ZAWES2UD.js +9364 -0
- package/dist/chunk-ZZFWMVJO.js +704 -0
- package/dist/cli-5UNY5G5L.js +136 -0
- package/dist/cli-UYZMVQMR.js +24534 -0
- package/dist/cli.js +25 -0
- package/dist/client-repo-SE4EKG6W.js +55 -0
- package/dist/create.js +25 -0
- package/dist/fields-FTWWMD7N.js +50 -0
- package/dist/grants-LOW6TSWD.js +32 -0
- package/dist/invoke-6KVT6WJI.js +41 -0
- package/dist/moves-E2HKYCTK.js +41 -0
- package/dist/order-U4KZLLSJ.js +19 -0
- package/dist/person-UHLVBVLR.js +67 -0
- package/dist/plan-on-sale-TJPFCNL7.js +26 -0
- package/dist/platform/migrations/0001_init.sql +59 -0
- package/dist/platform/migrations/0002_users_settings.sql +34 -0
- package/dist/platform/migrations/0003_people_organisations.sql +225 -0
- package/dist/platform/migrations/0004_activities_tasks.sql +88 -0
- package/dist/platform/migrations/0005_views_audit.sql +79 -0
- package/dist/platform/migrations/0006_search.sql +223 -0
- package/dist/platform/migrations/0007_crm_views.sql +141 -0
- package/dist/platform/migrations/0008_audit_redaction.sql +116 -0
- package/dist/platform/migrations/0010_approval_queue.sql +90 -0
- package/dist/platform/migrations/0011_connected_apps.sql +36 -0
- package/dist/platform/migrations/0020_extensions.sql +373 -0
- package/dist/platform/migrations/0030_extension_proposals.sql +29 -0
- package/dist/platform/migrations/0050_live_row_indexes.sql +32 -0
- package/dist/platform/migrations/0060_audit_read_counts.sql +31 -0
- package/dist/platform/migrations/0061_audit_retention.sql +95 -0
- package/dist/platform/migrations/0062_run_history_retention.sql +6 -0
- package/dist/platform/migrations/0063_pending_action_compaction.sql +18 -0
- package/dist/platform/migrations/0064_drop_rate_limit.sql +6 -0
- package/dist/platform/migrations/0065_storage_stats.sql +13 -0
- package/dist/platform/migrations/0070_drop_proposals_ext_idx.sql +9 -0
- package/dist/platform/migrations/0080_views_dashboards.sql +46 -0
- package/dist/platform/migrations/0100_stage_history.sql +54 -0
- package/dist/platform/migrations/0110_integrations.sql +103 -0
- package/dist/platform/migrations/0111_email_calendar_sync.sql +137 -0
- package/dist/platform/migrations/0112_sync_item_occurred_at.sql +8 -0
- package/dist/platform/migrations/0130_automations.sql +113 -0
- package/dist/platform/migrations/0131_notifications.sql +29 -0
- package/dist/platform/migrations/0132_automation_runtime.sql +14 -0
- package/dist/platform/migrations/0150_ai_summaries_embeddings.sql +48 -0
- package/dist/platform/migrations/0160_releases.sql +41 -0
- package/dist/platform/migrations/0161_setup_wizard.sql +30 -0
- package/dist/platform/migrations/0170_automation_connections.sql +32 -0
- package/dist/platform/migrations/0171_automation_outbox.sql +23 -0
- package/dist/platform/migrations/0172_notification_delivery.sql +46 -0
- package/dist/platform/migrations/0200_assistant_conversations.sql +25 -0
- package/dist/platform/migrations/0205_policy_adjudicator.sql +61 -0
- package/dist/platform/migrations/0210_daily_digest.sql +33 -0
- package/dist/platform/migrations/0220_entitlements.sql +13 -0
- package/dist/platform/migrations/0221_support_grants.sql +33 -0
- package/dist/platform/migrations/0250_judge.sql +11 -0
- package/dist/platform/migrations/0251_adjudication_judgement.sql +8 -0
- package/dist/platform/migrations/0252_judge_usage.sql +14 -0
- package/dist/platform/migrations/0255_summary_checks.sql +9 -0
- package/dist/platform/migrations/0256_outbound_check.sql +9 -0
- package/dist/platform/migrations/0260_ai_usage.sql +20 -0
- package/dist/platform/migrations/0270_assistant_conversation_refs.sql +29 -0
- package/dist/platform/migrations/0310_assignment_rules.sql +54 -0
- package/dist/platform/migrations/0320_duplicates.sql +41 -0
- package/dist/platform/migrations/0330_erase_completeness.sql +54 -0
- package/dist/platform/migrations/0350_assistant_thread.sql +38 -0
- package/dist/platform/migrations/0351_assistant_model_roles.sql +26 -0
- package/dist/platform/migrations/0352_assistant_memory.sql +74 -0
- package/dist/platform/migrations/0358_ai_cache_observation.sql +24 -0
- package/dist/platform/migrations/0359_ai_compaction_decision.sql +25 -0
- package/dist/platform/migrations/0360_ai_cache_estimate.sql +35 -0
- package/dist/platform/migrations/0361_voice_preferences.sql +27 -0
- package/dist/platform/migrations/0362_voice_usage.sql +17 -0
- package/dist/platform/migrations/0365_routines.sql +38 -0
- package/dist/platform/migrations/0370_approval_execution.sql +20 -0
- package/dist/platform/migrations/0371_agent_jobs.sql +65 -0
- package/dist/platform/migrations/0380_rec_views.sql +94 -0
- package/dist/platform/migrations/0400_customer_audit_actor.sql +142 -0
- package/dist/platform/migrations/0401_customer_accounts.sql +61 -0
- package/dist/platform/migrations/0402_erase_requests.sql +34 -0
- package/dist/platform/migrations/0410_idempotency_keys.sql +45 -0
- package/dist/platform/migrations/0411_device_sessions.sql +33 -0
- package/dist/platform/migrations/0420_transition_history.sql +100 -0
- package/dist/platform/migrations/0421_orders.sql +134 -0
- package/dist/platform/migrations/0422_order_payments.sql +109 -0
- package/dist/platform/migrations/0440_capacity.sql +100 -0
- package/dist/platform/migrations/0441_capacity_views.sql +40 -0
- package/dist/platform/migrations/0450_order_grants.sql +21 -0
- package/dist/platform/migrations/0451_pack_roles.sql +18 -0
- package/dist/platform/migrations/0460_content.sql +59 -0
- package/dist/platform/migrations/0461_media.sql +52 -0
- package/dist/platform/migrations/0470_publish_versions.sql +36 -0
- package/dist/platform/migrations/0471_permission_grants.sql +18 -0
- package/dist/platform/migrations/0490_staff_invites.sql +40 -0
- package/dist/platform/migrations/0491_sign_in_mail_kind.sql +10 -0
- package/dist/platform/migrations/0492_email_confirmation_and_sign_in_confirm.sql +30 -0
- package/dist/platform/migrations/0500_published_media_field.sql +25 -0
- package/dist/platform/migrations/0501_import_keys.sql +23 -0
- package/dist/platform/migrations/0510_video_and_file_media.sql +109 -0
- package/dist/platform/migrations/0516_order_tax.sql +63 -0
- package/dist/platform/migrations/0520_publish_requests.sql +20 -0
- package/dist/platform/migrations/0530_subscriptions.sql +173 -0
- package/dist/platform/migrations/0531_subscription_trials.sql +56 -0
- package/dist/platform/migrations/0532_subscription_offers.sql +80 -0
- package/dist/platform/migrations/0533_allowances.sql +262 -0
- package/dist/platform/migrations/0560_recurring.sql +75 -0
- package/dist/platform/migrations/0580_subscription_grants.sql +21 -0
- package/dist/platform/migrations/0581_once_per_person.sql +34 -0
- package/dist/platform/migrations/0600_tool_actions_ran_at_queue.sql +22 -0
- package/dist/platform/migrations/0610_waitlists.sql +54 -0
- package/dist/platform/migrations/0630_subscription_changes.sql +122 -0
- package/dist/platform/migrations/0650_person_links.sql +90 -0
- package/dist/platform/migrations/0670_unmoved_guard.sql +52 -0
- package/dist/platform/migrations/0690_sellable_refund_due.sql +98 -0
- package/dist/platform/sdk/allowance.ts +522 -0
- package/dist/platform/sdk/automation-check.ts +534 -0
- package/dist/platform/sdk/automation.ts +743 -0
- package/dist/platform/sdk/behaviour.ts +215 -0
- package/dist/platform/sdk/capacity.ts +303 -0
- package/dist/platform/sdk/contract.ts +909 -0
- package/dist/platform/sdk/document.ts +935 -0
- package/dist/platform/sdk/field-types.ts +111 -0
- package/dist/platform/sdk/formula/ast.ts +72 -0
- package/dist/platform/sdk/formula/compile.ts +454 -0
- package/dist/platform/sdk/formula/index.ts +4 -0
- package/dist/platform/sdk/formula/parser.ts +417 -0
- package/dist/platform/sdk/index.ts +36 -0
- package/dist/platform/sdk/manifest.ts +1785 -0
- package/dist/platform/sdk/media.ts +108 -0
- package/dist/platform/sdk/permissions.ts +60 -0
- package/dist/platform/sdk/recurring.ts +321 -0
- package/dist/platform/sdk/renamed.ts +63 -0
- package/dist/platform/sdk/rich-text-fixture.ts +68 -0
- package/dist/platform/sdk/rich-text.ts +221 -0
- package/dist/platform/sdk/runtime.ts +410 -0
- package/dist/platform/sdk/sellable.ts +1138 -0
- package/dist/platform/sdk/slug.ts +25 -0
- package/dist/platform/sdk/states.ts +598 -0
- package/dist/platform/sdk/testing.ts +847 -0
- package/dist/platform/sdk/unique.ts +81 -0
- package/dist/products-2H5DR232.js +11 -0
- package/dist/run-7P4RQALH.js +648 -0
- package/dist/run-PO3W5BFA.js +508 -0
- package/dist/run-ZCGFMEZF.js +309 -0
- package/dist/src-CRO35DYY.js +46 -0
- package/dist/src-I3IJ4NKC.js +354 -0
- package/dist/token-MOJUA2U6.js +70 -0
- package/dist/token-util-TENRN4V7.js +6 -0
- package/dist/visibility-TVXZ67FD.js +41 -0
- package/package.json +33 -4
|
@@ -0,0 +1,847 @@
|
|
|
1
|
+
// @composable-os/sdk/testing: unit-test an extension locally with in-memory host modules.
|
|
2
|
+
//
|
|
3
|
+
// const host = createTestHost(extension, { records: { organisation: [{ id: "org_1", name: "Acme" }] } });
|
|
4
|
+
// expect(host.issues).toEqual([]);
|
|
5
|
+
// const out = await host.runTool("scoreOrganisation", { organisationId: "org_1" });
|
|
6
|
+
// expect(host.calls).toContainEqual({ operation: "record.get", input: { ... } });
|
|
7
|
+
//
|
|
8
|
+
// The in-memory `ops` module enforces the extension's declared permissions with the host's rules
|
|
9
|
+
// (`checkGrant`) and implements the generic record operations over an in-memory store. Pass
|
|
10
|
+
// `operations` to fake anything else.
|
|
11
|
+
//
|
|
12
|
+
// Automations run in memory too, start to finish, without the Workflow:
|
|
13
|
+
//
|
|
14
|
+
// const run = await host.runAutomation("wonOnboarding", { record: { object: "deals.deal", id: "d1" } });
|
|
15
|
+
// expect(run.steps.map((s) => s.name)).toEqual(["createTasks", "notifyOwner", "wait", "notifyManager"]);
|
|
16
|
+
// expect(run.notifications[0]?.userIds).toEqual(["usr_owner"]);
|
|
17
|
+
//
|
|
18
|
+
// `step.do` runs its function, `step.sleep` and `step.waitForEvent` return at once (recorded with
|
|
19
|
+
// how long they would wait; pass `events` for waitForEvent payloads), and every step name is held
|
|
20
|
+
// to the automation's declarations like the host does. Writes and notifications a step did not
|
|
21
|
+
// declare are listed in `undeclared`.
|
|
22
|
+
import {
|
|
23
|
+
type AutomationContext,
|
|
24
|
+
type AutomationEvent,
|
|
25
|
+
type AutomationStepApi,
|
|
26
|
+
type AutomationTestStep,
|
|
27
|
+
durationMs,
|
|
28
|
+
type NotificationSendInput,
|
|
29
|
+
notificationInput,
|
|
30
|
+
} from "./automation.ts";
|
|
31
|
+
import { type AiModule, type Extension, GATEKEEPER_MODULES, type StartedBy } from "./contract.ts";
|
|
32
|
+
import { validateDocument } from "./document.ts";
|
|
33
|
+
import type { ExtensionManifest, ManifestIssue, ValidateOptions } from "./manifest.ts";
|
|
34
|
+
import { CORE_OBJECT_NAMES, toManifest, validateManifest } from "./manifest.ts";
|
|
35
|
+
import { checkGrant } from "./permissions.ts";
|
|
36
|
+
import { documentMaxBytesOf, documentSchemaOf } from "./rich-text.ts";
|
|
37
|
+
import { buildContext, type RawHostModules, runExtension } from "./runtime.ts";
|
|
38
|
+
|
|
39
|
+
type Values = Record<string, unknown> & { id: string };
|
|
40
|
+
type OperationFake = (input: Record<string, unknown>) => unknown;
|
|
41
|
+
|
|
42
|
+
export interface TestHostOptions {
|
|
43
|
+
/** Seed records by object name (`organisation`, `example.project`). */
|
|
44
|
+
records?: Record<string, Values[]>;
|
|
45
|
+
/** Fakes for operations the harness does not implement, by name. */
|
|
46
|
+
operations?: Record<string, OperationFake>;
|
|
47
|
+
/** Fakes for the AI module. Default: deterministic stand-ins. */
|
|
48
|
+
ai?: Partial<AiModule>;
|
|
49
|
+
/** Passed to validateManifest. */
|
|
50
|
+
validate?: ValidateOptions;
|
|
51
|
+
/**
|
|
52
|
+
* Users `notification.send` resolves (`{ role: "admin" }`, `managerOf`). Default one admin,
|
|
53
|
+
* `usr_admin`.
|
|
54
|
+
*/
|
|
55
|
+
users?: { id: string; role: "admin" | "member" | "viewer" }[];
|
|
56
|
+
/**
|
|
57
|
+
* Fakes for the gatekeepers the extension declares in `permissions.modules`, by name: what a
|
|
58
|
+
* session method returns for `call(connectionId, resource, method, ...args)`. Every call is
|
|
59
|
+
* recorded in `gatekeeperCalls`. A declared gatekeeper with no fake answers `{ status: "pending" }`
|
|
60
|
+
* (a person would approve it), with one connection per declared automation connection.
|
|
61
|
+
*/
|
|
62
|
+
gatekeepers?: Record<
|
|
63
|
+
string,
|
|
64
|
+
(call: { connectionId: string; resource: string; method: string; args: unknown[] }) => unknown
|
|
65
|
+
>;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** A call a tool or automation made through `ctx.gatekeeper(name).call(...)`. */
|
|
69
|
+
export interface GatekeeperCall {
|
|
70
|
+
gatekeeper: string;
|
|
71
|
+
connectionId: string;
|
|
72
|
+
resource: string;
|
|
73
|
+
method: string;
|
|
74
|
+
args: unknown[];
|
|
75
|
+
/** The step it was made in (null: outside a step, or a tool). */
|
|
76
|
+
step: string | null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** A notification the in-memory `notification.send` delivered. */
|
|
80
|
+
export interface SentNotification extends Omit<NotificationSendInput, "type" | "dedupeKey"> {
|
|
81
|
+
type: string;
|
|
82
|
+
dedupeKey: string | null;
|
|
83
|
+
/** Resolved, deduplicated recipients. */
|
|
84
|
+
userIds: string[];
|
|
85
|
+
notes: string[];
|
|
86
|
+
/** The step that sent it (null: outside a step). */
|
|
87
|
+
step: string | null;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export interface AutomationRunOptions {
|
|
91
|
+
/** The trigger record, from the seeded `records`. */
|
|
92
|
+
record?: { object: string; id: string };
|
|
93
|
+
change?: AutomationEvent["change"];
|
|
94
|
+
period?: string;
|
|
95
|
+
manual?: AutomationEvent["manual"];
|
|
96
|
+
approval?: AutomationEvent["approval"];
|
|
97
|
+
/** waitForEvent payloads by step name. Default null (the wait timed out). */
|
|
98
|
+
events?: Record<string, unknown>;
|
|
99
|
+
runId?: string;
|
|
100
|
+
/** `event.test`. Default false: the run writes to the in-memory store. */
|
|
101
|
+
test?: boolean;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export interface AutomationRunResult {
|
|
105
|
+
/** False when the declared conditions did not match the trigger record (nothing ran). */
|
|
106
|
+
matched: boolean;
|
|
107
|
+
/** What `run` returned. */
|
|
108
|
+
value: unknown;
|
|
109
|
+
/** Set when `run` threw (a step failed, or an undeclared step name). */
|
|
110
|
+
error: { code: string; message: string } | null;
|
|
111
|
+
/** Every step in the order it ran; waits carry `skippedMs`. */
|
|
112
|
+
steps: (AutomationTestStep & { calls: TestHost["calls"] })[];
|
|
113
|
+
/** Record writes the run made (operation, object, the created or changed id). */
|
|
114
|
+
writes: { step: string | null; operation: string; object: string | null; id: string | null }[];
|
|
115
|
+
notifications: SentNotification[];
|
|
116
|
+
/** Effects no declaration covers, e.g. "step notifyOwner wrote task (not in its writes)". */
|
|
117
|
+
undeclared: string[];
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Thrown into `run` when it uses a step name it did not declare (the host refuses it too). */
|
|
121
|
+
export class AutomationStepError extends Error {
|
|
122
|
+
override name = "AutomationStepError";
|
|
123
|
+
readonly code = "undeclared_step";
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export class ExtensionToolError extends Error {
|
|
127
|
+
override name = "ExtensionToolError";
|
|
128
|
+
constructor(
|
|
129
|
+
readonly code: string,
|
|
130
|
+
message: string,
|
|
131
|
+
readonly details?: unknown,
|
|
132
|
+
) {
|
|
133
|
+
super(message);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export interface TestHost {
|
|
138
|
+
manifest: ExtensionManifest;
|
|
139
|
+
/** Contract and formula issues (`extension.check` minus typecheck and dry-run reconcile). */
|
|
140
|
+
issues: ManifestIssue[];
|
|
141
|
+
/**
|
|
142
|
+
* Runs a tool like the host does: input and output validated, ctx from in-memory modules.
|
|
143
|
+
* `caller` is who started it (`ctx.caller`, ADR 0436); default the staff user `usr_admin`.
|
|
144
|
+
*/
|
|
145
|
+
runTool<T = unknown>(tool: string, input: unknown, options?: { caller?: StartedBy }): Promise<T>;
|
|
146
|
+
/** Every codemode:ops call, in order (allowed or refused). */
|
|
147
|
+
calls: { operation: string; input: unknown; allowed: boolean }[];
|
|
148
|
+
logs: { level: string; message: string; data: unknown }[];
|
|
149
|
+
storage: Map<string, unknown>;
|
|
150
|
+
records: Map<string, Map<string, Values>>;
|
|
151
|
+
/** Every notification sent through the in-memory `notification.send`. */
|
|
152
|
+
notifications: SentNotification[];
|
|
153
|
+
/** Every call through a gatekeeper module, in order. */
|
|
154
|
+
gatekeeperCalls: GatekeeperCall[];
|
|
155
|
+
/**
|
|
156
|
+
* Runs automation `name` in memory, start to finish: conditions checked on the trigger
|
|
157
|
+
* record, waits skipped (and recorded), steps held to the declarations.
|
|
158
|
+
*/
|
|
159
|
+
runAutomation(name: string, options?: AutomationRunOptions): Promise<AutomationRunResult>;
|
|
160
|
+
/**
|
|
161
|
+
* Publishes a record of a publishable object as a person would (`record.publish`, which no
|
|
162
|
+
* tool may call): its content fields become the next version, which `record.version` reads.
|
|
163
|
+
* Returns the version's number.
|
|
164
|
+
*/
|
|
165
|
+
publish(object: string, id: string): number;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function riskOf(operation: string): string {
|
|
169
|
+
const verb = operation.split(".").at(-1) ?? "";
|
|
170
|
+
if (
|
|
171
|
+
/^(get|list|search|listForRecord|listMine|sql|global|count|unreadCount|version|versions)$/.test(
|
|
172
|
+
verb,
|
|
173
|
+
)
|
|
174
|
+
)
|
|
175
|
+
return "read";
|
|
176
|
+
if (verb === "createMany") return "bulk-write";
|
|
177
|
+
if (/^(delete|erase|merge|deleteMany)$/.test(verb)) return "destructive";
|
|
178
|
+
return "write";
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function objectOf(operation: string, input: Record<string, unknown>): string | null {
|
|
182
|
+
// As the host's operationObject: record.* and my.* name their object in the input.
|
|
183
|
+
if (
|
|
184
|
+
operation.startsWith("record.") ||
|
|
185
|
+
operation.startsWith("my.") ||
|
|
186
|
+
operation === "state.resolve"
|
|
187
|
+
)
|
|
188
|
+
return typeof input.object === "string" ? input.object : null;
|
|
189
|
+
const prefix = operation.split(".")[0] ?? "";
|
|
190
|
+
return (CORE_OBJECT_NAMES as readonly string[]).includes(prefix) ? prefix : null;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
let sequence = 0;
|
|
194
|
+
|
|
195
|
+
export function createTestHost(extension: Extension, options: TestHostOptions = {}): TestHost {
|
|
196
|
+
const { manifest: validated, issues } = validateManifest(toManifest(extension), options.validate);
|
|
197
|
+
const manifest = validated ?? toManifest(extension);
|
|
198
|
+
const records = new Map<string, Map<string, Values>>();
|
|
199
|
+
for (const [object, rows] of Object.entries(options.records ?? {})) {
|
|
200
|
+
records.set(object, new Map(rows.map((row) => [row.id, { ...row }])));
|
|
201
|
+
}
|
|
202
|
+
const table = (object: string) => {
|
|
203
|
+
let rows = records.get(object);
|
|
204
|
+
if (!rows) {
|
|
205
|
+
rows = new Map();
|
|
206
|
+
records.set(object, rows);
|
|
207
|
+
}
|
|
208
|
+
return rows;
|
|
209
|
+
};
|
|
210
|
+
const calls: TestHost["calls"] = [];
|
|
211
|
+
const logs: TestHost["logs"] = [];
|
|
212
|
+
const storage = new Map<string, unknown>();
|
|
213
|
+
const versions = new Map<
|
|
214
|
+
string,
|
|
215
|
+
{ version: number; publishedAt: string; values: Record<string, unknown> }[]
|
|
216
|
+
>();
|
|
217
|
+
/** A person publishing a record (ADR 0446): its `publishable.content` becomes a version. */
|
|
218
|
+
const publish = (object: string, id: string) => {
|
|
219
|
+
const local = object.startsWith(`${manifest.id}.`) ? object.slice(manifest.id.length + 1) : "";
|
|
220
|
+
const content = manifest.objects[local]?.publishable?.content;
|
|
221
|
+
if (!content) throw new ExtensionToolError("invalid_input", `${object} is not publishable`);
|
|
222
|
+
const row = table(object).get(id);
|
|
223
|
+
if (!row) throw new ExtensionToolError("not_found", `No ${object} with id ${id}`);
|
|
224
|
+
const list = versions.get(`${object}|${id}`) ?? [];
|
|
225
|
+
const version = list.length + 1;
|
|
226
|
+
list.push({
|
|
227
|
+
version,
|
|
228
|
+
publishedAt: new Date().toISOString(),
|
|
229
|
+
values: structuredClone(Object.fromEntries(content.map((f) => [f, row[f] ?? null]))),
|
|
230
|
+
});
|
|
231
|
+
versions.set(`${object}|${id}`, list);
|
|
232
|
+
row.publishedVersion = version;
|
|
233
|
+
return version;
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
// Records are stored flat ({ id, ...values }) and returned in the host's record shape.
|
|
237
|
+
const titleOf = (object: string, row: Values): string | null => {
|
|
238
|
+
const local = object.startsWith(`${manifest.id}.`)
|
|
239
|
+
? object.slice(manifest.id.length + 1)
|
|
240
|
+
: null;
|
|
241
|
+
const field = local ? manifest.objects[local]?.titleField : undefined;
|
|
242
|
+
const title = field ? row[field] : (row.name ?? row.displayName ?? row.title);
|
|
243
|
+
return title == null ? null : String(title);
|
|
244
|
+
};
|
|
245
|
+
const shape = (object: string, row: Values) => {
|
|
246
|
+
const { id, ...values } = row;
|
|
247
|
+
return { object, id, title: titleOf(object, row), values, createdAt: null, updatedAt: null };
|
|
248
|
+
};
|
|
249
|
+
const matches = (row: Values, filter: unknown): boolean => {
|
|
250
|
+
if (!filter || typeof filter !== "object") return true;
|
|
251
|
+
const f = filter as {
|
|
252
|
+
and?: unknown[];
|
|
253
|
+
or?: unknown[];
|
|
254
|
+
field?: string;
|
|
255
|
+
op?: string;
|
|
256
|
+
value?: unknown;
|
|
257
|
+
};
|
|
258
|
+
if (f.and) return f.and.every((child) => matches(row, child));
|
|
259
|
+
if (f.or) return f.or.some((child) => matches(row, child));
|
|
260
|
+
const value = f.field ? row[f.field] : undefined;
|
|
261
|
+
switch (f.op) {
|
|
262
|
+
case "eq":
|
|
263
|
+
return value === f.value;
|
|
264
|
+
case "neq":
|
|
265
|
+
return value !== f.value;
|
|
266
|
+
case "is_null":
|
|
267
|
+
return value == null;
|
|
268
|
+
case "is_not_null":
|
|
269
|
+
return value != null;
|
|
270
|
+
case "in":
|
|
271
|
+
return Array.isArray(f.value) && f.value.includes(value);
|
|
272
|
+
case "not_in":
|
|
273
|
+
return Array.isArray(f.value) && !f.value.includes(value);
|
|
274
|
+
case "lt":
|
|
275
|
+
return value != null && (value as never) < (f.value as never);
|
|
276
|
+
case "lte":
|
|
277
|
+
return value != null && (value as never) <= (f.value as never);
|
|
278
|
+
case "gt":
|
|
279
|
+
return value != null && (value as never) > (f.value as never);
|
|
280
|
+
case "gte":
|
|
281
|
+
return value != null && (value as never) >= (f.value as never);
|
|
282
|
+
case "contains":
|
|
283
|
+
return String(value ?? "").includes(String(f.value));
|
|
284
|
+
case "not_contains":
|
|
285
|
+
return !String(value ?? "").includes(String(f.value));
|
|
286
|
+
case "starts_with":
|
|
287
|
+
return String(value ?? "").startsWith(String(f.value));
|
|
288
|
+
case "ends_with":
|
|
289
|
+
return String(value ?? "").endsWith(String(f.value));
|
|
290
|
+
default:
|
|
291
|
+
throw new ExtensionToolError(
|
|
292
|
+
"unsupported",
|
|
293
|
+
`The test host does not fake filter op ${f.op}`,
|
|
294
|
+
);
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
// A document field's value is checked against its schema, as the host checks it (ADR 0445).
|
|
298
|
+
const checkDocuments = (object: string, values: Record<string, unknown>) => {
|
|
299
|
+
const local = object.startsWith(`${manifest.id}.`) ? object.slice(manifest.id.length + 1) : "";
|
|
300
|
+
for (const [name, field] of Object.entries(manifest.objects[local]?.fields ?? {})) {
|
|
301
|
+
const schema = documentSchemaOf(field);
|
|
302
|
+
if (!schema || values[name] === undefined || values[name] === null) continue;
|
|
303
|
+
const maxBytes = documentMaxBytesOf(field);
|
|
304
|
+
const result = validateDocument(
|
|
305
|
+
schema,
|
|
306
|
+
values[name],
|
|
307
|
+
maxBytes === undefined ? {} : { maxBytes },
|
|
308
|
+
);
|
|
309
|
+
if (!result.ok) {
|
|
310
|
+
const first = result.issues[0];
|
|
311
|
+
throw new ExtensionToolError(
|
|
312
|
+
"invalid_input",
|
|
313
|
+
`Invalid value for ${object}.${name}: ${[name, ...(first?.path ?? [])].join(".")}: ${first?.message}`,
|
|
314
|
+
{ field: name, issues: result.issues },
|
|
315
|
+
);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
const create = (object: string, values: Record<string, unknown>) => {
|
|
320
|
+
checkDocuments(object, values);
|
|
321
|
+
sequence += 1;
|
|
322
|
+
const id = `rec_test${sequence}`;
|
|
323
|
+
// A record with a state machine starts in its initial state, as the host makes it.
|
|
324
|
+
const local = object.startsWith(`${manifest.id}.`) ? object.slice(manifest.id.length + 1) : "";
|
|
325
|
+
const states = manifest.objects[local]?.states;
|
|
326
|
+
const initial =
|
|
327
|
+
states && values[states.field] == null ? { [states.field]: states.initial } : {};
|
|
328
|
+
const row = { ...initial, ...values, id };
|
|
329
|
+
table(object).set(id, row);
|
|
330
|
+
return row;
|
|
331
|
+
};
|
|
332
|
+
const builtIn: Record<string, OperationFake> = {
|
|
333
|
+
"record.create": (input) => {
|
|
334
|
+
const object = String(input.object);
|
|
335
|
+
return shape(object, create(object, input.values as Record<string, unknown>));
|
|
336
|
+
},
|
|
337
|
+
"record.createMany": (input) => {
|
|
338
|
+
const object = String(input.object);
|
|
339
|
+
const rows = (input.records as Record<string, unknown>[]).map((values) => {
|
|
340
|
+
checkDocuments(object, values);
|
|
341
|
+
return values;
|
|
342
|
+
});
|
|
343
|
+
return { ids: rows.map((values) => create(object, values).id) };
|
|
344
|
+
},
|
|
345
|
+
// Versions a person published (`host.publish`), ADR 0446.
|
|
346
|
+
"record.version": (input) => {
|
|
347
|
+
const list = versions.get(`${input.object}|${input.id}`) ?? [];
|
|
348
|
+
const found =
|
|
349
|
+
input.version === undefined
|
|
350
|
+
? list.at(-1)
|
|
351
|
+
: list.find((v) => v.version === Number(input.version));
|
|
352
|
+
if (!found) {
|
|
353
|
+
throw new ExtensionToolError("not_found", `No published version of ${input.id}`);
|
|
354
|
+
}
|
|
355
|
+
return {
|
|
356
|
+
version: found.version,
|
|
357
|
+
current: found === list.at(-1),
|
|
358
|
+
publishedAt: found.publishedAt,
|
|
359
|
+
publishedBy: "usr_admin",
|
|
360
|
+
note: null,
|
|
361
|
+
bytes: JSON.stringify(found.values).length,
|
|
362
|
+
values: structuredClone(found.values),
|
|
363
|
+
};
|
|
364
|
+
},
|
|
365
|
+
"record.get": (input) => {
|
|
366
|
+
const object = String(input.object);
|
|
367
|
+
const row = table(object).get(String(input.id));
|
|
368
|
+
if (!row) throw new ExtensionToolError("not_found", `No ${object} with id ${input.id}`);
|
|
369
|
+
return shape(object, row);
|
|
370
|
+
},
|
|
371
|
+
"record.update": (input) => {
|
|
372
|
+
const object = String(input.object);
|
|
373
|
+
const rows = table(object);
|
|
374
|
+
const row = rows.get(String(input.id));
|
|
375
|
+
if (!row) throw new ExtensionToolError("not_found", `No ${object} with id ${input.id}`);
|
|
376
|
+
if (typeof input.from === "string") {
|
|
377
|
+
// `from` (ADR 0437): move only out of this state, refused as the host refuses it.
|
|
378
|
+
const local = object.startsWith(`${manifest.id}.`)
|
|
379
|
+
? object.slice(manifest.id.length + 1)
|
|
380
|
+
: "";
|
|
381
|
+
const spec = manifest.objects[local];
|
|
382
|
+
const field = spec?.states?.field ?? spec?.stages?.field;
|
|
383
|
+
const values = input.values as Record<string, unknown>;
|
|
384
|
+
if (!field || values[field] === undefined || values[field] === input.from) {
|
|
385
|
+
throw new ExtensionToolError(
|
|
386
|
+
"invalid_input",
|
|
387
|
+
`With "from", the write must move ${field}`,
|
|
388
|
+
);
|
|
389
|
+
}
|
|
390
|
+
if (row[field] !== input.from) {
|
|
391
|
+
throw new ExtensionToolError("conflict", `${object} is no longer ${input.from}`, {
|
|
392
|
+
reason: "not_in_position",
|
|
393
|
+
field,
|
|
394
|
+
from: input.from,
|
|
395
|
+
current: row[field] ?? null,
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
checkDocuments(object, input.values as Record<string, unknown>);
|
|
400
|
+
const next = { ...row, ...(input.values as Record<string, unknown>), id: row.id };
|
|
401
|
+
rows.set(row.id, next);
|
|
402
|
+
return shape(object, next);
|
|
403
|
+
},
|
|
404
|
+
"record.delete": (input) => {
|
|
405
|
+
table(String(input.object)).delete(String(input.id));
|
|
406
|
+
return { id: input.id };
|
|
407
|
+
},
|
|
408
|
+
"record.list": (input) => {
|
|
409
|
+
const object = String(input.object);
|
|
410
|
+
return {
|
|
411
|
+
items: [...table(object).values()]
|
|
412
|
+
.filter((row) => matches(row, input.filter))
|
|
413
|
+
.map((row) => shape(object, row)),
|
|
414
|
+
nextCursor: null,
|
|
415
|
+
};
|
|
416
|
+
},
|
|
417
|
+
};
|
|
418
|
+
for (const object of CORE_OBJECT_NAMES) {
|
|
419
|
+
builtIn[`${object}.get`] = (input) => builtIn["record.get"]?.({ ...input, object });
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// Tasks, in the task operations' shape (status, assignee, links).
|
|
423
|
+
const taskShape = (row: Values) => ({
|
|
424
|
+
title: null,
|
|
425
|
+
notes: null,
|
|
426
|
+
dueAt: null,
|
|
427
|
+
status: "open",
|
|
428
|
+
assigneeId: null,
|
|
429
|
+
links: [],
|
|
430
|
+
...row,
|
|
431
|
+
});
|
|
432
|
+
const requireTask = (id: unknown) => {
|
|
433
|
+
const row = table("task").get(String(id));
|
|
434
|
+
if (!row) throw new ExtensionToolError("not_found", `No task with id ${id}`);
|
|
435
|
+
return row;
|
|
436
|
+
};
|
|
437
|
+
Object.assign(builtIn, {
|
|
438
|
+
"task.create": (input: Record<string, unknown>) => {
|
|
439
|
+
sequence += 1;
|
|
440
|
+
const row: Values = {
|
|
441
|
+
status: "open",
|
|
442
|
+
assigneeId: null,
|
|
443
|
+
links: [],
|
|
444
|
+
...input,
|
|
445
|
+
id: `tsk_test${sequence}`,
|
|
446
|
+
};
|
|
447
|
+
table("task").set(row.id, row);
|
|
448
|
+
return taskShape(row);
|
|
449
|
+
},
|
|
450
|
+
"task.get": (input: Record<string, unknown>) => taskShape(requireTask(input.id)),
|
|
451
|
+
"task.update": (input: Record<string, unknown>) => {
|
|
452
|
+
const row = { ...requireTask(input.id), ...input } as Values;
|
|
453
|
+
table("task").set(row.id, row);
|
|
454
|
+
return taskShape(row);
|
|
455
|
+
},
|
|
456
|
+
"task.complete": (input: Record<string, unknown>) => {
|
|
457
|
+
const row = { ...requireTask(input.id), status: "done" } as Values;
|
|
458
|
+
table("task").set(row.id, row);
|
|
459
|
+
return taskShape(row);
|
|
460
|
+
},
|
|
461
|
+
"task.list": (input: Record<string, unknown>) => {
|
|
462
|
+
const linked = (row: Values, filter: unknown): boolean => {
|
|
463
|
+
const f = filter as { and?: unknown[]; field?: string; value?: unknown } | undefined;
|
|
464
|
+
if (f?.and) return f.and.every((child) => linked(row, child));
|
|
465
|
+
if (f?.field !== "linkedRecordId") return matches(row, f);
|
|
466
|
+
return (row.links as { id: string }[]).some((link) => link.id === f.value);
|
|
467
|
+
};
|
|
468
|
+
return {
|
|
469
|
+
items: [...table("task").values()]
|
|
470
|
+
.filter((row) => linked(row, input.filter))
|
|
471
|
+
.map(taskShape),
|
|
472
|
+
nextCursor: null,
|
|
473
|
+
};
|
|
474
|
+
},
|
|
475
|
+
});
|
|
476
|
+
|
|
477
|
+
// notification.send: resolves recipients like the host (managerOf → the admins, with a note,
|
|
478
|
+
// since users have no manager field) and keeps one notification per (user, dedupeKey).
|
|
479
|
+
const users = options.users ?? [{ id: "usr_admin", role: "admin" as const }];
|
|
480
|
+
const notifications: SentNotification[] = [];
|
|
481
|
+
const delivered = new Set<string>();
|
|
482
|
+
let currentStep: string | null = null;
|
|
483
|
+
let observer:
|
|
484
|
+
| ((operation: string, input: Record<string, unknown>, value: unknown) => void)
|
|
485
|
+
| null = null;
|
|
486
|
+
builtIn["notification.send"] = (input) => {
|
|
487
|
+
const notes: string[] = [];
|
|
488
|
+
const admins = users.filter((u) => u.role === "admin").map((u) => u.id);
|
|
489
|
+
const ids: string[] = [];
|
|
490
|
+
for (const to of input.to as Record<string, unknown>[]) {
|
|
491
|
+
if (typeof to.userId === "string") ids.push(to.userId);
|
|
492
|
+
else if (to.role === "admin") ids.push(...admins);
|
|
493
|
+
else if (typeof to.managerOf === "string") {
|
|
494
|
+
notes.push("Users have no manager field: sent to the admins instead");
|
|
495
|
+
ids.push(...admins);
|
|
496
|
+
} else if (typeof to.field === "string") {
|
|
497
|
+
const ref = to.record as { object: string; id: string };
|
|
498
|
+
const value = table(ref.object).get(ref.id)?.[to.field];
|
|
499
|
+
if (typeof value === "string" && value) ids.push(value);
|
|
500
|
+
else notes.push(`${ref.object} ${ref.id} has no ${to.field}`);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
const key = typeof input.dedupeKey === "string" ? input.dedupeKey : null;
|
|
504
|
+
const userIds = [...new Set(ids)].filter((id) => !key || !delivered.has(`${id}\n${key}`));
|
|
505
|
+
for (const id of userIds) if (key) delivered.add(`${id}\n${key}`);
|
|
506
|
+
const { dedupeKey: _key, type, ...rest } = input as unknown as NotificationSendInput;
|
|
507
|
+
notifications.push({
|
|
508
|
+
...rest,
|
|
509
|
+
type: String(type ?? "system.message"),
|
|
510
|
+
dedupeKey: key,
|
|
511
|
+
userIds,
|
|
512
|
+
notes,
|
|
513
|
+
step: currentStep,
|
|
514
|
+
});
|
|
515
|
+
return { sent: userIds.length, userIds, notes };
|
|
516
|
+
};
|
|
517
|
+
|
|
518
|
+
const has = (name: string) => manifest.permissions.modules.includes(name as never);
|
|
519
|
+
const raw: RawHostModules = {};
|
|
520
|
+
if (has("ops")) {
|
|
521
|
+
raw.ops = {
|
|
522
|
+
call: async (operation, input) => {
|
|
523
|
+
const name = String(operation);
|
|
524
|
+
const body = (input ?? {}) as Record<string, unknown>;
|
|
525
|
+
const decision = checkGrant(manifest.id, manifest.permissions, {
|
|
526
|
+
operation: name,
|
|
527
|
+
risk: riskOf(name),
|
|
528
|
+
object: objectOf(name, body),
|
|
529
|
+
});
|
|
530
|
+
calls.push({ operation: name, input: body, allowed: decision.ok });
|
|
531
|
+
if (!decision.ok)
|
|
532
|
+
return { ok: false, error: { code: "forbidden", message: decision.reason } };
|
|
533
|
+
const fake = options.operations?.[name] ?? builtIn[name];
|
|
534
|
+
if (!fake) {
|
|
535
|
+
return {
|
|
536
|
+
ok: false,
|
|
537
|
+
error: { code: "unknown_operation", message: `No fake for ${name}` },
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
try {
|
|
541
|
+
const value = structuredClone(await fake(body));
|
|
542
|
+
observer?.(name, body, value);
|
|
543
|
+
return { ok: true, value };
|
|
544
|
+
} catch (error) {
|
|
545
|
+
const e = error as { code?: string; message?: string; details?: unknown };
|
|
546
|
+
// As the real host: a refusal's details (its rule) reach the tool, as OpsCallError's.
|
|
547
|
+
return {
|
|
548
|
+
ok: false,
|
|
549
|
+
error: {
|
|
550
|
+
code: e.code ?? "internal",
|
|
551
|
+
message: e.message ?? String(error),
|
|
552
|
+
...(e.code && e.code !== "internal" && e.details !== undefined
|
|
553
|
+
? { details: e.details }
|
|
554
|
+
: {}),
|
|
555
|
+
},
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
},
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
if (has("storage")) {
|
|
562
|
+
raw.storage = {
|
|
563
|
+
get: async (key) => storage.get(String(key)) ?? null,
|
|
564
|
+
set: async (key, value) => {
|
|
565
|
+
storage.set(String(key), structuredClone(value));
|
|
566
|
+
},
|
|
567
|
+
del: async (key) => {
|
|
568
|
+
storage.delete(String(key));
|
|
569
|
+
},
|
|
570
|
+
list: async (prefix) =>
|
|
571
|
+
[...storage]
|
|
572
|
+
.filter(([key]) => key.startsWith(String(prefix ?? "")))
|
|
573
|
+
.map(([key, value]) => ({ key, value })),
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
if (has("log")) {
|
|
577
|
+
raw.log = {
|
|
578
|
+
write: async (level, message, data) => {
|
|
579
|
+
logs.push({ level: String(level), message: String(message), data });
|
|
580
|
+
},
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
const gatekeeperCalls: GatekeeperCall[] = [];
|
|
584
|
+
for (const name of manifest.permissions.modules) {
|
|
585
|
+
if (!(GATEKEEPER_MODULES as readonly string[]).includes(name)) continue;
|
|
586
|
+
const declared = Object.values(manifest.automations).flatMap((a) =>
|
|
587
|
+
(a.connections ?? []).filter((c) => c.gatekeeper === name).map((c) => c.id),
|
|
588
|
+
);
|
|
589
|
+
(raw as Record<string, unknown>)[name] = {
|
|
590
|
+
connections: async () =>
|
|
591
|
+
[...new Set(declared.length ? declared : ["default"])].map((id) => ({
|
|
592
|
+
id,
|
|
593
|
+
title: id,
|
|
594
|
+
resources: [{ key: `${id}-resource`, bindingName: "RESOURCE", tsType: "unknown" }],
|
|
595
|
+
})),
|
|
596
|
+
call: async (connectionId: unknown, resource: unknown, method: unknown, args: unknown) => {
|
|
597
|
+
const call = {
|
|
598
|
+
connectionId: String(connectionId),
|
|
599
|
+
resource: String(resource),
|
|
600
|
+
method: String(method),
|
|
601
|
+
args: (args as unknown[]) ?? [],
|
|
602
|
+
};
|
|
603
|
+
gatekeeperCalls.push({ gatekeeper: name, ...call, step: currentStep });
|
|
604
|
+
try {
|
|
605
|
+
const fake = options.gatekeepers?.[name];
|
|
606
|
+
const value = fake ? await fake(call) : { status: "pending" };
|
|
607
|
+
return { ok: true, value: { value: structuredClone(value), pending: [], applied: [] } };
|
|
608
|
+
} catch (error) {
|
|
609
|
+
const e = error as { code?: string; message?: string };
|
|
610
|
+
return {
|
|
611
|
+
ok: false,
|
|
612
|
+
error: { code: e.code ?? "internal", message: e.message ?? String(error) },
|
|
613
|
+
};
|
|
614
|
+
}
|
|
615
|
+
},
|
|
616
|
+
types: async () => "",
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
if (has("ai")) {
|
|
620
|
+
const ai: AiModule = {
|
|
621
|
+
summarise: async (text) => String(text).slice(0, 100),
|
|
622
|
+
extract: async (_text, fields) =>
|
|
623
|
+
Object.fromEntries(Object.keys(fields).map((k) => [k, null])),
|
|
624
|
+
classify: async (_text, labels) => ({ label: labels[0] ?? "" }),
|
|
625
|
+
...options.ai,
|
|
626
|
+
};
|
|
627
|
+
raw.ai = {
|
|
628
|
+
summarise: (text, opts) => ai.summarise(String(text), opts as never),
|
|
629
|
+
extract: (text, fields) => ai.extract(String(text), fields as Record<string, string>),
|
|
630
|
+
classify: (text, labels) => ai.classify(String(text), labels as string[]),
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
async function runAutomation(
|
|
635
|
+
name: string,
|
|
636
|
+
run: AutomationRunOptions = {},
|
|
637
|
+
): Promise<AutomationRunResult> {
|
|
638
|
+
const automation = extension.automations?.[name];
|
|
639
|
+
if (!automation) {
|
|
640
|
+
throw new ExtensionToolError("unknown_automation", `No automation named ${name}`);
|
|
641
|
+
}
|
|
642
|
+
const declared = new Map(automation.steps.map((step) => [step.name, step]));
|
|
643
|
+
const result: AutomationRunResult = {
|
|
644
|
+
matched: true,
|
|
645
|
+
value: null,
|
|
646
|
+
error: null,
|
|
647
|
+
steps: [],
|
|
648
|
+
writes: [],
|
|
649
|
+
notifications: [],
|
|
650
|
+
undeclared: [],
|
|
651
|
+
};
|
|
652
|
+
let row: Values | undefined;
|
|
653
|
+
if (run.record) {
|
|
654
|
+
row = records.get(run.record.object)?.get(run.record.id);
|
|
655
|
+
if (!row) {
|
|
656
|
+
throw new ExtensionToolError(
|
|
657
|
+
"not_found",
|
|
658
|
+
`Seed ${run.record.object} ${run.record.id} in records to use it as the trigger record`,
|
|
659
|
+
);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
if (automation.conditions && row && !matches(row, automation.conditions)) {
|
|
663
|
+
result.matched = false;
|
|
664
|
+
return result;
|
|
665
|
+
}
|
|
666
|
+
const event: AutomationEvent = {
|
|
667
|
+
automation: `${manifest.id}.${name}`,
|
|
668
|
+
runId: run.runId ?? "arn_TEST",
|
|
669
|
+
trigger: automation.trigger.type,
|
|
670
|
+
...(run.record && row
|
|
671
|
+
? {
|
|
672
|
+
record: {
|
|
673
|
+
object: run.record.object,
|
|
674
|
+
id: run.record.id,
|
|
675
|
+
data: Object.fromEntries(Object.entries(row).filter(([key]) => key !== "id")),
|
|
676
|
+
title: titleOf(run.record.object, row),
|
|
677
|
+
},
|
|
678
|
+
}
|
|
679
|
+
: {}),
|
|
680
|
+
...(run.change ? { change: run.change } : {}),
|
|
681
|
+
...(run.period ? { period: run.period } : {}),
|
|
682
|
+
...(run.manual ? { manual: run.manual } : {}),
|
|
683
|
+
...(run.approval ? { approval: run.approval } : {}),
|
|
684
|
+
test: run.test ?? false,
|
|
685
|
+
};
|
|
686
|
+
|
|
687
|
+
const ran = new Set<string>();
|
|
688
|
+
const claim = (stepName: string, kind: "do" | "sleep" | "waitForEvent") => {
|
|
689
|
+
const step = declared.get(stepName);
|
|
690
|
+
if (!step || (step.kind ?? "do") !== kind) {
|
|
691
|
+
throw new AutomationStepError(
|
|
692
|
+
`step.${kind}("${stepName}") is not a declared ${kind} step of ${name}; declare it in steps`,
|
|
693
|
+
);
|
|
694
|
+
}
|
|
695
|
+
if (ran.has(stepName)) {
|
|
696
|
+
throw new AutomationStepError(`Step ${stepName} already ran; each step runs once per run`);
|
|
697
|
+
}
|
|
698
|
+
ran.add(stepName);
|
|
699
|
+
return step;
|
|
700
|
+
};
|
|
701
|
+
const declaredWrites = (stepName: string | null) => {
|
|
702
|
+
const step = stepName ? declared.get(stepName) : undefined;
|
|
703
|
+
return step && (step.kind ?? "do") === "do"
|
|
704
|
+
? ((step as { writes?: { object: string }[] }).writes ?? []).map((w) => w.object)
|
|
705
|
+
: [];
|
|
706
|
+
};
|
|
707
|
+
const declaresNotify = (stepName: string | null) => {
|
|
708
|
+
const step = stepName ? declared.get(stepName) : undefined;
|
|
709
|
+
return Boolean((step as { notifies?: unknown[] } | undefined)?.notifies?.length);
|
|
710
|
+
};
|
|
711
|
+
const where = (stepName: string | null) =>
|
|
712
|
+
stepName ? `step ${stepName}` : "run (outside a step)";
|
|
713
|
+
const notificationsBefore = notifications.length;
|
|
714
|
+
observer = (operation, input, value) => {
|
|
715
|
+
if (operation === "notification.send") {
|
|
716
|
+
if (!declaresNotify(currentStep)) {
|
|
717
|
+
result.undeclared.push(`${where(currentStep)} sent a notification (not in its notifies)`);
|
|
718
|
+
}
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
if (riskOf(operation) === "read") return;
|
|
722
|
+
const object = objectOf(operation, input);
|
|
723
|
+
const id =
|
|
724
|
+
value && typeof value === "object" && "id" in value
|
|
725
|
+
? String((value as { id: unknown }).id)
|
|
726
|
+
: null;
|
|
727
|
+
result.writes.push({ step: currentStep, operation, object, id });
|
|
728
|
+
if (!object || !declaredWrites(currentStep).includes(object)) {
|
|
729
|
+
result.undeclared.push(
|
|
730
|
+
`${where(currentStep)} called ${operation}${object ? ` on ${object}` : ""} (not in its writes)`,
|
|
731
|
+
);
|
|
732
|
+
}
|
|
733
|
+
};
|
|
734
|
+
|
|
735
|
+
const pending: Promise<unknown>[] = [];
|
|
736
|
+
const base = buildContext(extension, raw, pending);
|
|
737
|
+
const notifyCounts = new Map<string, number>();
|
|
738
|
+
const ctx: AutomationContext = {
|
|
739
|
+
...base,
|
|
740
|
+
async notify(to, message) {
|
|
741
|
+
const key = currentStep ?? "run";
|
|
742
|
+
const n = (notifyCounts.get(key) ?? 0) + 1;
|
|
743
|
+
notifyCounts.set(key, n);
|
|
744
|
+
const input = notificationInput(event, to, message, `${key}:${n}`);
|
|
745
|
+
const sent = await base.ops.call<{ sent: number }>("notification.send", input);
|
|
746
|
+
return { sent: sent.sent };
|
|
747
|
+
},
|
|
748
|
+
};
|
|
749
|
+
const stepApi: AutomationStepApi = {
|
|
750
|
+
async do<T>(stepName: string, a: unknown, b?: unknown): Promise<T> {
|
|
751
|
+
const fn = (typeof a === "function" ? a : b) as () => Promise<T> | T;
|
|
752
|
+
const step = claim(stepName, "do");
|
|
753
|
+
if (typeof a === "object" && a !== null) {
|
|
754
|
+
const intent = a as { writes?: { object: string }[] };
|
|
755
|
+
const allowed = declaredWrites(step.name);
|
|
756
|
+
for (const write of intent.writes ?? []) {
|
|
757
|
+
if (!allowed.includes(write.object)) {
|
|
758
|
+
throw new AutomationStepError(
|
|
759
|
+
`step.do("${stepName}") says it writes ${write.object}, but its declaration does not`,
|
|
760
|
+
);
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
const first = calls.length;
|
|
765
|
+
currentStep = stepName;
|
|
766
|
+
try {
|
|
767
|
+
const value = await fn();
|
|
768
|
+
result.steps.push({
|
|
769
|
+
name: stepName,
|
|
770
|
+
kind: "do",
|
|
771
|
+
value: value === undefined ? null : structuredClone(value),
|
|
772
|
+
calls: calls.slice(first),
|
|
773
|
+
});
|
|
774
|
+
return value;
|
|
775
|
+
} finally {
|
|
776
|
+
currentStep = null;
|
|
777
|
+
}
|
|
778
|
+
},
|
|
779
|
+
async sleep(stepName, duration) {
|
|
780
|
+
claim(stepName, "sleep");
|
|
781
|
+
result.steps.push({
|
|
782
|
+
name: stepName,
|
|
783
|
+
kind: "sleep",
|
|
784
|
+
skippedMs: durationMs(duration),
|
|
785
|
+
calls: [],
|
|
786
|
+
});
|
|
787
|
+
},
|
|
788
|
+
async waitForEvent<T>(stepName: string): Promise<T | null> {
|
|
789
|
+
const step = claim(stepName, "waitForEvent") as { timeout?: number | string };
|
|
790
|
+
const value = (run.events?.[stepName] ?? null) as T | null;
|
|
791
|
+
result.steps.push({
|
|
792
|
+
name: stepName,
|
|
793
|
+
kind: "waitForEvent",
|
|
794
|
+
value,
|
|
795
|
+
skippedMs: durationMs((step.timeout ?? "7 days") as never),
|
|
796
|
+
calls: [],
|
|
797
|
+
});
|
|
798
|
+
return value;
|
|
799
|
+
},
|
|
800
|
+
};
|
|
801
|
+
try {
|
|
802
|
+
const value = await automation.run(event, stepApi, ctx);
|
|
803
|
+
result.value = value === undefined ? null : structuredClone(value);
|
|
804
|
+
} catch (error) {
|
|
805
|
+
const e = error as { code?: unknown; message?: unknown };
|
|
806
|
+
result.error = {
|
|
807
|
+
code: typeof e.code === "string" ? e.code : "automation_error",
|
|
808
|
+
message: typeof e.message === "string" ? e.message : String(error),
|
|
809
|
+
};
|
|
810
|
+
} finally {
|
|
811
|
+
observer = null;
|
|
812
|
+
currentStep = null;
|
|
813
|
+
await Promise.all(pending);
|
|
814
|
+
}
|
|
815
|
+
result.notifications = notifications.slice(notificationsBefore);
|
|
816
|
+
return result;
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
return {
|
|
820
|
+
manifest,
|
|
821
|
+
issues,
|
|
822
|
+
calls,
|
|
823
|
+
logs,
|
|
824
|
+
storage,
|
|
825
|
+
records,
|
|
826
|
+
notifications,
|
|
827
|
+
gatekeeperCalls,
|
|
828
|
+
runAutomation,
|
|
829
|
+
publish,
|
|
830
|
+
async runTool<T>(
|
|
831
|
+
tool: string,
|
|
832
|
+
input: unknown,
|
|
833
|
+
options: { caller?: StartedBy } = {},
|
|
834
|
+
): Promise<T> {
|
|
835
|
+
const caller = options.caller ?? { kind: "staff", userId: "usr_admin", name: "Admin" };
|
|
836
|
+
const response = await runExtension(extension, { kind: "tool", tool, input, caller }, raw);
|
|
837
|
+
if (!response.ok) {
|
|
838
|
+
throw new ExtensionToolError(
|
|
839
|
+
response.error.code,
|
|
840
|
+
response.error.message,
|
|
841
|
+
response.error.details,
|
|
842
|
+
);
|
|
843
|
+
}
|
|
844
|
+
return response.value as T;
|
|
845
|
+
},
|
|
846
|
+
};
|
|
847
|
+
}
|