@uru-intelligence/app 2.2.1 → 2.2.4

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.
@@ -0,0 +1,162 @@
1
+ const REQUEST_TIMEOUT_MS = 25_000;
2
+ export const approvedExternalWriteRequest = (intent) => ({
3
+ capabilityName: "send_approved_update",
4
+ idempotencyKey: `external-write:${intent.approvalId}`,
5
+ input: {
6
+ approvalId: intent.approvalId,
7
+ approvedByActorId: intent.approvedByActorId,
8
+ targetId: intent.targetId,
9
+ payload: intent.payload,
10
+ },
11
+ deadlineAt: intent.deadlineAt,
12
+ timeoutMs: REQUEST_TIMEOUT_MS,
13
+ });
14
+ /** Start once, after approval. Uru still checks the bound tool and its policy. */
15
+ export const startApprovedExternalWrite = (coordinator, approvalId, loadApprovedIntent, options) => loadApprovedIntent(approvalId, options?.signal).then((intent) => {
16
+ options?.signal?.throwIfAborted();
17
+ if (intent === null || intent.approvalId !== approvalId) {
18
+ throw new Error("This external write has no matching approved intent.");
19
+ }
20
+ return coordinator.start(approvedExternalWriteRequest(intent), options);
21
+ });
22
+ /** Recover the same request. Never mint a new key after an uncertain result. */
23
+ export const resumeApprovedExternalWrite = (coordinator, approvalId, options) => coordinator.resume(`external-write:${approvalId}`, options);
24
+ export const observeApprovedExternalWrite = (coordinator, approvalId, options) => coordinator.observe(`external-write:${approvalId}`, options);
25
+ export const waitApprovedExternalWrite = (coordinator, approvalId, options) => coordinator.wait(`external-write:${approvalId}`, options);
26
+ export const cancelApprovedExternalWrite = (coordinator, approvalId, options) => coordinator.cancel(`external-write:${approvalId}`, options);
27
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
28
+ const sameJson = (left, right) => {
29
+ if (left === right)
30
+ return true;
31
+ if (Array.isArray(left) && Array.isArray(right)) {
32
+ return (left.length === right.length &&
33
+ left.every((value, index) => sameJson(value, right[index])));
34
+ }
35
+ if (isRecord(left) && isRecord(right)) {
36
+ const leftKeys = Object.keys(left);
37
+ const rightKeys = Object.keys(right);
38
+ return (leftKeys.length === rightKeys.length &&
39
+ leftKeys.every((key) => Object.hasOwn(right, key) && sameJson(left[key], right[key])));
40
+ }
41
+ return false;
42
+ };
43
+ export const approvedExternalIntentMatchesInput = (intent, input) => intent.approvalId === input.approvalId &&
44
+ intent.approvedByActorId === input.approvedByActorId &&
45
+ intent.targetId === input.targetId &&
46
+ sameJson(intent.payload, input.payload);
47
+ const errorCodes = (error) => {
48
+ if (!isRecord(error))
49
+ return [];
50
+ const codes = [];
51
+ const code = error["code"];
52
+ if (typeof code === "string")
53
+ codes.push(code);
54
+ const body = error["body"];
55
+ if (!isRecord(body))
56
+ return codes;
57
+ const diagnostics = body["diagnostics"];
58
+ if (!isRecord(diagnostics))
59
+ return codes;
60
+ const platformCode = diagnostics["platformCode"];
61
+ if (typeof platformCode === "string")
62
+ codes.push(platformCode);
63
+ return codes;
64
+ };
65
+ export const isProviderOutcomeUnknown = (error) => errorCodes(error).some((code) => code === "artifact_tool_provider_outcome_unknown" ||
66
+ code === "execution_outcome_unknown");
67
+ const inputIsValid = (input) => input.approvalId.trim() !== "" &&
68
+ input.approvedByActorId.trim() !== "" &&
69
+ input.targetId.trim() !== "" &&
70
+ isRecord(input.payload);
71
+ /** Run the approved provider action from a durable program job. */
72
+ export const runApprovedExternalWrite = async (context, input, checkpoint, signal, loadApprovedIntent) => {
73
+ if (!inputIsValid(input)) {
74
+ throw new Error("The approved external write input is invalid.");
75
+ }
76
+ const savedKind = checkpoint?.["kind"];
77
+ if (checkpoint?.["approvalId"] === input.approvalId &&
78
+ checkpoint["approvedByActorId"] === input.approvedByActorId &&
79
+ checkpoint["targetId"] === input.targetId &&
80
+ (savedKind === "complete" ||
81
+ savedKind === "unknown" ||
82
+ savedKind === "canceled")) {
83
+ if (savedKind === "complete") {
84
+ return {
85
+ kind: "complete",
86
+ approvalId: input.approvalId,
87
+ targetId: input.targetId,
88
+ };
89
+ }
90
+ if (savedKind === "unknown") {
91
+ return {
92
+ kind: "unknown",
93
+ approvalId: input.approvalId,
94
+ targetId: input.targetId,
95
+ reason: "provider_outcome_unknown",
96
+ };
97
+ }
98
+ return { kind: "canceled" };
99
+ }
100
+ const result = await context.jobs.step("send approved update", async (step) => {
101
+ if (signal.aborted)
102
+ return { kind: "canceled" };
103
+ const approvedIntent = await loadApprovedIntent(input.approvalId, signal);
104
+ if (signal.aborted)
105
+ return { kind: "canceled" };
106
+ if (approvedIntent === null ||
107
+ !approvedExternalIntentMatchesInput(approvedIntent, input)) {
108
+ throw new Error("The approved external intent changed or is no longer approved.");
109
+ }
110
+ let actionInvocationStarted = false;
111
+ try {
112
+ await context.actions.run("send_approved_update", {
113
+ approvalId: approvedIntent.approvalId,
114
+ targetId: approvedIntent.targetId,
115
+ payload: approvedIntent.payload,
116
+ }, {
117
+ idempotencyKey: step.idempotencyKey,
118
+ signal,
119
+ onStatus: (event) => {
120
+ if (event.type === "started")
121
+ actionInvocationStarted = true;
122
+ },
123
+ });
124
+ return {
125
+ kind: "complete",
126
+ approvalId: input.approvalId,
127
+ targetId: input.targetId,
128
+ };
129
+ }
130
+ catch (error) {
131
+ if (signal.aborted &&
132
+ !actionInvocationStarted &&
133
+ !isProviderOutcomeUnknown(error)) {
134
+ return { kind: "canceled" };
135
+ }
136
+ // A stopped wait can follow a provider dispatch. Keep the result open.
137
+ if (signal.aborted || isProviderOutcomeUnknown(error)) {
138
+ return {
139
+ kind: "unknown",
140
+ approvalId: input.approvalId,
141
+ targetId: input.targetId,
142
+ reason: "provider_outcome_unknown",
143
+ };
144
+ }
145
+ throw error;
146
+ }
147
+ });
148
+ if (result.kind !== "canceled") {
149
+ await context.jobs.checkpoint({
150
+ approvalId: input.approvalId,
151
+ approvedByActorId: input.approvedByActorId,
152
+ targetId: input.targetId,
153
+ kind: result.kind,
154
+ });
155
+ }
156
+ return result;
157
+ };
158
+ /** Build a published handler with its trusted server approval lookup. */
159
+ export const createSendApprovedUpdateHandler = (createContext, createLoadApprovedIntent) => async (env, input, checkpoint, signal) => {
160
+ const context = createContext(env);
161
+ return await runApprovedExternalWrite(context, input, checkpoint, signal, createLoadApprovedIntent(env));
162
+ };
@@ -0,0 +1,46 @@
1
+ import type { UruBackgroundJobCallOptions, UruBackgroundJobRequest, UruFileContent, UruFileOutput, UruJobCheckpoint, UruServerContext } from "@uru-intelligence/app";
2
+ import type { JobCoordinator } from "./job-coordinator.js";
3
+ export interface FileProcessorStart {
4
+ fileId: string;
5
+ processorVersion: string;
6
+ deadlineAt: number;
7
+ }
8
+ export type FileProcessorInput = Pick<FileProcessorStart, "fileId" | "processorVersion">;
9
+ export interface FileProcessorResult {
10
+ kind: "complete";
11
+ outputId: string;
12
+ }
13
+ type FileProcessorContext = {
14
+ files: {
15
+ read(fileId: string, options?: {
16
+ signal?: AbortSignal;
17
+ }): Promise<UruFileContent>;
18
+ createOutput(input: {
19
+ name: string;
20
+ contentType: string;
21
+ content: Uint8Array;
22
+ idempotencyKey: string;
23
+ signal?: AbortSignal;
24
+ }): Promise<Pick<UruFileOutput, "outputId">>;
25
+ };
26
+ jobs: Pick<UruServerContext["jobs"], "checkpoint" | "progress" | "step">;
27
+ };
28
+ export type TransformFile = (file: UruFileContent, signal: AbortSignal) => Promise<{
29
+ content: Uint8Array;
30
+ name: string;
31
+ contentType: string;
32
+ }>;
33
+ export declare const fileProcessorRequest: (input: FileProcessorStart) => UruBackgroundJobRequest;
34
+ export declare const startFileProcessor: (coordinator: JobCoordinator, input: FileProcessorStart, options?: UruBackgroundJobCallOptions) => Promise<{
35
+ record: import("@uru-intelligence/app").UruBackgroundJobRecord;
36
+ response: import("@uru-intelligence/app").UruAppRuntimeInvocationResponse;
37
+ }>;
38
+ export declare const resumeFileProcessor: (coordinator: JobCoordinator, input: Pick<FileProcessorStart, "fileId" | "processorVersion">, options?: UruBackgroundJobCallOptions) => Promise<import("@uru-intelligence/app").UruBackgroundJobResumeResult>;
39
+ export declare const observeFileProcessor: (coordinator: JobCoordinator, input: Pick<FileProcessorStart, "fileId" | "processorVersion">, options?: UruBackgroundJobCallOptions) => Promise<import("@uru-intelligence/app").UruBackgroundJobObservation>;
40
+ export declare const waitFileProcessor: (coordinator: JobCoordinator, input: Pick<FileProcessorStart, "fileId" | "processorVersion">, options?: UruBackgroundJobCallOptions) => Promise<import("@uru-intelligence/app").UruBackgroundJobWaitResult>;
41
+ export declare const cancelFileProcessor: (coordinator: JobCoordinator, input: Pick<FileProcessorStart, "fileId" | "processorVersion">, options?: UruBackgroundJobCallOptions) => Promise<import("@uru-intelligence/app").UruBackgroundJobResumeResult>;
42
+ /** Read through Uru, then save a result with a replay-safe output key. */
43
+ export declare const processVerifiedFile: (context: FileProcessorContext, input: FileProcessorInput, checkpoint: UruJobCheckpoint | null, signal: AbortSignal, transform: TransformFile) => Promise<FileProcessorResult | {
44
+ kind: "canceled";
45
+ }>;
46
+ export {};
@@ -0,0 +1,53 @@
1
+ const REQUEST_TIMEOUT_MS = 25_000;
2
+ export const fileProcessorRequest = (input) => ({
3
+ capabilityName: "process_file",
4
+ idempotencyKey: `file:${input.fileId}:processor:${input.processorVersion}`,
5
+ input: { fileId: input.fileId, processorVersion: input.processorVersion },
6
+ deadlineAt: input.deadlineAt,
7
+ timeoutMs: REQUEST_TIMEOUT_MS,
8
+ });
9
+ export const startFileProcessor = (coordinator, input, options) => coordinator.start(fileProcessorRequest(input), options);
10
+ export const resumeFileProcessor = (coordinator, input, options) => coordinator.resume(fileProcessorKey(input), options);
11
+ export const observeFileProcessor = (coordinator, input, options) => coordinator.observe(fileProcessorKey(input), options);
12
+ export const waitFileProcessor = (coordinator, input, options) => coordinator.wait(fileProcessorKey(input), options);
13
+ export const cancelFileProcessor = (coordinator, input, options) => coordinator.cancel(fileProcessorKey(input), options);
14
+ const fileProcessorKey = (input) => `file:${input.fileId}:processor:${input.processorVersion}`;
15
+ /** Read through Uru, then save a result with a replay-safe output key. */
16
+ export const processVerifiedFile = async (context, input, checkpoint, signal, transform) => {
17
+ if (checkpoint?.["fileId"] === input.fileId &&
18
+ checkpoint["processorVersion"] === input.processorVersion &&
19
+ checkpoint["phase"] === "complete" &&
20
+ typeof checkpoint["outputId"] === "string") {
21
+ return { kind: "complete", outputId: checkpoint["outputId"] };
22
+ }
23
+ if (signal.aborted)
24
+ return { kind: "canceled" };
25
+ const file = await context.files.read(input.fileId, { signal });
26
+ if (signal.aborted)
27
+ return { kind: "canceled" };
28
+ const transformed = await transform(file, signal);
29
+ if (signal.aborted)
30
+ return { kind: "canceled" };
31
+ const result = await context.jobs.step("write processed file", async (step) => {
32
+ if (signal.aborted)
33
+ return { kind: "canceled" };
34
+ const output = await context.files.createOutput({
35
+ name: transformed.name,
36
+ contentType: transformed.contentType,
37
+ content: transformed.content,
38
+ idempotencyKey: step.idempotencyKey,
39
+ signal,
40
+ });
41
+ await context.jobs.progress({ completed: 1, message: "File ready" });
42
+ return { kind: "complete", outputId: output.outputId };
43
+ });
44
+ if (result.kind === "canceled")
45
+ return result;
46
+ await context.jobs.checkpoint({
47
+ fileId: input.fileId,
48
+ processorVersion: input.processorVersion,
49
+ phase: "complete",
50
+ outputId: result.outputId,
51
+ });
52
+ return result;
53
+ };
@@ -0,0 +1,5 @@
1
+ import type { UruBackgroundJobCallOptions, UruBackgroundJobCoordinator } from "@uru-intelligence/app";
2
+ /** The complete public coordinator surface used by these examples. */
3
+ export type JobCoordinator = UruBackgroundJobCoordinator;
4
+ /** Per-call cancellation and lifecycle callbacks. */
5
+ export type JobCallOptions = UruBackgroundJobCallOptions;
@@ -0,0 +1,38 @@
1
+ import type { UruBackgroundJobCallOptions, UruBackgroundJobRequest, UruJobCheckpoint, UruServerContext, UruFileOutput } from "@uru-intelligence/app";
2
+ import type { JobCoordinator } from "./job-coordinator.js";
3
+ export interface ReviewDraftStart {
4
+ draftId: string;
5
+ markdown: string;
6
+ deadlineAt: number;
7
+ }
8
+ export interface ReviewDraftResult {
9
+ kind: "review_required";
10
+ outputId: string;
11
+ }
12
+ type ReviewOutputInput = {
13
+ name: string;
14
+ contentType: string;
15
+ content: Uint8Array;
16
+ idempotencyKey: string;
17
+ signal?: AbortSignal;
18
+ };
19
+ type ReviewDraftContext = {
20
+ files: {
21
+ createOutput(input: ReviewOutputInput): Promise<Pick<UruFileOutput, "outputId">>;
22
+ };
23
+ jobs: Pick<UruServerContext["jobs"], "checkpoint" | "progress" | "step">;
24
+ };
25
+ export declare const reviewDraftRequest: (input: ReviewDraftStart) => UruBackgroundJobRequest;
26
+ export declare const startReviewDraft: (coordinator: JobCoordinator, input: ReviewDraftStart, options?: UruBackgroundJobCallOptions) => Promise<{
27
+ record: import("@uru-intelligence/app").UruBackgroundJobRecord;
28
+ response: import("@uru-intelligence/app").UruAppRuntimeInvocationResponse;
29
+ }>;
30
+ export declare const resumeReviewDraft: (coordinator: JobCoordinator, draftId: string, options?: UruBackgroundJobCallOptions) => Promise<import("@uru-intelligence/app").UruBackgroundJobResumeResult>;
31
+ export declare const observeReviewDraft: (coordinator: JobCoordinator, draftId: string, options?: UruBackgroundJobCallOptions) => Promise<import("@uru-intelligence/app").UruBackgroundJobObservation>;
32
+ export declare const waitReviewDraft: (coordinator: JobCoordinator, draftId: string, options?: UruBackgroundJobCallOptions) => Promise<import("@uru-intelligence/app").UruBackgroundJobWaitResult>;
33
+ export declare const cancelReviewDraft: (coordinator: JobCoordinator, draftId: string, options?: UruBackgroundJobCallOptions) => Promise<import("@uru-intelligence/app").UruBackgroundJobResumeResult>;
34
+ /** Save a draft for a person to inspect. This function does not send it. */
35
+ export declare const saveReviewDraft: (context: ReviewDraftContext, input: Pick<ReviewDraftStart, "draftId" | "markdown">, checkpoint: UruJobCheckpoint | null, signal: AbortSignal) => Promise<ReviewDraftResult | {
36
+ kind: "canceled";
37
+ }>;
38
+ export {};
@@ -0,0 +1,48 @@
1
+ const REQUEST_TIMEOUT_MS = 25_000;
2
+ export const reviewDraftRequest = (input) => ({
3
+ capabilityName: "save_review_draft",
4
+ idempotencyKey: `review-draft:${input.draftId}`,
5
+ input: { draftId: input.draftId, markdown: input.markdown },
6
+ deadlineAt: input.deadlineAt,
7
+ timeoutMs: REQUEST_TIMEOUT_MS,
8
+ });
9
+ export const startReviewDraft = (coordinator, input, options) => coordinator.start(reviewDraftRequest(input), options);
10
+ export const resumeReviewDraft = (coordinator, draftId, options) => coordinator.resume(reviewDraftKey(draftId), options);
11
+ export const observeReviewDraft = (coordinator, draftId, options) => coordinator.observe(reviewDraftKey(draftId), options);
12
+ export const waitReviewDraft = (coordinator, draftId, options) => coordinator.wait(reviewDraftKey(draftId), options);
13
+ export const cancelReviewDraft = (coordinator, draftId, options) => coordinator.cancel(reviewDraftKey(draftId), options);
14
+ const reviewDraftKey = (draftId) => `review-draft:${draftId}`;
15
+ /** Save a draft for a person to inspect. This function does not send it. */
16
+ export const saveReviewDraft = async (context, input, checkpoint, signal) => {
17
+ if (checkpoint?.["draftId"] === input.draftId &&
18
+ checkpoint["phase"] === "review_required" &&
19
+ typeof checkpoint["outputId"] === "string") {
20
+ return { kind: "review_required", outputId: checkpoint["outputId"] };
21
+ }
22
+ if (signal.aborted)
23
+ return { kind: "canceled" };
24
+ const result = await context.jobs.step("save review draft", async (step) => {
25
+ if (signal.aborted)
26
+ return { kind: "canceled" };
27
+ const output = await context.files.createOutput({
28
+ name: `${input.draftId}.md`,
29
+ contentType: "text/markdown",
30
+ content: new TextEncoder().encode(input.markdown),
31
+ idempotencyKey: step.idempotencyKey,
32
+ signal,
33
+ });
34
+ await context.jobs.progress({
35
+ completed: 1,
36
+ message: "Draft ready for review",
37
+ });
38
+ return { kind: "review_required", outputId: output.outputId };
39
+ });
40
+ if (result.kind === "canceled")
41
+ return result;
42
+ await context.jobs.checkpoint({
43
+ draftId: input.draftId,
44
+ phase: "review_required",
45
+ outputId: result.outputId,
46
+ });
47
+ return result;
48
+ };
@@ -0,0 +1,46 @@
1
+ import type { UruBackgroundJobCallOptions, UruBackgroundJobRequest, UruDatasetRowMutationInput, UruJobCheckpoint, UruServerContext } from "@uru-intelligence/app";
2
+ import type { JobCoordinator } from "./job-coordinator.js";
3
+ export interface ScheduledCollectorStart {
4
+ sourceId: string;
5
+ requestId: string;
6
+ deadlineAt: number;
7
+ }
8
+ export interface ScheduledCollectorInput {
9
+ sourceId: string;
10
+ }
11
+ /** One source order. Its source id is customer data, not a Uru row id. */
12
+ export interface CollectorOrderRow {
13
+ sourceRowId: string;
14
+ fields: UruDatasetRowMutationInput["fields"];
15
+ }
16
+ export interface CollectorPage {
17
+ rows: readonly CollectorOrderRow[];
18
+ nextCursor: string | null;
19
+ hasMore: boolean;
20
+ }
21
+ export interface CollectorResult {
22
+ pagesWritten: number;
23
+ nextCursor: string | null;
24
+ }
25
+ type CollectorDatasetContext = {
26
+ queryRows: UruServerContext["datasets"]["queryRows"];
27
+ upsertRows: UruServerContext["datasets"]["upsertRows"];
28
+ upsertRowViews: UruServerContext["datasets"]["upsertRowViews"];
29
+ };
30
+ type CollectorContext = {
31
+ datasets: CollectorDatasetContext;
32
+ jobs: Pick<UruServerContext["jobs"], "checkpoint" | "progress" | "step">;
33
+ };
34
+ export type ReadCollectorPage = (sourceId: string, cursor: string | null, signal: AbortSignal) => Promise<CollectorPage>;
35
+ export declare const scheduledCollectorRequest: (input: ScheduledCollectorStart) => UruBackgroundJobRequest;
36
+ export declare const startScheduledCollector: (coordinator: JobCoordinator, input: ScheduledCollectorStart, options?: UruBackgroundJobCallOptions) => Promise<{
37
+ record: import("@uru-intelligence/app").UruBackgroundJobRecord;
38
+ response: import("@uru-intelligence/app").UruAppRuntimeInvocationResponse;
39
+ }>;
40
+ export declare const resumeScheduledCollector: (coordinator: JobCoordinator, input: Pick<ScheduledCollectorStart, "sourceId" | "requestId">, options?: UruBackgroundJobCallOptions) => Promise<import("@uru-intelligence/app").UruBackgroundJobResumeResult>;
41
+ export declare const observeScheduledCollector: (coordinator: JobCoordinator, input: Pick<ScheduledCollectorStart, "sourceId" | "requestId">, options?: UruBackgroundJobCallOptions) => Promise<import("@uru-intelligence/app").UruBackgroundJobObservation>;
42
+ export declare const waitScheduledCollector: (coordinator: JobCoordinator, input: Pick<ScheduledCollectorStart, "sourceId" | "requestId">, options?: UruBackgroundJobCallOptions) => Promise<import("@uru-intelligence/app").UruBackgroundJobWaitResult>;
43
+ export declare const cancelScheduledCollector: (coordinator: JobCoordinator, input: Pick<ScheduledCollectorStart, "sourceId" | "requestId">, options?: UruBackgroundJobCallOptions) => Promise<import("@uru-intelligence/app").UruBackgroundJobResumeResult>;
44
+ /** Run one scheduled collection. Every page write belongs to one named step. */
45
+ export declare const collectScheduledOrders: (context: CollectorContext, input: ScheduledCollectorInput, checkpoint: UruJobCheckpoint | null, signal: AbortSignal, readPage: ReadCollectorPage) => Promise<CollectorResult>;
46
+ export {};