@devosurf/tesser-sdk 0.1.0-alpha.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,36 @@
1
+ # @devosurf/tesser-sdk
2
+
3
+ The authoring SDK. One durable-function primitive; durability comes only from `ctx.step()`.
4
+
5
+ > Status: **implemented.** Zero runtime dependencies; schemas through the Standard Schema interface (zod / valibot / arktype all fit). Connector *authoring* lives at `@devosurf/tesser-sdk/connector`; runtime/tooling machinery at `@devosurf/tesser-sdk/internal` (deliberately outside the stable facade). The compact agent-facing reference is [`llms.txt`](./llms.txt).
6
+
7
+ ```ts
8
+ import { defineAutomation, onSchedule } from "@devosurf/tesser-sdk";
9
+ import { github, slack } from "@devosurf/tesser-connectors";
10
+ import { z } from "zod";
11
+
12
+ export default defineAutomation({
13
+ id: "daily-digest",
14
+ trigger: onSchedule({ cron: "0 9 * * *", tz: "America/New_York" }),
15
+ connections: { github, slack },
16
+ output: z.object({ posted: z.boolean(), count: z.number() }),
17
+
18
+ run: async (_input, ctx) => {
19
+ // Plain TS control flow. Durability ONLY from ctx.step().
20
+ const issues = await ctx.step("fetch-open-issues", () =>
21
+ ctx.connections.github.issues.list({ state: "open", labels: ["bug"] }),
22
+ );
23
+ if (issues.length === 0) return { posted: false, count: 0 };
24
+
25
+ await ctx.step("post-to-slack", () =>
26
+ ctx.connections.slack.chat.postMessage({
27
+ channel: "#eng-standup",
28
+ text: `:bug: ${issues.length} open bugs today`,
29
+ }),
30
+ );
31
+ return { posted: true, count: issues.length };
32
+ },
33
+ });
34
+ ```
35
+
36
+ The agent never sees a token — `ctx.connections.*` are injected by the credential broker at call time (ADR-0004). To require a credential that may not exist yet, declare it on the def — `connections: { stripe }` for a connector, or `secrets: { … }` for a raw value; if it's missing on the target instance, deploy halts and a human is handed a connect link (ADR-0005, ADR-0010).
package/llms.txt ADDED
@@ -0,0 +1,90 @@
1
+ # @devosurf/tesser-sdk — the authoring surface (for agents)
2
+
3
+ One file = one automation. Write ordinary async TypeScript. THE ONE DURABILITY RULE:
4
+ wrap every side effect (connector call, any external I/O, emit) in `ctx.step("name", fn)`.
5
+ Suspensions (ctx.sleep / ctx.waitForSignal) are NOT side effects — never put them in a step.
6
+
7
+ ## Define an automation
8
+
9
+ import { defineAutomation, onSchedule, secret } from "@devosurf/tesser-sdk";
10
+ import { github, slack } from "@devosurf/tesser-connectors";
11
+ import { z } from "zod";
12
+
13
+ export default defineAutomation({
14
+ id: "daily-digest", // kebab-case, = its directory name
15
+ trigger: onSchedule({ cron: "0 9 * * *", tz: "UTC" }),// exactly ONE trigger
16
+ connections: { github, slack }, // typed map; mirrored on ctx.connections
17
+ secrets: { signingKey: secret({ describe: "…" }) }, // raw values; mirrored on ctx.secrets
18
+ input: z.object({ … }).optional(), // validates trigger payload
19
+ output: z.object({ … }), // validates the return value
20
+ retry: { maxAttempts: 3 }, // default step retry policy
21
+ concurrency: { limit: 1, key: (i) => i.userId, onConflict: "queue" }, // or "drop"
22
+ run: async (input, ctx) => { …; return …; },
23
+ });
24
+
25
+ ## Triggers (pick one)
26
+
27
+ onWebhook({ input: zodSchema, respond: "async" | "sync" }) // POST /hooks/<project>/<id>
28
+ onSchedule({ cron: "0 9 * * *", tz: "America/New_York" })
29
+ onEvent(eventDef) // project-scoped events
30
+ <connector>.triggers.<name>({ ...params, connection: "key"?, every: "5m"? })
31
+ // e.g. github.triggers.issueOpened({ repo: "acme/api" })
32
+ // `connection` names the connections-map entry when ambiguous; `every` overrides
33
+ // poll cadence (clamped to the connector's floor). Payload becomes the run input.
34
+
35
+ ## ctx — the runtime-injected context
36
+
37
+ await ctx.step("name", () => …, { // THE durable checkpoint
38
+ retry: { maxAttempts: 5, backoff: { type: "exponential", base: "1s", max: "1h" } },
39
+ timeout: "30s",
40
+ idempotencyKey: "custom", // default: runId + step + occurrence
41
+ undo: (result) => …, // saga: runs in REVERSE on terminal failure
42
+ });
43
+ // Step results are journaled: must be plain data (string/number/boolean/null/bigint/
44
+ // Date/Map/Set/Uint8Array/arrays/objects). Returning a function/handle throws.
45
+ // The same step name in a loop is fine — occurrences are auto-disambiguated.
46
+ // Completed steps NEVER re-execute across retries/crashes/resumes.
47
+
48
+ ctx.connections.<key>.<…>.<action>(input) // pre-authed typed connector calls —
49
+ // ONLY inside a step; broker injects tokens
50
+ ctx.secrets.<key> // string value, masked in logs
51
+ await ctx.sleep("2h") // durable timer, zero idle cost
52
+ await ctx.waitForSignal("approval", { schema, timeout: "2d" }) // null on timeout
53
+ await ctx.emit(eventDef, payload) // broadcast event — call INSIDE a step
54
+ ctx.request // { headers, query, rawBody } (webhook only)
55
+ ctx.logger.info|warn|error(msg, meta?)
56
+ ctx.run // { id, attempt, automationId }
57
+
58
+ ## Events (project-scoped)
59
+
60
+ export const invoicePaid = defineEvent("invoice.paid", z.object({ id: z.string() }));
61
+ // emitter: await ctx.emit(invoicePaid, { id }); (inside a step)
62
+ // listener: trigger: onEvent(invoicePaid) (payload = run input)
63
+
64
+ ## Errors control retries
65
+
66
+ throw new RetryableError("throttled", { retryAfterMs: 30_000 }); // retry (default for throws)
67
+ throw new TerminalError("bad input"); // stop now; undos run
68
+ // Non-retry-safe connector WRITES never auto-retry unless the step sets `retry`.
69
+
70
+ ## Testing (colocate index.test.ts; `tesser test`)
71
+
72
+ import { createTest } from "@devosurf/tesser-testing";
73
+ const t = createTest({ automation });
74
+ const { result, steps, calls, status } = await t.run({
75
+ input: …,
76
+ mocks: { "step-name": (input) => mockedConnectorResult }, // step code still runs
77
+ connections: { slack: { chat: { postMessage: fn } } }, // or mock whole actions
78
+ signals: { approval: { approved: true } },
79
+ journal: [{ name: "step", result: recorded }], // replay: skip execution
80
+ });
81
+ // Unmocked connector calls auto-mock from connector samples / output schemas.
82
+ // Time skips: crons, sleeps, retry backoff resolve instantly.
83
+
84
+ ## Rules that bite
85
+
86
+ - Side effects outside ctx.step throw at run time. Wrap them.
87
+ - Don't catch errors you didn't throw (suspension signals unwind through your code).
88
+ - Step names: stable strings, no "$" prefix; steps never nest.
89
+ - Deploy halts if a declared connection/secret is missing — a human completes a connect
90
+ link; you only poll `tesser connect --status`. You never see credential values.
package/package.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "@devosurf/tesser-sdk",
3
+ "version": "0.1.0-alpha.0",
4
+ "description": "Tesser authoring SDK — define automations as typed TypeScript.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": "./src/index.ts",
9
+ "./connector": "./src/connector/index.ts",
10
+ "./internal": "./src/internal/index.ts"
11
+ },
12
+ "main": "./src/index.ts",
13
+ "types": "./src/index.ts",
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "files": [
18
+ "src",
19
+ "README.md",
20
+ "LICENSE",
21
+ "llms.txt"
22
+ ]
23
+ }
@@ -0,0 +1,258 @@
1
+ // The one authoring primitive (ADR-0001) and the runtime-injected ctx surface.
2
+ // Shape locked by the SDK grill — see docs/SCOPES.md §2 and ADR-0010/0011.
3
+
4
+ import type { EventDefinition } from "./events.js";
5
+ import type { HarnessBudget, HarnessMap, Harnesses } from "./harnesses.js";
6
+ import { isHarnessDef } from "./harnesses.js";
7
+ import type { StandardSchemaV1 } from "./internal/standard-schema.js";
8
+ import type { AutomationBudget, ModelMap, OperatorMap, Operators } from "./operators.js";
9
+ import { isModelDef, isOperatorDef } from "./operators.js";
10
+ import type { Trigger } from "./triggers.js";
11
+
12
+ /** A validation schema (Standard Schema — Zod / Valibot / ArkType). Our own name for the
13
+ * spec interface; no third-party name in the surface (ADR-0004). */
14
+ export type Schema<T> = StandardSchemaV1<unknown, T>;
15
+
16
+ /** Values that can be journaled (persisted between steps). Returning anything else from a
17
+ * step — a function, a stream, a live handle — is a compile (and runtime) error.
18
+ * Date / Map / Set / bigint round-trip via an internal structured codec (ADR-0004). */
19
+ export type Serializable =
20
+ | string
21
+ | number
22
+ | boolean
23
+ | null
24
+ | undefined
25
+ | bigint
26
+ | Date
27
+ | Uint8Array
28
+ | Serializable[]
29
+ | ReadonlyArray<Serializable>
30
+ | Map<Serializable, Serializable>
31
+ | Set<Serializable>
32
+ | { [key: string]: Serializable };
33
+
34
+ // ---- Connectors & secrets: declared on the def, mirrored on ctx (ADR-0004 / 0005 / 0010) ----
35
+
36
+ /** A typed connector, imported from @devosurf/tesser-connectors. Identical on every Instance; holds
37
+ * no credential. `.perUser()` selects per-end-user connection scope (default: workspace,
38
+ * ADR-0005). */
39
+ export interface Connector<TClient> {
40
+ readonly id: string;
41
+ readonly scope: "workspace" | "per_user";
42
+ /** Phantom for inference; never set. */
43
+ readonly _client?: TClient;
44
+ perUser(): Connector<TClient>;
45
+ }
46
+
47
+ export type ClientOf<C> = C extends Connector<infer T> ? T : never;
48
+
49
+ /** A raw, non-connector secret declaration (ADR-0010): an API key, a webhook-signing secret.
50
+ * Referenced by name on ctx.secrets; the value is injected at run time and masked in logs —
51
+ * the author never sees it. The escape hatch for what a Connector can't cover. */
52
+ export interface SecretDef {
53
+ readonly _secret: true;
54
+ readonly describe?: string;
55
+ }
56
+
57
+ export function secret(opts?: { describe?: string }): SecretDef {
58
+ return Object.freeze({
59
+ _secret: true as const,
60
+ ...(opts?.describe !== undefined ? { describe: opts.describe } : {}),
61
+ });
62
+ }
63
+
64
+ export type ConnectionMap = Record<string, Connector<unknown>>;
65
+ export type SecretMap = Record<string, SecretDef>;
66
+
67
+ /** Pre-authenticated typed connector clients; the broker injects the token at call time. */
68
+ export type Connections<C extends ConnectionMap> = {
69
+ readonly [K in keyof C]: ClientOf<C[K]>;
70
+ };
71
+ /** Raw secret values, injected at run time, masked in logs. */
72
+ export type Secrets<S extends SecretMap> = {
73
+ readonly [K in keyof S]: string;
74
+ };
75
+
76
+ // ---- ctx.step config ----
77
+
78
+ export interface RetryPolicy {
79
+ maxAttempts: number;
80
+ backoff?:
81
+ | "exponential"
82
+ | "fixed"
83
+ | { type: "exponential" | "fixed"; base?: string; max?: string; jitter?: boolean };
84
+ }
85
+
86
+ export interface StepOpts<T> {
87
+ retry?: RetryPolicy;
88
+ timeout?: string;
89
+ /** Override the auto-derived (runId + name + occurrence) idempotency key for cross-run dedup. */
90
+ idempotencyKey?: string;
91
+ /** Opt-in saga rollback (ADR-0002): runs in reverse order if a later step fails terminally. */
92
+ undo?: (result: T) => unknown | Promise<unknown>;
93
+ }
94
+
95
+ export interface Logger {
96
+ info(msg: string, meta?: Record<string, unknown>): void;
97
+ warn(msg: string, meta?: Record<string, unknown>): void;
98
+ error(msg: string, meta?: Record<string, unknown>): void;
99
+ }
100
+
101
+ /** Raw inbound request — present only for webhook triggers (raw bytes are needed for HMAC). */
102
+ export interface WebhookRequest {
103
+ readonly headers: Record<string, string>;
104
+ readonly query: Record<string, string>;
105
+ readonly rawBody: Uint8Array;
106
+ }
107
+
108
+ // ---- The runtime-injected context ----
109
+
110
+ export interface Ctx<
111
+ C extends ConnectionMap = ConnectionMap,
112
+ S extends SecretMap = SecretMap,
113
+ O extends OperatorMap = OperatorMap,
114
+ H extends HarnessMap = HarnessMap,
115
+ > {
116
+ /** The durable boundary. Wrap every side effect here; the output must be Serializable. (ADR-0002) */
117
+ step<T extends Serializable>(name: string, fn: () => Promise<T> | T, opts?: StepOpts<T>): Promise<T>;
118
+
119
+ /** Pre-authenticated typed connectors; tokens injected by the broker. (ADR-0004) */
120
+ readonly connections: Connections<C>;
121
+ /** Raw secret values, injected at run time, masked in logs. (ADR-0010) */
122
+ readonly secrets: Secrets<S>;
123
+ /** Automation-scoped Operator calls; each expands into model/tool Steps. */
124
+ readonly operators: Operators<O>;
125
+ /** Sandboxed external Harness runners. Call inside ctx.step. */
126
+ readonly harnesses: Harnesses<H>;
127
+
128
+ /** Durable timer — suspends the run at zero idle cost. Not a side effect → not in a step. */
129
+ sleep(duration: string): Promise<void>;
130
+ /** Durable suspend until an external Signal arrives (HITL, callbacks). Resolves null on timeout. */
131
+ waitForSignal<T>(name: string, opts: { schema: Schema<T>; timeout?: string }): Promise<T | null>;
132
+ /** Emit a Project-scoped Event (broadcast, at-least-once). A side effect → call inside a step. */
133
+ emit<T>(event: EventDefinition<T>, payload: T): Promise<void>;
134
+
135
+ /** Present only for webhook triggers. */
136
+ readonly request?: WebhookRequest;
137
+ readonly logger: Logger;
138
+ readonly run: { readonly id: string; readonly attempt: number; readonly automationId: string };
139
+ }
140
+
141
+ // ---- The one authoring primitive (ADR-0001) ----
142
+
143
+ export interface AutomationDef<
144
+ TInput = unknown,
145
+ TOutput = unknown,
146
+ C extends ConnectionMap = ConnectionMap,
147
+ S extends SecretMap = SecretMap,
148
+ M extends ModelMap = ModelMap,
149
+ O extends OperatorMap = OperatorMap,
150
+ H extends HarnessMap = HarnessMap,
151
+ > {
152
+ id: string;
153
+ trigger: Trigger<TInput>;
154
+ input?: Schema<TInput>;
155
+ output?: Schema<TOutput>;
156
+
157
+ /** Required connections — declared statically so the build extracts them WITHOUT running the
158
+ * handler; mirrored on ctx.connections.<key>. (ADR-0005 / 0010) */
159
+ connections?: C;
160
+ /** Required raw secrets — same static-extraction guarantee; mirrored on ctx.secrets.<key>. */
161
+ secrets?: S;
162
+
163
+ /** Brokered direct LLM choices used by Operators. */
164
+ models?: M;
165
+ /** In-Automation LLM actors. Not deployable primitives. */
166
+ operators?: O;
167
+ /** Sandboxed external runners used only from deterministic Automation code. */
168
+ harnesses?: H;
169
+ /** Run-level operational caps. `budget.models` is mandatory when Operators are present. */
170
+ budget?: AutomationBudget & { harnesses?: HarnessBudget };
171
+
172
+ /** Operational config, co-located — no hidden GUI menus. `retry` is the per-run default; a
173
+ * per-step `StepOpts.retry` overrides. Timeout is per-step only (durable waits make a
174
+ * run-wide deadline meaningless). `onConflict` also covers schedule overlap. */
175
+ retry?: RetryPolicy;
176
+ concurrency?: {
177
+ limit: number;
178
+ key?: (input: TInput) => string;
179
+ onConflict?: "queue" | "drop";
180
+ };
181
+
182
+ run: (input: TInput, ctx: Ctx<C, S, O, H>) => Promise<TOutput>;
183
+ }
184
+
185
+ const AUTOMATION_ID = /^[a-z][a-z0-9-]{0,63}$/;
186
+ const TRIGGER_KINDS = new Set(["webhook", "schedule", "event", "connector"]);
187
+
188
+ /** Define one complete automation. One file = one automation. */
189
+ export function defineAutomation<
190
+ TInput,
191
+ TOutput,
192
+ C extends ConnectionMap = Record<string, never>,
193
+ S extends SecretMap = Record<string, never>,
194
+ M extends ModelMap = Record<string, never>,
195
+ O extends OperatorMap = Record<string, never>,
196
+ H extends HarnessMap = Record<string, never>,
197
+ >(def: AutomationDef<TInput, TOutput, C, S, M, O, H>): AutomationDef<TInput, TOutput, C, S, M, O, H> {
198
+ if (!AUTOMATION_ID.test(def?.id ?? "")) {
199
+ throw new TypeError(
200
+ `defineAutomation: id "${String(def?.id)}" — ids are kebab-case ([a-z0-9-], max 64), e.g. "daily-digest"`,
201
+ );
202
+ }
203
+ if (!def.trigger || !TRIGGER_KINDS.has(def.trigger.kind)) {
204
+ throw new TypeError(
205
+ `defineAutomation(${def.id}): trigger must be onWebhook / onSchedule / onEvent or a connector trigger`,
206
+ );
207
+ }
208
+ if (typeof def.run !== "function") {
209
+ throw new TypeError(`defineAutomation(${def.id}): run must be an async function`);
210
+ }
211
+ for (const [key, conn] of Object.entries(def.connections ?? {})) {
212
+ if (typeof (conn as Connector<unknown>)?.id !== "string") {
213
+ throw new TypeError(
214
+ `defineAutomation(${def.id}): connections.${key} is not a connector — import it from @devosurf/tesser-connectors`,
215
+ );
216
+ }
217
+ }
218
+ for (const [key, sec] of Object.entries(def.secrets ?? {})) {
219
+ if ((sec as SecretDef)?._secret !== true) {
220
+ throw new TypeError(
221
+ `defineAutomation(${def.id}): secrets.${key} must be declared with secret({ describe })`,
222
+ );
223
+ }
224
+ }
225
+ for (const [key, m] of Object.entries(def.models ?? {})) {
226
+ if (!isModelDef(m)) {
227
+ throw new TypeError(`defineAutomation(${def.id}): models.${key} must be declared with model({ connection, alias })`);
228
+ }
229
+ }
230
+ for (const [key, op] of Object.entries(def.operators ?? {})) {
231
+ if (!isOperatorDef(op)) {
232
+ throw new TypeError(`defineAutomation(${def.id}): operators.${key} must be declared with defineOperator(...)`);
233
+ }
234
+ }
235
+ for (const [key, h] of Object.entries(def.harnesses ?? {})) {
236
+ if (!isHarnessDef(h)) {
237
+ throw new TypeError(`defineAutomation(${def.id}): harnesses.${key} must be declared with harness({ connection })`);
238
+ }
239
+ }
240
+ if (Object.keys(def.operators ?? {}).length > 0) {
241
+ const b = def.budget?.models;
242
+ if (
243
+ !b ||
244
+ !Number.isInteger(b.tokens) ||
245
+ b.tokens < 1 ||
246
+ !Number.isInteger(b.outputTokens) ||
247
+ b.outputTokens < 1
248
+ ) {
249
+ throw new TypeError(
250
+ `defineAutomation(${def.id}): budget.models with positive tokens and outputTokens is required when operators are declared`,
251
+ );
252
+ }
253
+ }
254
+ if (def.concurrency && (!Number.isInteger(def.concurrency.limit) || def.concurrency.limit < 1)) {
255
+ throw new TypeError(`defineAutomation(${def.id}): concurrency.limit must be a positive integer`);
256
+ }
257
+ return def;
258
+ }