@uru-intelligence/app 2.1.6 → 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.
- package/README.md +463 -14
- package/dist/background-jobs.d.ts +11 -0
- package/dist/background-jobs.js +571 -0
- package/dist/dampers.d.ts +24 -1
- package/dist/dampers.js +3 -0
- package/dist/dataset-boundary.js +38 -1
- package/dist/dataset-row.d.ts +9 -0
- package/dist/dataset-row.js +11 -0
- package/dist/datasets.d.ts +2 -1
- package/dist/datasets.js +82 -28
- package/dist/errors.js +5 -4
- package/dist/examples/customer-workflows/approved-external-write.d.ts +50 -0
- package/dist/examples/customer-workflows/approved-external-write.js +162 -0
- package/dist/examples/customer-workflows/file-processor.d.ts +46 -0
- package/dist/examples/customer-workflows/file-processor.js +53 -0
- package/dist/examples/customer-workflows/job-coordinator.d.ts +5 -0
- package/dist/examples/customer-workflows/job-coordinator.js +1 -0
- package/dist/examples/customer-workflows/review-only-draft.d.ts +38 -0
- package/dist/examples/customer-workflows/review-only-draft.js +48 -0
- package/dist/examples/customer-workflows/scheduled-collector.d.ts +46 -0
- package/dist/examples/customer-workflows/scheduled-collector.js +343 -0
- package/dist/files.js +4 -1
- package/dist/index.d.ts +6 -3
- package/dist/index.js +20 -7
- package/dist/invocations.d.ts +11 -1
- package/dist/invocations.js +72 -4
- package/dist/job-run.d.ts +90 -0
- package/dist/job-run.js +229 -0
- package/dist/jobs.d.ts +3 -3
- package/dist/jobs.js +39 -11
- package/dist/runtime.d.ts +8 -4
- package/dist/runtime.js +27 -7
- package/dist/transport-deadline.d.ts +0 -1
- package/dist/transport-deadline.js +0 -27
- package/dist/transport-invocation.d.ts +23 -4
- package/dist/transport-invocation.js +114 -29
- package/dist/transport-retry.d.ts +68 -0
- package/dist/transport-retry.js +245 -0
- package/dist/transport.d.ts +5 -20
- package/dist/transport.js +54 -33
- package/dist/types.d.ts +203 -4
- package/dist/uploads.js +158 -19
- package/package.json +34 -9
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Convert a native Dataset row view into a lossless row update.
|
|
3
|
+
*
|
|
4
|
+
* Keep row identity separate from customer fields. A flat row cannot represent
|
|
5
|
+
* a customer field named `id` because that key names the row in an upsert.
|
|
6
|
+
*/
|
|
7
|
+
export const datasetRowForMutation = (row) => ({
|
|
8
|
+
expectedRowVersion: row.rowVersion ?? null,
|
|
9
|
+
fields: { ...row.fields },
|
|
10
|
+
rowId: row.id,
|
|
11
|
+
});
|
package/dist/datasets.d.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* The HTTP boundary lives in `dataset-boundary.ts` so this module only assembles
|
|
7
7
|
* the current Dataset request paths and overloads.
|
|
8
8
|
*/
|
|
9
|
+
import type { CallKeys } from "./job-run.js";
|
|
9
10
|
import type { CreateUruAppRuntimeClientOptions, UruAppRuntimeClient, UruDatasetsContext } from "./types.js";
|
|
10
11
|
/** Build the Dataset surface hung off a server context. */
|
|
11
|
-
export declare const createDatasetsContext: (app: UruAppRuntimeClient, clientOptions: CreateUruAppRuntimeClientOptions) => UruDatasetsContext;
|
|
12
|
+
export declare const createDatasetsContext: (app: UruAppRuntimeClient, clientOptions: CreateUruAppRuntimeClientOptions, keys?: CallKeys) => UruDatasetsContext;
|
package/dist/datasets.js
CHANGED
|
@@ -7,9 +7,12 @@
|
|
|
7
7
|
* the current Dataset request paths and overloads.
|
|
8
8
|
*/
|
|
9
9
|
import { datasetIdsForRequest, datasetRowIdsForRequest, datasetRowsForRequest, decodeDatasetMutationResult, decodeDatasetRowsResult, decodeDefaultDatasetMutationResult, decodeDefaultDatasetRowsResult, datasetWriteErrorMessage, serializeDatasetRequest, } from "./dataset-boundary.js";
|
|
10
|
+
import { resolveDamperConfig } from "./dampers.js";
|
|
10
11
|
import { UruAppRuntimeError } from "./errors.js";
|
|
12
|
+
import { RANDOM_CALL_KEYS } from "./job-run.js";
|
|
11
13
|
import { requireCompletedRuntimeResponse, resolveHeaders, resolveRuntimeFetch, runtimeBasePath, trimTrailingSlash, } from "./runtime.js";
|
|
12
|
-
|
|
14
|
+
import { postWithResends } from "./transport-retry.js";
|
|
15
|
+
const fetchDatasetWrite = async (options, subpath, body, send) => {
|
|
13
16
|
const runtimeFetch = resolveRuntimeFetch(options);
|
|
14
17
|
const deploymentId = typeof options.deploymentId === "string" ? options.deploymentId.trim() : "";
|
|
15
18
|
if (!deploymentId) {
|
|
@@ -25,13 +28,15 @@ const fetchDatasetWrite = async (options, subpath, body) => {
|
|
|
25
28
|
const url = `${baseUrl}${basePath}/apps/${encodeURIComponent(deploymentId)}/${subpath}`;
|
|
26
29
|
const headers = new Headers(await resolveHeaders(options.headers));
|
|
27
30
|
headers.set("content-type", "application/json");
|
|
28
|
-
const response = await
|
|
31
|
+
const { body: parsed, response } = await postWithResends({
|
|
29
32
|
body: serializedBody,
|
|
33
|
+
config: send.config,
|
|
30
34
|
headers,
|
|
31
|
-
|
|
32
|
-
|
|
35
|
+
repeatable: send.repeatable,
|
|
36
|
+
runtimeFetch,
|
|
37
|
+
sendTimeoutMs: 30_000,
|
|
38
|
+
url,
|
|
33
39
|
});
|
|
34
|
-
const parsed = await response.json().catch(() => null);
|
|
35
40
|
if (!response.ok) {
|
|
36
41
|
const message = datasetWriteErrorMessage(parsed, response.status);
|
|
37
42
|
throw new UruAppRuntimeError(message, {
|
|
@@ -41,8 +46,30 @@ const fetchDatasetWrite = async (options, subpath, body) => {
|
|
|
41
46
|
}
|
|
42
47
|
return parsed;
|
|
43
48
|
};
|
|
44
|
-
const postProviderDatasetWrite = async (options, subpath, body) => decodeDefaultDatasetMutationResult(await fetchDatasetWrite(options, subpath, body));
|
|
45
|
-
const postProviderDatasetWriteDecoded = async (options, subpath, body, decodeResult) => decodeDatasetMutationResult(await fetchDatasetWrite(options, subpath, body), decodeResult);
|
|
49
|
+
const postProviderDatasetWrite = async (options, subpath, body, send) => decodeDefaultDatasetMutationResult(await fetchDatasetWrite(options, subpath, body, send));
|
|
50
|
+
const postProviderDatasetWriteDecoded = async (options, subpath, body, send, decodeResult) => decodeDatasetMutationResult(await fetchDatasetWrite(options, subpath, body, send), decodeResult);
|
|
51
|
+
/**
|
|
52
|
+
* One row write's body with its key. Each call gets its own key, and every
|
|
53
|
+
* send of that call carries it, so a resend after a lost response or a
|
|
54
|
+
* temporary answer joins the stored command rather than making a second
|
|
55
|
+
* write.
|
|
56
|
+
*/
|
|
57
|
+
const keyedMutationBody = (body, mutationOptions, config, keys, datasetRef) => {
|
|
58
|
+
const callerKey = mutationOptions?.idempotencyKey;
|
|
59
|
+
const idempotencyKey = callerKey !== undefined && callerKey !== ""
|
|
60
|
+
? callerKey
|
|
61
|
+
: config.defaultIdempotencyKeys
|
|
62
|
+
? keys.next("dataset", datasetRef.trim())
|
|
63
|
+
: undefined;
|
|
64
|
+
return {
|
|
65
|
+
body: {
|
|
66
|
+
...body,
|
|
67
|
+
...mutationOptions,
|
|
68
|
+
...(idempotencyKey === undefined ? {} : { idempotencyKey }),
|
|
69
|
+
},
|
|
70
|
+
send: { config, repeatable: idempotencyKey !== undefined },
|
|
71
|
+
};
|
|
72
|
+
};
|
|
46
73
|
const datasetMutationPath = (datasetRef) => {
|
|
47
74
|
const slug = datasetRef.trim();
|
|
48
75
|
if (!slug) {
|
|
@@ -61,7 +88,7 @@ const idMutationBody = (operation, rowIds) => ({
|
|
|
61
88
|
operation,
|
|
62
89
|
row_ids: datasetRowIdsForRequest(rowIds),
|
|
63
90
|
});
|
|
64
|
-
const sqlBody = (sql, options) => {
|
|
91
|
+
const sqlBody = (sql, options, config, keys) => {
|
|
65
92
|
if (typeof sql !== "string" || sql.trim() === "") {
|
|
66
93
|
throw new UruAppRuntimeError("SQL statement is required.", {
|
|
67
94
|
body: sql,
|
|
@@ -89,6 +116,14 @@ const sqlBody = (sql, options) => {
|
|
|
89
116
|
if (options.timeoutMs !== undefined) {
|
|
90
117
|
body.timeout_ms = options.timeoutMs;
|
|
91
118
|
}
|
|
119
|
+
const idempotencyKey = options.idempotencyKey !== undefined && options.idempotencyKey !== ""
|
|
120
|
+
? options.idempotencyKey
|
|
121
|
+
: config.defaultIdempotencyKeys
|
|
122
|
+
? keys.next("dataset-sql", "")
|
|
123
|
+
: undefined;
|
|
124
|
+
if (idempotencyKey !== undefined) {
|
|
125
|
+
body.idempotency_key = idempotencyKey;
|
|
126
|
+
}
|
|
92
127
|
return body;
|
|
93
128
|
};
|
|
94
129
|
const createQueryRowsInvoker = (app) => {
|
|
@@ -101,44 +136,63 @@ const createQueryRowsInvoker = (app) => {
|
|
|
101
136
|
}
|
|
102
137
|
return queryRows;
|
|
103
138
|
};
|
|
104
|
-
const createRowMutationInvoker = (options) => {
|
|
139
|
+
const createRowMutationInvoker = (options, config, keys) => {
|
|
105
140
|
async function mutate(datasetRef, rows, decodeResult, mutationOptions) {
|
|
106
|
-
const body = { ...upsertBody(rows), ...mutationOptions };
|
|
107
141
|
const path = datasetMutationPath(datasetRef);
|
|
142
|
+
const { body, send } = keyedMutationBody(upsertBody(rows), mutationOptions, config, keys, datasetRef);
|
|
108
143
|
if (decodeResult === undefined) {
|
|
109
|
-
return await postProviderDatasetWrite(options, path, body);
|
|
144
|
+
return await postProviderDatasetWrite(options, path, body, send);
|
|
110
145
|
}
|
|
111
|
-
return await postProviderDatasetWriteDecoded(options, path, body, decodeResult);
|
|
146
|
+
return await postProviderDatasetWriteDecoded(options, path, body, send, decodeResult);
|
|
112
147
|
}
|
|
113
148
|
return mutate;
|
|
114
149
|
};
|
|
115
|
-
const
|
|
150
|
+
const createRowViewMutationInvoker = (options, config, keys) => {
|
|
151
|
+
async function mutate(datasetRef, rows, decodeResult, mutationOptions) {
|
|
152
|
+
const path = datasetMutationPath(datasetRef);
|
|
153
|
+
const { body, send } = keyedMutationBody({ operation: "upsertFields", rows: datasetRowsForRequest(rows) }, mutationOptions, config, keys, datasetRef);
|
|
154
|
+
if (decodeResult === undefined) {
|
|
155
|
+
return await postProviderDatasetWrite(options, path, body, send);
|
|
156
|
+
}
|
|
157
|
+
return await postProviderDatasetWriteDecoded(options, path, body, send, decodeResult);
|
|
158
|
+
}
|
|
159
|
+
return mutate;
|
|
160
|
+
};
|
|
161
|
+
const createIdMutationInvoker = (options, config, keys, operation) => {
|
|
116
162
|
async function mutate(datasetRef, rowIds, decodeResult, mutationOptions) {
|
|
117
|
-
const body = { ...idMutationBody(operation, rowIds), ...mutationOptions };
|
|
118
163
|
const path = datasetMutationPath(datasetRef);
|
|
164
|
+
const { body, send } = keyedMutationBody(idMutationBody(operation, rowIds), mutationOptions, config, keys, datasetRef);
|
|
119
165
|
if (decodeResult === undefined) {
|
|
120
|
-
return await postProviderDatasetWrite(options, path, body);
|
|
166
|
+
return await postProviderDatasetWrite(options, path, body, send);
|
|
121
167
|
}
|
|
122
|
-
return await postProviderDatasetWriteDecoded(options, path, body, decodeResult);
|
|
168
|
+
return await postProviderDatasetWriteDecoded(options, path, body, send, decodeResult);
|
|
123
169
|
}
|
|
124
170
|
return mutate;
|
|
125
171
|
};
|
|
126
|
-
const createSqlWriteInvoker = (options) => {
|
|
172
|
+
const createSqlWriteInvoker = (options, config, keys) => {
|
|
173
|
+
// A SQL statement is never sent again here. Its key lets the server answer
|
|
174
|
+
// a caller's own second send of the same statement with the first saved
|
|
175
|
+
// result instead of running it twice.
|
|
176
|
+
const send = { config, repeatable: false };
|
|
127
177
|
async function write(sql, writeOptions, decodeResult) {
|
|
128
|
-
const body = sqlBody(sql, writeOptions);
|
|
178
|
+
const body = sqlBody(sql, writeOptions, config, keys);
|
|
129
179
|
if (decodeResult === undefined) {
|
|
130
|
-
return await postProviderDatasetWrite(options, "dataset-sql", body);
|
|
180
|
+
return await postProviderDatasetWrite(options, "dataset-sql", body, send);
|
|
131
181
|
}
|
|
132
|
-
return await postProviderDatasetWriteDecoded(options, "dataset-sql", body, decodeResult);
|
|
182
|
+
return await postProviderDatasetWriteDecoded(options, "dataset-sql", body, send, decodeResult);
|
|
133
183
|
}
|
|
134
184
|
return write;
|
|
135
185
|
};
|
|
136
186
|
/** Build the Dataset surface hung off a server context. */
|
|
137
|
-
export const createDatasetsContext = (app, clientOptions) =>
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
187
|
+
export const createDatasetsContext = (app, clientOptions, keys = RANDOM_CALL_KEYS) => {
|
|
188
|
+
const config = resolveDamperConfig(clientOptions.dampers);
|
|
189
|
+
return {
|
|
190
|
+
deleteRows: createIdMutationInvoker(clientOptions, config, keys, "delete"),
|
|
191
|
+
insertRows: createRowMutationInvoker(clientOptions, config, keys),
|
|
192
|
+
queryRows: createQueryRowsInvoker(app),
|
|
193
|
+
restoreRows: createIdMutationInvoker(clientOptions, config, keys, "restore"),
|
|
194
|
+
sqlWrite: createSqlWriteInvoker(clientOptions, config, keys),
|
|
195
|
+
upsertRows: createRowMutationInvoker(clientOptions, config, keys),
|
|
196
|
+
upsertRowViews: createRowViewMutationInvoker(clientOptions, config, keys),
|
|
197
|
+
};
|
|
198
|
+
};
|
package/dist/errors.js
CHANGED
|
@@ -13,15 +13,14 @@ const SAFE_RUNTIME_FAILURE_CODES = new Set([
|
|
|
13
13
|
"policy_receipt_handoff_invalid",
|
|
14
14
|
"mcp_proxy_not_configured",
|
|
15
15
|
"missing_api_key",
|
|
16
|
-
"
|
|
17
|
-
"
|
|
16
|
+
"row_conflict",
|
|
17
|
+
"dataset_conflict",
|
|
18
|
+
"idempotency_conflict",
|
|
18
19
|
"timeout",
|
|
19
20
|
"transport_error",
|
|
20
21
|
"connection_unavailable",
|
|
21
22
|
"artifact_tool_receipt_unavailable",
|
|
22
23
|
"artifact_tool_attempt_unavailable",
|
|
23
|
-
"tool_result_content_unavailable",
|
|
24
|
-
"tool_parameters_content_unavailable",
|
|
25
24
|
"artifact_tool_refresh_failed",
|
|
26
25
|
"tool_admission_unavailable",
|
|
27
26
|
"tool_gateway_denied",
|
|
@@ -72,6 +71,7 @@ const SAFE_RUNTIME_FAILURE_CODES = new Set([
|
|
|
72
71
|
"job_cleanup_failed",
|
|
73
72
|
"job_completion_not_accepted",
|
|
74
73
|
"job_handler_failed",
|
|
74
|
+
"job_import_failed",
|
|
75
75
|
"job_hard_deadline",
|
|
76
76
|
"job_machine_start_failed",
|
|
77
77
|
"job_machine_stopped",
|
|
@@ -98,6 +98,7 @@ const SAFE_RUNTIME_FAILURE_CODES = new Set([
|
|
|
98
98
|
"provider_unavailable",
|
|
99
99
|
"public_tool_budget_limited",
|
|
100
100
|
"public_tool_budget_unavailable",
|
|
101
|
+
"result_limit",
|
|
101
102
|
"runtime_capability_unsupported",
|
|
102
103
|
"runtime_unavailable",
|
|
103
104
|
"tool_execution_failed",
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { UruBackgroundJobCallOptions, UruBackgroundJobRequest, UruJobCheckpoint, UruProviderRuntimeEnvironment, UruServerContext } from "@uru-intelligence/app";
|
|
2
|
+
import type { JobCoordinator } from "./job-coordinator.js";
|
|
3
|
+
/** Return this only after a trusted server confirms the exact approved payload. */
|
|
4
|
+
export interface ApprovedExternalIntent {
|
|
5
|
+
approvalId: string;
|
|
6
|
+
approvedByActorId: string;
|
|
7
|
+
targetId: string;
|
|
8
|
+
payload: Readonly<Record<string, unknown>>;
|
|
9
|
+
deadlineAt: number;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* A server-owned approval lookup. It must use verified actor identity, require
|
|
13
|
+
* that actor to match the approver, and return only a current exact approval.
|
|
14
|
+
* A Gem-owned Dataset row is not proof of approval.
|
|
15
|
+
*/
|
|
16
|
+
export type LoadApprovedExternalIntent = (approvalId: string, signal: AbortSignal | undefined) => Promise<ApprovedExternalIntent | null>;
|
|
17
|
+
/** Build a job-side loader from trusted runtime data, such as its run id. */
|
|
18
|
+
export type CreateJobApprovedExternalIntentLoader = (env: UruProviderRuntimeEnvironment) => LoadApprovedExternalIntent;
|
|
19
|
+
export type ApprovedExternalWriteInput = Pick<ApprovedExternalIntent, "approvalId" | "approvedByActorId" | "targetId" | "payload">;
|
|
20
|
+
export type ApprovedExternalWriteResult = {
|
|
21
|
+
kind: "complete";
|
|
22
|
+
approvalId: string;
|
|
23
|
+
targetId: string;
|
|
24
|
+
} | {
|
|
25
|
+
kind: "unknown";
|
|
26
|
+
approvalId: string;
|
|
27
|
+
targetId: string;
|
|
28
|
+
reason: "provider_outcome_unknown";
|
|
29
|
+
} | {
|
|
30
|
+
kind: "canceled";
|
|
31
|
+
};
|
|
32
|
+
type ApprovedExternalWriteContext = Pick<UruServerContext, "actions" | "jobs">;
|
|
33
|
+
export declare const approvedExternalWriteRequest: (intent: ApprovedExternalIntent) => UruBackgroundJobRequest;
|
|
34
|
+
/** Start once, after approval. Uru still checks the bound tool and its policy. */
|
|
35
|
+
export declare const startApprovedExternalWrite: (coordinator: JobCoordinator, approvalId: string, loadApprovedIntent: LoadApprovedExternalIntent, options?: UruBackgroundJobCallOptions) => Promise<{
|
|
36
|
+
record: import("@uru-intelligence/app").UruBackgroundJobRecord;
|
|
37
|
+
response: import("@uru-intelligence/app").UruAppRuntimeInvocationResponse;
|
|
38
|
+
}>;
|
|
39
|
+
/** Recover the same request. Never mint a new key after an uncertain result. */
|
|
40
|
+
export declare const resumeApprovedExternalWrite: (coordinator: JobCoordinator, approvalId: string, options?: UruBackgroundJobCallOptions) => Promise<import("@uru-intelligence/app").UruBackgroundJobResumeResult>;
|
|
41
|
+
export declare const observeApprovedExternalWrite: (coordinator: JobCoordinator, approvalId: string, options?: UruBackgroundJobCallOptions) => Promise<import("@uru-intelligence/app").UruBackgroundJobObservation>;
|
|
42
|
+
export declare const waitApprovedExternalWrite: (coordinator: JobCoordinator, approvalId: string, options?: UruBackgroundJobCallOptions) => Promise<import("@uru-intelligence/app").UruBackgroundJobWaitResult>;
|
|
43
|
+
export declare const cancelApprovedExternalWrite: (coordinator: JobCoordinator, approvalId: string, options?: UruBackgroundJobCallOptions) => Promise<import("@uru-intelligence/app").UruBackgroundJobResumeResult>;
|
|
44
|
+
export declare const approvedExternalIntentMatchesInput: (intent: ApprovedExternalIntent, input: ApprovedExternalWriteInput) => boolean;
|
|
45
|
+
export declare const isProviderOutcomeUnknown: (error: unknown) => boolean;
|
|
46
|
+
/** Run the approved provider action from a durable program job. */
|
|
47
|
+
export declare const runApprovedExternalWrite: (context: ApprovedExternalWriteContext, input: ApprovedExternalWriteInput, checkpoint: UruJobCheckpoint | null, signal: AbortSignal, loadApprovedIntent: LoadApprovedExternalIntent) => Promise<ApprovedExternalWriteResult>;
|
|
48
|
+
/** Build a published handler with its trusted server approval lookup. */
|
|
49
|
+
export declare const createSendApprovedUpdateHandler: (createContext: (env: UruProviderRuntimeEnvironment) => ApprovedExternalWriteContext, createLoadApprovedIntent: CreateJobApprovedExternalIntentLoader) => (env: UruProviderRuntimeEnvironment, input: ApprovedExternalWriteInput, checkpoint: UruJobCheckpoint | null, signal: AbortSignal) => Promise<ApprovedExternalWriteResult>;
|
|
50
|
+
export {};
|
|
@@ -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 @@
|
|
|
1
|
+
export {};
|
|
@@ -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
|
+
};
|