@opengeni/codemode 1.2.1-canary.37222177070001 → 1.3.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/README.md CHANGED
@@ -103,8 +103,15 @@ by the shared attempt executor. Catalog, approval, authorization, input
103
103
  validation, and argument-sensitive connector-policy prepare complete before the
104
104
  durable execution-start marker. The prepared call performs connector begin at
105
105
  the executor boundary and completion afterward, so model MCP and Codemode share
106
- one lifecycle while invalid, blocked, Ask, or unavailable-policy calls settle
107
- before provider execution. Human-gated model calls additionally require the
106
+ one lifecycle. Invalid, blocked, or unavailable-policy calls settle before
107
+ provider execution. With the `durableApproval` protocol capability, Ask becomes
108
+ `waiting_for_approval` and returns `CodemodeApprovalPendingError` with a compact
109
+ operation handle. It releases the claim and pauses the owning turn for review.
110
+ Human approval resumes the stored operation once; it does not restore a
111
+ JavaScript stack. Use `environmentCodemodeClient().status(id)` or `.resume(id)`
112
+ from the current authorized attempt of the same turn to observe results.
113
+ `ogtool read <id>` and `ogtool resume <id>` expose the same behavior. Older
114
+ clients receive an upgrade-required failure before an approval can execute. Human-gated model calls additionally require the
108
115
  attempt host's exact approved SDK invocation context; calling the environment
109
116
  directly cannot bypass approval. The dispatcher keeps its claim alive during
110
117
  gateway preparation and reuses a deterministic durable tool-created event if a
@@ -161,3 +168,31 @@ await workbook.apply([
161
168
  },
162
169
  ]);
