stageflow 0.31.0 → 0.32.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/dist/agent/piAdapter.js +21 -0
- package/dist/agent/port.d.ts +2 -0
- package/dist/config/loadStage.js +10 -0
- package/dist/config/pipelineStageKeys.js +1 -0
- package/dist/email/accounts.d.ts +109 -0
- package/dist/email/accounts.js +285 -0
- package/dist/email/adapter.d.ts +69 -0
- package/dist/email/adapter.js +720 -0
- package/dist/email/attachments.d.ts +21 -0
- package/dist/email/attachments.js +146 -0
- package/dist/email/events.d.ts +95 -0
- package/dist/email/events.js +292 -0
- package/dist/email/host.d.ts +15 -0
- package/dist/email/host.js +119 -0
- package/dist/email/messages.d.ts +44 -0
- package/dist/email/messages.js +182 -0
- package/dist/email/port.d.ts +161 -0
- package/dist/email/port.js +12 -0
- package/dist/email/replies.d.ts +5 -0
- package/dist/email/replies.js +56 -0
- package/dist/email/submissions.d.ts +31 -0
- package/dist/email/submissions.js +123 -0
- package/dist/email/triggers.d.ts +140 -0
- package/dist/email/triggers.js +563 -0
- package/dist/package-meta.d.ts +1 -1
- package/dist/package-meta.js +1 -1
- package/dist/runstore/port.d.ts +4 -0
- package/dist/runstore/sqlite/SqliteRunStore.d.ts +1 -0
- package/dist/runstore/sqlite/SqliteRunStore.js +24 -5
- package/dist/runstore/sqlite/migrations/011-email-dispatch-key.d.ts +7 -0
- package/dist/runstore/sqlite/migrations/011-email-dispatch-key.js +12 -0
- package/dist/runstore/sqlite/migrations/index.js +2 -0
- package/dist/runtime/pipelineRunner.d.ts +3 -0
- package/dist/runtime/pipelineRunner.js +11 -0
- package/dist/runtime/pipelineScheduler.js +3 -0
- package/dist/runtime/runManager.d.ts +1 -0
- package/dist/runtime/runManager.js +24 -3
- package/dist/runtime/stageAttemptBootstrap.js +14 -0
- package/dist/runtime/stageProcessLauncher.d.ts +4 -0
- package/dist/runtime/stageProcessLauncher.js +45 -1
- package/dist/server/bootstrap.d.ts +7 -0
- package/dist/server/bootstrap.js +17 -0
- package/dist/server/emailRoutes.d.ts +5 -0
- package/dist/server/emailRoutes.js +136 -0
- package/dist/server/http.d.ts +2 -0
- package/dist/server/http.js +16 -0
- package/dist/tools/readEmail.d.ts +77 -0
- package/dist/tools/readEmail.js +31 -0
- package/dist/tools/replyEmail.d.ts +31 -0
- package/dist/tools/replyEmail.js +25 -0
- package/dist/tools/sendEmail.d.ts +43 -0
- package/dist/tools/sendEmail.js +26 -0
- package/dist/types/stage.d.ts +4 -0
- package/dist/ui/assets/index-59cjF0OA.js +133 -0
- package/dist/ui/index.html +1 -1
- package/examples/hello-email/README.md +23 -0
- package/examples/hello-email/hello-email-reply.pipeline.yaml +6 -0
- package/examples/hello-email/hello-email.pipeline.yaml +6 -0
- package/examples/hello-email/hello-email.task.yaml +6 -0
- package/examples/hello-email/reply-hello-email.yaml +63 -0
- package/examples/hello-email/send-hello-email.yaml +37 -0
- package/package.json +6 -2
- package/dist/ui/assets/index-p8Iou3zk.js +0 -133
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { attachmentReferencesSchema } from "./attachments.js";
|
|
6
|
+
import { EmailError } from "./port.js";
|
|
7
|
+
const address = z.object({ address: z.email(), name: z.string().max(200).regex(/^[^\r\n]*$/).optional() }).strict();
|
|
8
|
+
export const messageIdSchema = z.string().max(998).regex(/^[\x21-\x7e]+$/).regex(/^<[^<>\s@]+@[^<>\s@]+>$/);
|
|
9
|
+
const sendSchema = z.object({
|
|
10
|
+
accountId: z.string().min(1), operationKey: z.string().min(1).max(200),
|
|
11
|
+
from: z.email().optional(), to: z.array(address).max(100), cc: z.array(address).max(100).default([]),
|
|
12
|
+
bcc: z.array(address).max(100).default([]), subject: z.string().max(998).regex(/^[^\r\n]*$/),
|
|
13
|
+
text: z.string().max(262144), html: z.string().max(262144).optional(),
|
|
14
|
+
inReplyTo: messageIdSchema.optional(), references: z.array(messageIdSchema).max(100).refine(values => values.join(" ").length <= 8192).optional(),
|
|
15
|
+
attachments: attachmentReferencesSchema.optional(),
|
|
16
|
+
}).strict().refine(input => input.to.length + input.cc.length + input.bcc.length > 0);
|
|
17
|
+
export function validateSend(input, account) {
|
|
18
|
+
const parsed = sendSchema.safeParse(input);
|
|
19
|
+
if (!parsed.success)
|
|
20
|
+
throw new EmailError("EMAIL_INVALID_INPUT");
|
|
21
|
+
const from = parsed.data.from ?? account.address;
|
|
22
|
+
if (![account.address, ...account.senderAliases].some(value => value.toLowerCase() === from.toLowerCase())) {
|
|
23
|
+
throw new EmailError("EMAIL_UNAUTHORIZED");
|
|
24
|
+
}
|
|
25
|
+
return { ...parsed.data, from };
|
|
26
|
+
}
|
|
27
|
+
/** The host is the single writer. Pending records survive crashes as uncertain outcomes. */
|
|
28
|
+
export class EmailSubmissions {
|
|
29
|
+
file;
|
|
30
|
+
records;
|
|
31
|
+
active = new Map();
|
|
32
|
+
accepting = true;
|
|
33
|
+
constructor(scope) {
|
|
34
|
+
this.file = path.join(scope, ".stageflow", "email-submissions.json");
|
|
35
|
+
this.records = existsSync(this.file) ? JSON.parse(readFileSync(this.file, "utf8")) : [];
|
|
36
|
+
for (const record of this.records)
|
|
37
|
+
if (record.state === "pending")
|
|
38
|
+
record.state = "unknown";
|
|
39
|
+
for (const record of this.records)
|
|
40
|
+
if (record.receipt?.sentCopy?.state === "pending") {
|
|
41
|
+
record.receipt.sentCopy = { state: "unknown" };
|
|
42
|
+
record.receipt.warnings = ["EMAIL_SENT_COPY_OUTCOME_UNKNOWN"];
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
list() { return structuredClone(this.records); }
|
|
46
|
+
async drain() { await Promise.allSettled(this.active.values()); }
|
|
47
|
+
setAccepting(accepting) { this.accepting = accepting; }
|
|
48
|
+
async send(input, submit, identity) {
|
|
49
|
+
if (!this.accepting)
|
|
50
|
+
throw new EmailError("EMAIL_CONNECTION_FAILED", true);
|
|
51
|
+
const hash = createHash("sha256").update(JSON.stringify(identity === undefined ? input : { input, identity })).digest("hex");
|
|
52
|
+
const key = `${input.accountId}\0${input.operationKey}`;
|
|
53
|
+
const found = this.records.find(record => record.accountId === input.accountId && record.operationKey === input.operationKey);
|
|
54
|
+
if (found) {
|
|
55
|
+
if (found.hash !== hash)
|
|
56
|
+
throw new EmailError("EMAIL_OPERATION_CONFLICT");
|
|
57
|
+
const active = this.active.get(key);
|
|
58
|
+
if (active)
|
|
59
|
+
return active;
|
|
60
|
+
if (found.receipt)
|
|
61
|
+
return structuredClone(found.receipt);
|
|
62
|
+
if (found.state === "failed" && found.error)
|
|
63
|
+
throw new EmailError(found.error.code, found.error.retryable);
|
|
64
|
+
throw new EmailError("EMAIL_SEND_OUTCOME_UNKNOWN");
|
|
65
|
+
}
|
|
66
|
+
// Completed records expire after 30 days; unresolved records are never evicted.
|
|
67
|
+
const cutoff = Date.now() - 30 * 86400000;
|
|
68
|
+
this.records = this.records.filter(record => !["submitted", "failed"].includes(record.state)
|
|
69
|
+
|| ["pending", "unknown"].includes(record.receipt?.sentCopy?.state ?? "") || Date.parse(record.createdAt) >= cutoff);
|
|
70
|
+
if (this.records.length >= 10000)
|
|
71
|
+
throw new EmailError("EMAIL_RESOURCE_LIMIT");
|
|
72
|
+
const record = { operationId: randomUUID(), accountId: input.accountId,
|
|
73
|
+
operationKey: input.operationKey, hash, state: "pending", createdAt: new Date().toISOString() };
|
|
74
|
+
this.records.push(record);
|
|
75
|
+
this.persist();
|
|
76
|
+
let checkpointed = false;
|
|
77
|
+
const work = Promise.resolve().then(() => submit(record.operationId, receipt => {
|
|
78
|
+
checkpointed = true;
|
|
79
|
+
record.state = "submitted";
|
|
80
|
+
record.receipt = structuredClone(receipt);
|
|
81
|
+
this.persist();
|
|
82
|
+
})).then(receipt => {
|
|
83
|
+
record.state = "submitted";
|
|
84
|
+
record.receipt = receipt;
|
|
85
|
+
this.persist();
|
|
86
|
+
return structuredClone(receipt);
|
|
87
|
+
}).catch(error => {
|
|
88
|
+
if (checkpointed && record.receipt) {
|
|
89
|
+
if (record.receipt.sentCopy?.state === "pending") {
|
|
90
|
+
record.receipt.sentCopy = { state: "unknown", error: "EMAIL_STORAGE_FAILED" };
|
|
91
|
+
record.receipt.warnings = ["EMAIL_SENT_COPY_OUTCOME_UNKNOWN"];
|
|
92
|
+
}
|
|
93
|
+
record.receipt.warnings = [...record.receipt.warnings ?? [], "EMAIL_STORAGE_FAILED"];
|
|
94
|
+
try {
|
|
95
|
+
this.persist();
|
|
96
|
+
}
|
|
97
|
+
catch { /* The durable pending record still forbids resubmission. */ }
|
|
98
|
+
return structuredClone(record.receipt);
|
|
99
|
+
}
|
|
100
|
+
const fault = error instanceof EmailError ? error : new EmailError("EMAIL_SEND_OUTCOME_UNKNOWN");
|
|
101
|
+
record.state = fault.code === "EMAIL_SEND_OUTCOME_UNKNOWN" ? "unknown" : "failed";
|
|
102
|
+
record.error = { code: fault.code, retryable: fault.retryable };
|
|
103
|
+
delete record.receipt;
|
|
104
|
+
try {
|
|
105
|
+
this.persist();
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
// The previously durable pending record is sufficient to forbid resubmission.
|
|
109
|
+
record.state = "unknown";
|
|
110
|
+
throw new EmailError("EMAIL_SEND_OUTCOME_UNKNOWN");
|
|
111
|
+
}
|
|
112
|
+
throw fault;
|
|
113
|
+
}).finally(() => { this.active.delete(key); });
|
|
114
|
+
this.active.set(key, work);
|
|
115
|
+
return work;
|
|
116
|
+
}
|
|
117
|
+
persist() {
|
|
118
|
+
mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 });
|
|
119
|
+
const temporary = `${this.file}.${randomUUID()}.tmp`;
|
|
120
|
+
writeFileSync(temporary, JSON.stringify(this.records), { mode: 0o600 });
|
|
121
|
+
renameSync(temporary, this.file);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import type { RunStore } from "../runstore/port.js";
|
|
3
|
+
import type { RunManager } from "../runtime/runManager.js";
|
|
4
|
+
import type { EmailAccounts } from "./accounts.js";
|
|
5
|
+
import { type EmailMailbox, type EmailReceivedEvent, type EmailMessageRef } from "./port.js";
|
|
6
|
+
export type EmailReplayOutcome = {
|
|
7
|
+
ref: EmailMessageRef;
|
|
8
|
+
status: "matched" | "skipped" | "alreadyHandled" | "pending" | "started" | "failed";
|
|
9
|
+
code?: string;
|
|
10
|
+
dispatchKey?: string;
|
|
11
|
+
runId?: string;
|
|
12
|
+
};
|
|
13
|
+
export type EmailReplayResult = {
|
|
14
|
+
selected: number;
|
|
15
|
+
matched: number;
|
|
16
|
+
skipped: number;
|
|
17
|
+
alreadyHandled: number;
|
|
18
|
+
pending: number;
|
|
19
|
+
failed: number;
|
|
20
|
+
started: number;
|
|
21
|
+
outcomes: EmailReplayOutcome[];
|
|
22
|
+
refs: EmailMessageRef[];
|
|
23
|
+
ruleVersion: number;
|
|
24
|
+
nextCursor?: string;
|
|
25
|
+
};
|
|
26
|
+
declare const ruleInput: z.ZodObject<{
|
|
27
|
+
enabled: z.ZodDefault<z.ZodBoolean>;
|
|
28
|
+
accountId: z.ZodString;
|
|
29
|
+
folder: z.ZodDefault<z.ZodString>;
|
|
30
|
+
from: z.ZodOptional<z.ZodEmail>;
|
|
31
|
+
subjectContains: z.ZodOptional<z.ZodString>;
|
|
32
|
+
pipeline: z.ZodString;
|
|
33
|
+
task: z.ZodObject<{
|
|
34
|
+
id: z.ZodString;
|
|
35
|
+
goal: z.ZodString;
|
|
36
|
+
context: z.ZodOptional<z.ZodString>;
|
|
37
|
+
constraints: z.ZodOptional<z.ZodString>;
|
|
38
|
+
checkout: z.ZodOptional<z.ZodString>;
|
|
39
|
+
}, z.core.$strict>;
|
|
40
|
+
includeBody: z.ZodDefault<z.ZodBoolean>;
|
|
41
|
+
bodyLimit: z.ZodDefault<z.ZodNumber>;
|
|
42
|
+
}, z.core.$strict>;
|
|
43
|
+
export type EmailTriggerRule = z.output<typeof ruleInput> & {
|
|
44
|
+
triggerId: string;
|
|
45
|
+
version: number;
|
|
46
|
+
activeAfter: string;
|
|
47
|
+
};
|
|
48
|
+
export type EmailDispatch = {
|
|
49
|
+
dispatchKey: string;
|
|
50
|
+
eventId: string;
|
|
51
|
+
triggerId: string;
|
|
52
|
+
ruleVersion: number;
|
|
53
|
+
accountId: string;
|
|
54
|
+
status: "pending" | "started" | "failed" | "suspended";
|
|
55
|
+
runId?: string;
|
|
56
|
+
code?: string;
|
|
57
|
+
attempts?: number;
|
|
58
|
+
retryAt?: string;
|
|
59
|
+
completedAt?: string;
|
|
60
|
+
};
|
|
61
|
+
declare const queueInput: z.ZodObject<{
|
|
62
|
+
maxPending: z.ZodDefault<z.ZodNumber>;
|
|
63
|
+
workers: z.ZodDefault<z.ZodNumber>;
|
|
64
|
+
batchSize: z.ZodDefault<z.ZodNumber>;
|
|
65
|
+
intervalMs: z.ZodDefault<z.ZodNumber>;
|
|
66
|
+
retryMaxMs: z.ZodDefault<z.ZodNumber>;
|
|
67
|
+
retentionMs: z.ZodDefault<z.ZodNumber>;
|
|
68
|
+
maxCompleted: z.ZodDefault<z.ZodNumber>;
|
|
69
|
+
}, z.core.$strict>;
|
|
70
|
+
type Options = {
|
|
71
|
+
cwd: string;
|
|
72
|
+
accounts: EmailAccounts;
|
|
73
|
+
mailbox: EmailMailbox;
|
|
74
|
+
manager: RunManager;
|
|
75
|
+
store: RunStore;
|
|
76
|
+
now?: () => Date;
|
|
77
|
+
queue?: z.input<typeof queueInput>;
|
|
78
|
+
/** Fault injection at the durable dispatch seam. */
|
|
79
|
+
checkpoint?: (point: "beforeRun" | "afterRun", dispatch: EmailDispatch) => Promise<void>;
|
|
80
|
+
};
|
|
81
|
+
/** Durable rule evaluation and dispatch above the normal run execution path. */
|
|
82
|
+
export declare class EmailTriggers {
|
|
83
|
+
private readonly options;
|
|
84
|
+
private readonly db;
|
|
85
|
+
private readonly now;
|
|
86
|
+
private readonly queue;
|
|
87
|
+
private readonly active;
|
|
88
|
+
private readonly activeFolders;
|
|
89
|
+
private timer?;
|
|
90
|
+
private nextBatchAt;
|
|
91
|
+
private lastFolder?;
|
|
92
|
+
private stopPromise?;
|
|
93
|
+
private faultCode?;
|
|
94
|
+
private readonly suspensions;
|
|
95
|
+
private stopped;
|
|
96
|
+
private closed;
|
|
97
|
+
private readonly unsubscribe;
|
|
98
|
+
constructor(options: Options);
|
|
99
|
+
list(): EmailTriggerRule[];
|
|
100
|
+
get(triggerId: string): EmailTriggerRule;
|
|
101
|
+
create(input: unknown): Promise<EmailTriggerRule>;
|
|
102
|
+
update(triggerId: string, patch: unknown): Promise<EmailTriggerRule>;
|
|
103
|
+
remove(triggerId: string): void;
|
|
104
|
+
history(): EmailDispatch[];
|
|
105
|
+
health(): {
|
|
106
|
+
pending?: number;
|
|
107
|
+
suspended?: number;
|
|
108
|
+
active: number;
|
|
109
|
+
saturated?: boolean;
|
|
110
|
+
code?: string;
|
|
111
|
+
};
|
|
112
|
+
accept(event: EmailReceivedEvent): Promise<void>;
|
|
113
|
+
/** Preview one search page, or admit an exact selection through the normal queue. */
|
|
114
|
+
replay(input: unknown, execute?: boolean): Promise<EmailReplayResult>;
|
|
115
|
+
private dispatchKey;
|
|
116
|
+
private hasDispatch;
|
|
117
|
+
/** Run one due batch. The timer continues recovery without waiting for runs to finish. */
|
|
118
|
+
recover(): Promise<void>;
|
|
119
|
+
stop(): Promise<void>;
|
|
120
|
+
resume(dispatchKey: string): EmailDispatch;
|
|
121
|
+
cancel(dispatchKey: string): void;
|
|
122
|
+
cleanup(): void;
|
|
123
|
+
private schedule;
|
|
124
|
+
private pump;
|
|
125
|
+
private attempt;
|
|
126
|
+
private isPending;
|
|
127
|
+
private accountRevision;
|
|
128
|
+
private saveOutcome;
|
|
129
|
+
private saveStarted;
|
|
130
|
+
private assertOpen;
|
|
131
|
+
private assertAccepting;
|
|
132
|
+
private validate;
|
|
133
|
+
private saveRule;
|
|
134
|
+
private save;
|
|
135
|
+
private records;
|
|
136
|
+
private suspendObsolete;
|
|
137
|
+
private suspendAccount;
|
|
138
|
+
private dispatch;
|
|
139
|
+
}
|
|
140
|
+
export {};
|