163
170
  ```
171
+
172
+ ### Frozen paginated selections
173
+
174
+ `collectIdPages(load, { maxItems, maxPages, signal })` reads all pages, removes
175
+ repeated IDs and refuses incomplete selections (repeated cursor, empty continued
176
+ page, cap, provider error or cancellation). Defaults: 10,000 IDs and 200 pages;
177
+ hard bounds: 50,000 IDs and 1,000 pages. `planIdBatches(ids, 1000)` freezes a
178
+ selection digest and distinct operation IDs for chunks of at most 1,000 IDs.
179
+ It performs no writes. Save the plan in the agent workspace before submitting
180
+ chunks; keep the arrays out of model output. Never continue searching after a
181
+ mutation changes the search membership.
182
+
183
+ For Gmail, use `search_messages` with `messageFormat: "IDS_ONLY"` (or
184
+ `search_threads` with `view: "IDS_ONLY"`). These return one list page without
185
+ hydration requests; existing rich views keep their defaults. Adapt that page's
186
+ `messages.map(message => message.id)` and `nextPageToken` to `collectIdPages`.
187
+ Each planned chunk is an independently authorized durable call. An Ask returns
188
+ a waiting handle; catch that typed result and retain its operation ID rather
189
+ than copying arguments into another call. Original JavaScript locals are not
190
+ restored when a turn resumes. Inspect saved handles on the next attempt.
191
+
192
+ `batch_modify_messages` returns `status: "acknowledged"`, `submittedCount` and
193
+ `reconciliation: "not_checked"`. Gmail's empty success response establishes
194
+ batch acceptance, not a per-message verification. The former `modified: true`
195
+ claim and echoed ID array are removed. `summarizeIdBatches(plan, receipts)`
196
+ counts acknowledged, failed-before-effect, unknown, waiting and unstarted IDs
197
+ separately. Only mark a receipt acknowledged after that provider response;
198
+ transport uncertainty is unknown and must not be retried automatically.
package/dist/index.d.ts CHANGED
@@ -64,6 +64,14 @@ export declare class CodemodeOperationError extends Error {
64
64
  readonly code: string;
65
65
  constructor(operation: CodemodeOperationValue, code: string);
66
66
  }
67
+ /** Compact receipt: payloads remain in the protected operation journal. */
68
+ export declare class CodemodeApprovalPendingError extends Error {
69
+ readonly operationId: string;
70
+ readonly approvalRequestId: string | undefined;
71
+ readonly code = "codemode_approval_pending";
72
+ readonly state = "waiting_for_approval";
73
+ constructor(operationId: string, approvalRequestId: string | undefined);
74
+ }
67
75
  export type CodemodeTokenProvider = string | (() => string | Promise<string>);
68
76
  export type CodemodeClientOptions = {
69
77
  /** `/v1/workspaces/:workspaceId/codemode` base URL. */
@@ -118,6 +126,78 @@ export declare class CodemodeClient {
118
126
  /** Return structured content, or a local-image wrapper for typed multimodal results. */
119
127
  callPathValue(path: readonly string[], argumentsValue?: Record<string, unknown>, options?: CodemodeCallOptions): Promise<unknown>;
120
128
  private submit;
129
+ /** Observe a durable handle using the current attempt, without resubmitting its payload. */
130
+ status(operationId: string, signal?: AbortSignal): Promise<{
131
+ operationId: string;
132
+ state: "cancelled" | "completed" | "failed" | "outcome_unknown" | "queued" | "running" | "waiting_for_approval";
133
+ approvalRequestId: string | undefined;
134
+ result: {
135
+ [x: string]: unknown;
136
+ content: ({
137
+ [x: string]: unknown;
138
+ type: "text";
139
+ text: string;
140
+ annotations?: Record<string, import("zod").JSONType> | undefined;
141
+ _meta?: Record<string, import("zod").JSONType> | undefined;
142
+ } | {
143
+ [x: string]: unknown;
144
+ type: "image";
145
+ data: string;
146
+ mimeType: string;
147
+ annotations?: Record<string, import("zod").JSONType> | undefined;
148
+ _meta?: Record<string, import("zod").JSONType> | undefined;
149
+ } | {
150
+ [x: string]: unknown;
151
+ type: "audio";
152
+ data: string;
153
+ mimeType: string;
154
+ annotations?: Record<string, import("zod").JSONType> | undefined;
155
+ _meta?: Record<string, import("zod").JSONType> | undefined;
156
+ } | {
157
+ [x: string]: unknown;
158
+ type: "resource_link";
159
+ name: string;
160
+ title?: string | undefined;
161
+ uri: string;
162
+ description?: string | undefined;
163
+ mimeType?: string | undefined;
164
+ size?: number | undefined;
165
+ icons?: {
166
+ src: string;
167
+ mimeType?: string | undefined;
168
+ sizes?: string[] | undefined;
169
+ theme?: "dark" | "light" | undefined;
170
+ }[] | undefined;
171
+ annotations?: Record<string, import("zod").JSONType> | undefined;
172
+ _meta?: Record<string, import("zod").JSONType> | undefined;
173
+ } | {
174
+ [x: string]: unknown;
175
+ type: "resource";
176
+ resource: {
177
+ [x: string]: unknown;
178
+ uri: string;
179
+ mimeType?: string | undefined;
180
+ text: string;
181
+ _meta?: Record<string, import("zod").JSONType> | undefined;
182
+ } | {
183
+ [x: string]: unknown;
184
+ uri: string;
185
+ mimeType?: string | undefined;
186
+ blob: string;
187
+ _meta?: Record<string, import("zod").JSONType> | undefined;
188
+ };
189
+ annotations?: Record<string, import("zod").JSONType> | undefined;
190
+ _meta?: Record<string, import("zod").JSONType> | undefined;
191
+ })[];
192
+ structuredContent?: Record<string, import("zod").JSONType> | undefined;
193
+ isError?: boolean | undefined;
194
+ _meta?: Record<string, import("zod").JSONType> | undefined;
195
+ } | null;
196
+ errorCode: string | null;
197
+ errorMessage: string | null;
198
+ }>;
199
+ /** Observe continuation after review. Human approval wakes the worker; this never grants permission. */
200
+ resume(operationId: string, options?: Omit<CodemodeCallOptions, "operationId">): Promise<AttemptToolResultValue>;
121
201
  private read;
122
202
  /** Server-side Site preview forwarding. The attempt bearer never enters the
123
203
  * page. Validate tenant routing here; ordinary API handlers authorize the
@@ -138,6 +218,7 @@ export declare class AttemptToolEnvironment {
138
218
  transportMeta?: Record<string, unknown> | null;
139
219
  signal?: AbortSignal;
140
220
  }): Promise<PreparedToolGatewayCall>;
221
+ effectDigest(identity: AttemptToolIdentity): string;
141
222
  callModel(input: ModelAttemptToolCall): Promise<AttemptToolResultValue>;
142
223
  }
143
224
  export declare function createAttemptToolEnvironment(input: CreateAttemptToolEnvironmentInput): AttemptToolEnvironment;
@@ -156,3 +237,4 @@ export * from "./artifacts.js";
156
237
  export * from "./structured.js";
157
238
  export * from "./declarations.js";
158
239
  export * from "./site.js";
240
+ export * from "./pagination.js";
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/index.ts
2
- import { randomUUID as randomUUID2 } from "crypto";
2
+ import { randomUUID as randomUUID3 } from "crypto";
3
3
  import {
4
4
  ATTEMPT_TOOL_CATALOG_VERSION,
5
5
  ATTEMPT_TOOL_CATALOG_MAX_BYTES,
@@ -1427,6 +1427,72 @@ function isRecord(value) {
1427
1427
  return typeof value === "object" && value !== null && !Array.isArray(value);
1428
1428
  }
1429
1429
 
1430
+ // src/pagination.ts
1431
+ import { createHash, randomUUID as randomUUID2 } from "crypto";
1432
+ async function collectIdPages(load, options = {}) {
1433
+ const maxItems = options.maxItems ?? 1e4, maxPages = options.maxPages ?? 200;
1434
+ if (!Number.isSafeInteger(maxItems) || maxItems < 1 || maxItems > 5e4 || !Number.isSafeInteger(maxPages) || maxPages < 1 || maxPages > 1e3)
1435
+ throw new Error("Invalid selection limit");
1436
+ const ids = /* @__PURE__ */ new Set(), tokens = /* @__PURE__ */ new Set();
1437
+ let token;
1438
+ for (let index = 0; index < maxPages; index++) {
1439
+ options.signal?.throwIfAborted();
1440
+ const page = await load(token, options.signal);
1441
+ options.signal?.throwIfAborted();
1442
+ if (!Array.isArray(page?.ids) || page.ids.length > 5e4)
1443
+ throw new Error("Invalid selection page");
1444
+ for (const id of page.ids) {
1445
+ if (typeof id !== "string" || !id || id.length > 256) throw new Error("Invalid selection ID");
1446
+ ids.add(id);
1447
+ if (ids.size > maxItems)
1448
+ throw new Error("Selection exceeds item limit; no complete selection returned");
1449
+ }
1450
+ if (!page.nextPageToken) return Object.freeze([...ids]);
1451
+ if (typeof page.nextPageToken !== "string" || page.nextPageToken.length > 4096)
1452
+ throw new Error("Invalid page token");
1453
+ if (!page.ids.length || tokens.has(page.nextPageToken))
1454
+ throw new Error("Pagination did not progress; no complete selection returned");
1455
+ tokens.add(page.nextPageToken);
1456
+ token = page.nextPageToken;
1457
+ }
1458
+ throw new Error("Selection exceeds page limit; no complete selection returned");
1459
+ }
1460
+ function planIdBatches(selection, maxBatchSize = 1e3) {
1461
+ if (!Number.isSafeInteger(maxBatchSize) || maxBatchSize < 1 || maxBatchSize > 1e3 || selection.length > 5e4)
1462
+ throw new Error("Invalid batch limit");
1463
+ if (selection.some((id) => typeof id !== "string" || !id || id.length > 256))
1464
+ throw new Error("Invalid selection ID");
1465
+ const ids = [...new Set(selection)];
1466
+ const batches = Array.from(
1467
+ { length: Math.ceil(ids.length / maxBatchSize) },
1468
+ (_, index) => Object.freeze({
1469
+ operationId: randomUUID2(),
1470
+ ids: Object.freeze(ids.slice(index * maxBatchSize, (index + 1) * maxBatchSize))
1471
+ })
1472
+ );
1473
+ return Object.freeze({
1474
+ id: randomUUID2(),
1475
+ selectionDigest: createHash("sha256").update(JSON.stringify(ids)).digest("hex"),
1476
+ count: ids.length,
1477
+ batches: Object.freeze(batches)
1478
+ });
1479
+ }
1480
+ function summarizeIdBatches(plan, receipts) {
1481
+ const byId = /* @__PURE__ */ new Map();
1482
+ const known = new Set(plan.batches.map((batch) => batch.operationId));
1483
+ for (const receipt of receipts) {
1484
+ if (!["acknowledged", "failed_before_effect", "unknown", "waiting"].includes(receipt.outcome))
1485
+ throw new Error("Invalid batch outcome");
1486
+ if (!known.has(receipt.operationId) || byId.has(receipt.operationId))
1487
+ throw new Error("Receipt does not uniquely identify a planned batch");
1488
+ byId.set(receipt.operationId, receipt.outcome);
1489
+ }
1490
+ const counts = { acknowledged: 0, failed_before_effect: 0, unknown: 0, waiting: 0, unstarted: 0 };
1491
+ for (const batch of plan.batches)
1492
+ counts[byId.get(batch.operationId) ?? "unstarted"] += batch.ids.length;
1493
+ return { selected: plan.count, ...counts, individualStateVerified: false };
1494
+ }
1495
+
1430
1496
  // src/index.ts
1431
1497
  var CodemodeTransportError = class extends Error {
1432
1498
  constructor(message, status = null, options = {}) {
@@ -1450,7 +1516,20 @@ var CodemodeOperationError = class extends Error {
1450
1516
  this.operation = operation;
1451
1517
  this.code = code;
1452
1518
  this.name = "CodemodeOperationError";
1519
+ Object.defineProperty(this, "operation", { value: operation, enumerable: false });
1520
+ }
1521
+ };
1522
+ var CodemodeApprovalPendingError = class extends Error {
1523
+ constructor(operationId, approvalRequestId) {
1524
+ super(
1525
+ `Operation ${operationId} is waiting for approval. After review, read or resume this handle; do not submit its arguments again.`
1526
+ );
1527
+ this.operationId = operationId;
1528
+ this.approvalRequestId = approvalRequestId;
1529
+ this.name = "CodemodeApprovalPendingError";
1453
1530
  }
1531
+ code = "codemode_approval_pending";
1532
+ state = "waiting_for_approval";
1454
1533
  };
1455
1534
  var CodemodeToolCallError = class extends Error {
1456
1535
  constructor(result) {
@@ -1513,7 +1592,7 @@ var CodemodeClient = class {
1513
1592
  let catalog = await this.catalog(options.signal ? { signal: options.signal } : {});
1514
1593
  let entry = resolveEntry(catalog);
1515
1594
  if (!entry) throw new AttemptToolNotFoundError();
1516
- const operationId = options.operationId ?? randomUUID2();
1595
+ const operationId = options.operationId ?? randomUUID3();
1517
1596
  const deadline = Date.now() + boundedPositiveInteger(options.timeoutMs ?? this.timeoutMs, 1e3, 60 * 6e4);
1518
1597
  let submitted = false;
1519
1598
  let staleRefreshAttempted = false;
@@ -1580,6 +1659,9 @@ var CodemodeClient = class {
1580
1659
  } else {
1581
1660
  operation = await this.read(operationId, options.signal);
1582
1661
  }
1662
+ if (operation.state === "waiting_for_approval") {
1663
+ throw new CodemodeApprovalPendingError(operation.operationId, operation.approvalRequestId);
1664
+ }
1583
1665
  if (operation.state === "completed") {
1584
1666
  return { result: AttemptToolResult.parse(operation.result), entry };
1585
1667
  }
@@ -1639,11 +1721,45 @@ var CodemodeClient = class {
1639
1721
  operationId,
1640
1722
  catalogDigest,
1641
1723
  identity,
1642
- arguments: argumentsValue
1724
+ arguments: argumentsValue,
1725
+ durableApproval: true
1643
1726
  })
1644
1727
  });
1645
1728
  return CodemodeCallSubmission.parse(await response.json()).operation;
1646
1729
  }
1730
+ /** Observe a durable handle using the current attempt, without resubmitting its payload. */
1731
+ async status(operationId, signal) {
1732
+ const operation = await this.read(operationId, signal);
1733
+ return {
1734
+ operationId: operation.operationId,
1735
+ state: operation.state,
1736
+ approvalRequestId: operation.approvalRequestId,
1737
+ result: operation.result,
1738
+ errorCode: operation.errorCode,
1739
+ errorMessage: operation.errorMessage
1740
+ };
1741
+ }
1742
+ /** Observe continuation after review. Human approval wakes the worker; this never grants permission. */
1743
+ async resume(operationId, options = {}) {
1744
+ const deadline = Date.now() + boundedPositiveInteger(options.timeoutMs ?? this.timeoutMs, 1e3, 60 * 6e4);
1745
+ while (true) {
1746
+ throwIfAborted(options.signal);
1747
+ const operation = await this.read(operationId, options.signal);
1748
+ if (operation.state === "waiting_for_approval")
1749
+ throw new CodemodeApprovalPendingError(operation.operationId, operation.approvalRequestId);
1750
+ if (operation.state === "completed") return AttemptToolResult.parse(operation.result);
1751
+ if (["failed", "outcome_unknown", "cancelled"].includes(operation.state))
1752
+ throw new CodemodeOperationError(
1753
+ operation,
1754
+ operation.errorCode ?? `codemode_${operation.state}`
1755
+ );
1756
+ if (Date.now() >= deadline)
1757
+ throw new CodemodeTransportError(
1758
+ `Codemode operation ${operationId} did not settle before the client deadline`
1759
+ );
1760
+ await abortableDelay(this.pollIntervalMs, options.signal);
1761
+ }
1762
+ }
1647
1763
  async read(operationId, signal) {
1648
1764
  const response = await this.request(`/calls/${operationId}`, {
1649
1765
  method: "GET",
@@ -1664,7 +1780,8 @@ var CodemodeClient = class {
1664
1780
  ...init,
1665
1781
  headers: {
1666
1782
  ...Object.fromEntries(new Headers(init.headers).entries()),
1667
- authorization: `Bearer ${token}`
1783
+ authorization: `Bearer ${token}`,
1784
+ "x-opengeni-codemode-capabilities": "durable-approval-v1"
1668
1785
  }
1669
1786
  });
1670
1787
  if (!response.ok && throwOnError) {
@@ -1737,6 +1854,9 @@ var AttemptToolEnvironment = class {
1737
1854
  const call = AttemptToolCall.parse(input);
1738
1855
  return await this.gateway.prepareCall(call, context);
1739
1856
  }
1857
+ effectDigest(identity) {
1858
+ return this.gateway.effectDigest(identity);
1859
+ }
1740
1860
  async callModel(input) {
1741
1861
  return await this.gateway.callModel(input);
1742
1862
  }
@@ -1896,6 +2016,7 @@ export {
1896
2016
  AttemptToolPathCollisionError,
1897
2017
  CODEMODE_ENVIRONMENT,
1898
2018
  CODEMODE_SITE_LOCAL_PATH,
2019
+ CodemodeApprovalPendingError,
1899
2020
  CodemodeArtifact,
1900
2021
  CodemodeArtifactCollection,
1901
2022
  CodemodeArtifactExport,
@@ -1928,6 +2049,7 @@ export {
1928
2049
  codemodeArtifactIds,
1929
2050
  codemodeClientProvider,
1930
2051
  codemodeDispatchSubject,
2052
+ collectIdPages,
1931
2053
  compileCodemodeTools,
1932
2054
  createAttemptToolEnvironment,
1933
2055
  createCodemodeSiteRequestHandler,
@@ -1945,6 +2067,8 @@ export {
1945
2067
  materializeCodemodeImages,
1946
2068
  openGeni,
1947
2069
  parseVerifiedAttemptToolCatalog,
2070
+ planIdBatches,
2071
+ summarizeIdBatches,
1948
2072
  tools
1949
2073
  };
1950
2074
  //# sourceMappingURL=index.js.map