@autohq/cli 0.1.609 → 0.1.611

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.
@@ -37751,7 +37751,7 @@ Object.assign(lookup, {
37751
37751
  // package.json
37752
37752
  var package_default = {
37753
37753
  name: "@autohq/cli",
37754
- version: "0.1.609",
37754
+ version: "0.1.611",
37755
37755
  license: "SEE LICENSE IN README.md",
37756
37756
  publishConfig: {
37757
37757
  access: "public"
@@ -38969,6 +38969,8 @@ var AuthScopeSchema = external_exports.enum([
38969
38969
  "tools:write",
38970
38970
  "environments:read",
38971
38971
  "environments:write",
38972
+ "runtimes:read",
38973
+ "runtimes:write",
38972
38974
  "profiles:read",
38973
38975
  "profiles:write",
38974
38976
  "sessions:read",
@@ -39104,6 +39106,7 @@ function normalizePersistedAuthClient(value2) {
39104
39106
  }
39105
39107
  var SERVICE_ACCOUNT_READ_ONLY_SCOPES = [
39106
39108
  "environments:read",
39109
+ "runtimes:read",
39107
39110
  "tools:read",
39108
39111
  "agents:read",
39109
39112
  "sessions:read",
@@ -42197,6 +42200,270 @@ var SecretRevealResponseSchema = external_exports.object({
42197
42200
  value: external_exports.string()
42198
42201
  });
42199
42202
 
42203
+ // ../../packages/schemas/src/environments.ts
42204
+ var RESOURCE_KIND_ENVIRONMENT = "environment";
42205
+ var CURRENT_SANDBOX_USER_HOME = "/home/user";
42206
+ var LEGACY_SANDBOX_USER_HOMES = ["/home/auto", "/home/node"];
42207
+ var STORED_SANDBOX_USER_HOMES = [
42208
+ CURRENT_SANDBOX_USER_HOME,
42209
+ ...LEGACY_SANDBOX_USER_HOMES
42210
+ ];
42211
+ var EnvironmentSetupCachePathSchema = external_exports.string().trim().refine((value2) => isSafeSandboxUserHomePath(value2), {
42212
+ message: `Expected an absolute path under ${CURRENT_SANDBOX_USER_HOME}`
42213
+ });
42214
+ var StoredEnvironmentSetupCachePathSchema = external_exports.string().trim().refine(
42215
+ (value2) => isSafeSandboxUserHomePath(value2, {
42216
+ allowedHomes: STORED_SANDBOX_USER_HOMES
42217
+ }),
42218
+ {
42219
+ message: `Expected an absolute path under ${CURRENT_SANDBOX_USER_HOME}`
42220
+ }
42221
+ );
42222
+ var EnvironmentImageSchema = external_exports.discriminatedUnion("kind", [
42223
+ external_exports.object({
42224
+ kind: external_exports.literal("preset"),
42225
+ name: ResourceNameSchema
42226
+ }).strict(),
42227
+ external_exports.object({
42228
+ kind: external_exports.literal("base"),
42229
+ ref: external_exports.string().trim().min(1).max(512).refine(isSafeBaseImageRef, {
42230
+ message: "Expected a single Docker/OCI image reference"
42231
+ })
42232
+ }).strict()
42233
+ ]);
42234
+ var StoredEnvironmentImageSchema = external_exports.discriminatedUnion("kind", [
42235
+ external_exports.object({
42236
+ kind: external_exports.literal("preset"),
42237
+ name: external_exports.string().trim().min(1)
42238
+ }).strict(),
42239
+ external_exports.object({
42240
+ kind: external_exports.literal("base"),
42241
+ ref: external_exports.string().trim().min(1).refine(isSafeBaseImageRef, {
42242
+ message: "Expected a single Docker/OCI image reference"
42243
+ })
42244
+ }).strict()
42245
+ ]);
42246
+ var ENVIRONMENT_APPROVALS_MODES = ["bypass", "prompt"];
42247
+ var EnvironmentApprovalsSchema = external_exports.enum(ENVIRONMENT_APPROVALS_MODES);
42248
+ var EnvironmentSetupSchema = environmentSetupSchema(
42249
+ StoredEnvironmentSetupCachePathSchema
42250
+ );
42251
+ var EnvironmentApplySetupSchema = environmentSetupSchema(
42252
+ EnvironmentSetupCachePathSchema
42253
+ );
42254
+ var EnvironmentSetupCacheSchema = external_exports.object({
42255
+ ttl: external_exports.string().trim().refine(isSetupCacheTtl, {
42256
+ message: "Expected a positive setup cache TTL such as 30m, 24h, or 7d"
42257
+ })
42258
+ }).strict();
42259
+ var EnvironmentResourcesSchema = external_exports.object({
42260
+ cpuCount: external_exports.number().int().min(1).optional(),
42261
+ memoryMB: external_exports.number().int().min(128).optional()
42262
+ }).strict().refine(
42263
+ (resources) => resources.cpuCount !== void 0 || resources.memoryMB !== void 0,
42264
+ {
42265
+ message: "Expected at least one runtime resource setting"
42266
+ }
42267
+ );
42268
+ var EnvironmentSpecSchema = environmentSpecSchema({
42269
+ imageSchema: StoredEnvironmentImageSchema,
42270
+ setupSchema: EnvironmentSetupSchema
42271
+ });
42272
+ var EnvironmentApplySpecSchema = environmentSpecSchema({
42273
+ imageSchema: EnvironmentImageSchema,
42274
+ setupSchema: EnvironmentApplySetupSchema
42275
+ });
42276
+ var EnvironmentCandidateSpecSchema = EnvironmentApplySpecSchema;
42277
+ var EnvironmentResourceSchema = resourceEnvelopeSchema(
42278
+ EnvironmentSpecSchema
42279
+ );
42280
+ var EnvironmentApplyRequestSchema = resourceApplySchema(
42281
+ EnvironmentApplySpecSchema
42282
+ );
42283
+ function environmentSetupSchema(cachePathSchema) {
42284
+ return external_exports.object({
42285
+ name: ResourceNameSchema,
42286
+ commands: external_exports.array(external_exports.string().trim().min(1)).min(1),
42287
+ cache: external_exports.object({
42288
+ key: ResourceNameSchema.optional(),
42289
+ files: external_exports.array(
42290
+ external_exports.string().trim().refine(isSafeRelativePath, {
42291
+ message: "Expected a relative path without traversal"
42292
+ })
42293
+ ).default([]),
42294
+ paths: external_exports.array(cachePathSchema).default([])
42295
+ }).strict().default({ files: [], paths: [] })
42296
+ }).strict();
42297
+ }
42298
+ function environmentSpecSchema({
42299
+ imageSchema,
42300
+ setupSchema
42301
+ }) {
42302
+ return external_exports.object({
42303
+ image: imageSchema,
42304
+ env: SecretEnvSchema.default({}),
42305
+ resources: EnvironmentResourcesSchema.optional(),
42306
+ steps: external_exports.array(external_exports.string()).default([]),
42307
+ setup: external_exports.array(setupSchema).default([]),
42308
+ setupCache: EnvironmentSetupCacheSchema.optional(),
42309
+ // Optional rather than defaulted: a default would materialize the key
42310
+ // into stored specs and session environment snapshots the moment the web
42311
+ // app deploys, and this strict schema on a not-yet-deployed worker would
42312
+ // reject those rows (web and workers do not deploy atomically). Absent
42313
+ // means `bypass`; consumers default at the read boundary.
42314
+ approvals: EnvironmentApprovalsSchema.optional()
42315
+ }).strict();
42316
+ }
42317
+ function isSafeSandboxUserHomePath(value2, options = {}) {
42318
+ return (options.allowedHomes ?? [CURRENT_SANDBOX_USER_HOME]).some(
42319
+ (home) => isSafePathUnderHome(value2, home)
42320
+ );
42321
+ }
42322
+ function isSafePathUnderHome(value2, home) {
42323
+ const prefix = `${home}/`;
42324
+ if (!value2.startsWith(prefix)) {
42325
+ return false;
42326
+ }
42327
+ const relative2 = value2.slice(prefix.length);
42328
+ return relative2.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..");
42329
+ }
42330
+ function isSafeRelativePath(value2) {
42331
+ if (!value2 || value2.startsWith("/")) {
42332
+ return false;
42333
+ }
42334
+ return value2.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..");
42335
+ }
42336
+ function isSafeBaseImageRef(value2) {
42337
+ return !value2.startsWith("-") && /^[^\s#\\]+$/.test(value2);
42338
+ }
42339
+ function isSetupCacheTtl(value2) {
42340
+ return /^[1-9][0-9]*(s|m|h|d)$/.test(value2);
42341
+ }
42342
+
42343
+ // ../../packages/schemas/src/hosted-runtimes.ts
42344
+ var HOSTED_RUNTIME_STATUSES = [
42345
+ "queued",
42346
+ "provisioning",
42347
+ "running",
42348
+ "closing",
42349
+ "closed"
42350
+ ];
42351
+ var HOSTED_RUNTIME_OUTCOMES = [
42352
+ "succeeded",
42353
+ "failed",
42354
+ "cancelled"
42355
+ ];
42356
+ var HOSTED_RUNTIME_COMMAND_STATUSES = [
42357
+ "pending",
42358
+ "running",
42359
+ "succeeded",
42360
+ "failed",
42361
+ "cancelled"
42362
+ ];
42363
+ var HOSTED_RUNTIME_CLOSE_REASONS = [
42364
+ "completed",
42365
+ "command_failed",
42366
+ "provision_failed",
42367
+ "requested",
42368
+ "internal_error"
42369
+ ];
42370
+ var HOSTED_RUNTIME_MAX_COMMAND_BUDGET_SECONDS = 45 * 60;
42371
+ var HostedRuntimeEnvironmentInputSchema = external_exports.discriminatedUnion(
42372
+ "kind",
42373
+ [
42374
+ external_exports.object({
42375
+ kind: external_exports.literal("inline"),
42376
+ spec: EnvironmentCandidateSpecSchema
42377
+ }).strict(),
42378
+ external_exports.object({
42379
+ kind: external_exports.literal("applied"),
42380
+ name: ResourceNameSchema
42381
+ }).strict()
42382
+ ]
42383
+ );
42384
+ var HostedRuntimeEnvironmentSourceSchema = external_exports.discriminatedUnion(
42385
+ "kind",
42386
+ [
42387
+ external_exports.object({ kind: external_exports.literal("inline") }).strict(),
42388
+ external_exports.object({
42389
+ kind: external_exports.literal("applied"),
42390
+ name: ResourceNameSchema,
42391
+ resourceId: external_exports.string().trim().min(1),
42392
+ generation: external_exports.number().int().positive()
42393
+ }).strict()
42394
+ ]
42395
+ );
42396
+ var HostedRuntimeEnvironmentSnapshotSchema = external_exports.object({
42397
+ source: HostedRuntimeEnvironmentSourceSchema,
42398
+ spec: EnvironmentSpecSchema
42399
+ }).strict();
42400
+ var HostedRuntimeCommandInputSchema = external_exports.object({
42401
+ command: external_exports.string().trim().min(1).max(4096),
42402
+ timeoutSeconds: external_exports.number().int().min(1).max(300).default(60)
42403
+ }).strict();
42404
+ var HostedRuntimeIdempotencyKeySchema = external_exports.string().trim().min(1).max(200);
42405
+ var CreateHostedRuntimeRequestSchema = external_exports.object({
42406
+ environment: HostedRuntimeEnvironmentInputSchema,
42407
+ commands: external_exports.array(HostedRuntimeCommandInputSchema).min(1).max(20)
42408
+ }).strict().superRefine((request, context) => {
42409
+ const totalTimeoutSeconds = request.commands.reduce(
42410
+ (total, command) => total + command.timeoutSeconds,
42411
+ 0
42412
+ );
42413
+ if (totalTimeoutSeconds > HOSTED_RUNTIME_MAX_COMMAND_BUDGET_SECONDS) {
42414
+ context.addIssue({
42415
+ code: "custom",
42416
+ message: `Total command timeout must not exceed ${HOSTED_RUNTIME_MAX_COMMAND_BUDGET_SECONDS} seconds`,
42417
+ path: ["commands"]
42418
+ });
42419
+ }
42420
+ });
42421
+ var HostedRuntimeStatusSchema = external_exports.enum(HOSTED_RUNTIME_STATUSES);
42422
+ var HostedRuntimeOutcomeSchema = external_exports.enum(HOSTED_RUNTIME_OUTCOMES);
42423
+ var HostedRuntimeCommandStatusSchema = external_exports.enum(
42424
+ HOSTED_RUNTIME_COMMAND_STATUSES
42425
+ );
42426
+ var HostedRuntimeCloseReasonSchema = external_exports.enum(
42427
+ HOSTED_RUNTIME_CLOSE_REASONS
42428
+ );
42429
+ var HostedRuntimeCommandRecordSchema = external_exports.object({
42430
+ ordinal: external_exports.number().int().positive(),
42431
+ command: external_exports.string(),
42432
+ timeoutSeconds: external_exports.number().int().positive(),
42433
+ status: HostedRuntimeCommandStatusSchema,
42434
+ startedAt: external_exports.string().datetime().nullable(),
42435
+ finishedAt: external_exports.string().datetime().nullable(),
42436
+ durationMs: external_exports.number().int().nonnegative().nullable(),
42437
+ exitCode: external_exports.number().int().nullable(),
42438
+ stdout: external_exports.string().nullable(),
42439
+ stderr: external_exports.string().nullable(),
42440
+ error: external_exports.string().nullable()
42441
+ }).strict();
42442
+ var HostedRuntimeRecordSchema = external_exports.object({
42443
+ id: RuntimeIdSchema2,
42444
+ status: HostedRuntimeStatusSchema,
42445
+ outcome: HostedRuntimeOutcomeSchema.nullable(),
42446
+ environment: HostedRuntimeEnvironmentSourceSchema,
42447
+ commands: external_exports.array(HostedRuntimeCommandRecordSchema),
42448
+ error: external_exports.string().nullable(),
42449
+ closeReason: HostedRuntimeCloseReasonSchema.nullable(),
42450
+ closeRequestedAt: external_exports.string().datetime().nullable(),
42451
+ startedAt: external_exports.string().datetime().nullable(),
42452
+ finishedAt: external_exports.string().datetime().nullable(),
42453
+ createdAt: external_exports.string().datetime(),
42454
+ updatedAt: external_exports.string().datetime()
42455
+ }).strict();
42456
+ var HostedRuntimeDispatchStatusSchema = external_exports.enum([
42457
+ "started",
42458
+ "deferred"
42459
+ ]);
42460
+ var HostedRuntimeReceiptSchema = external_exports.object({
42461
+ runtime: HostedRuntimeRecordSchema,
42462
+ workflowId: external_exports.string().trim().min(1),
42463
+ dispatchStatus: HostedRuntimeDispatchStatusSchema
42464
+ }).strict();
42465
+ var HostedRuntimeWorkflowInputSchema = external_exports.object({ runtimeId: RuntimeIdSchema2 }).strip();
42466
+
42200
42467
  // ../../packages/schemas/src/session-bindings.ts
42201
42468
  var BINDING_TARGET_TYPES = [
42202
42469
  "github.pull_request",
@@ -43980,145 +44247,6 @@ var IdentitySpecSchema = AgentIdentitySchema;
43980
44247
  var IdentityResourceSchema = resourceEnvelopeSchema(IdentitySpecSchema);
43981
44248
  var IdentityApplyRequestSchema = resourceApplySchema(IdentitySpecSchema);
43982
44249
 
43983
- // ../../packages/schemas/src/environments.ts
43984
- var RESOURCE_KIND_ENVIRONMENT = "environment";
43985
- var CURRENT_SANDBOX_USER_HOME = "/home/user";
43986
- var LEGACY_SANDBOX_USER_HOMES = ["/home/auto", "/home/node"];
43987
- var STORED_SANDBOX_USER_HOMES = [
43988
- CURRENT_SANDBOX_USER_HOME,
43989
- ...LEGACY_SANDBOX_USER_HOMES
43990
- ];
43991
- var EnvironmentSetupCachePathSchema = external_exports.string().trim().refine((value2) => isSafeSandboxUserHomePath(value2), {
43992
- message: `Expected an absolute path under ${CURRENT_SANDBOX_USER_HOME}`
43993
- });
43994
- var StoredEnvironmentSetupCachePathSchema = external_exports.string().trim().refine(
43995
- (value2) => isSafeSandboxUserHomePath(value2, {
43996
- allowedHomes: STORED_SANDBOX_USER_HOMES
43997
- }),
43998
- {
43999
- message: `Expected an absolute path under ${CURRENT_SANDBOX_USER_HOME}`
44000
- }
44001
- );
44002
- var EnvironmentImageSchema = external_exports.discriminatedUnion("kind", [
44003
- external_exports.object({
44004
- kind: external_exports.literal("preset"),
44005
- name: ResourceNameSchema
44006
- }).strict(),
44007
- external_exports.object({
44008
- kind: external_exports.literal("base"),
44009
- ref: external_exports.string().trim().min(1).max(512).refine(isSafeBaseImageRef, {
44010
- message: "Expected a single Docker/OCI image reference"
44011
- })
44012
- }).strict()
44013
- ]);
44014
- var StoredEnvironmentImageSchema = external_exports.discriminatedUnion("kind", [
44015
- external_exports.object({
44016
- kind: external_exports.literal("preset"),
44017
- name: external_exports.string().trim().min(1)
44018
- }).strict(),
44019
- external_exports.object({
44020
- kind: external_exports.literal("base"),
44021
- ref: external_exports.string().trim().min(1).refine(isSafeBaseImageRef, {
44022
- message: "Expected a single Docker/OCI image reference"
44023
- })
44024
- }).strict()
44025
- ]);
44026
- var ENVIRONMENT_APPROVALS_MODES = ["bypass", "prompt"];
44027
- var EnvironmentApprovalsSchema = external_exports.enum(ENVIRONMENT_APPROVALS_MODES);
44028
- var EnvironmentSetupSchema = environmentSetupSchema(
44029
- StoredEnvironmentSetupCachePathSchema
44030
- );
44031
- var EnvironmentApplySetupSchema = environmentSetupSchema(
44032
- EnvironmentSetupCachePathSchema
44033
- );
44034
- var EnvironmentSetupCacheSchema = external_exports.object({
44035
- ttl: external_exports.string().trim().refine(isSetupCacheTtl, {
44036
- message: "Expected a positive setup cache TTL such as 30m, 24h, or 7d"
44037
- })
44038
- }).strict();
44039
- var EnvironmentResourcesSchema = external_exports.object({
44040
- cpuCount: external_exports.number().int().min(1).optional(),
44041
- memoryMB: external_exports.number().int().min(128).optional()
44042
- }).strict().refine(
44043
- (resources) => resources.cpuCount !== void 0 || resources.memoryMB !== void 0,
44044
- {
44045
- message: "Expected at least one runtime resource setting"
44046
- }
44047
- );
44048
- var EnvironmentSpecSchema = environmentSpecSchema({
44049
- imageSchema: StoredEnvironmentImageSchema,
44050
- setupSchema: EnvironmentSetupSchema
44051
- });
44052
- var EnvironmentApplySpecSchema = environmentSpecSchema({
44053
- imageSchema: EnvironmentImageSchema,
44054
- setupSchema: EnvironmentApplySetupSchema
44055
- });
44056
- var EnvironmentResourceSchema = resourceEnvelopeSchema(
44057
- EnvironmentSpecSchema
44058
- );
44059
- var EnvironmentApplyRequestSchema = resourceApplySchema(
44060
- EnvironmentApplySpecSchema
44061
- );
44062
- function environmentSetupSchema(cachePathSchema) {
44063
- return external_exports.object({
44064
- name: ResourceNameSchema,
44065
- commands: external_exports.array(external_exports.string().trim().min(1)).min(1),
44066
- cache: external_exports.object({
44067
- key: ResourceNameSchema.optional(),
44068
- files: external_exports.array(
44069
- external_exports.string().trim().refine(isSafeRelativePath, {
44070
- message: "Expected a relative path without traversal"
44071
- })
44072
- ).default([]),
44073
- paths: external_exports.array(cachePathSchema).default([])
44074
- }).strict().default({ files: [], paths: [] })
44075
- }).strict();
44076
- }
44077
- function environmentSpecSchema({
44078
- imageSchema,
44079
- setupSchema
44080
- }) {
44081
- return external_exports.object({
44082
- image: imageSchema,
44083
- env: SecretEnvSchema.default({}),
44084
- resources: EnvironmentResourcesSchema.optional(),
44085
- steps: external_exports.array(external_exports.string()).default([]),
44086
- setup: external_exports.array(setupSchema).default([]),
44087
- setupCache: EnvironmentSetupCacheSchema.optional(),
44088
- // Optional rather than defaulted: a default would materialize the key
44089
- // into stored specs and session environment snapshots the moment the web
44090
- // app deploys, and this strict schema on a not-yet-deployed worker would
44091
- // reject those rows (web and workers do not deploy atomically). Absent
44092
- // means `bypass`; consumers default at the read boundary.
44093
- approvals: EnvironmentApprovalsSchema.optional()
44094
- }).strict();
44095
- }
44096
- function isSafeSandboxUserHomePath(value2, options = {}) {
44097
- return (options.allowedHomes ?? [CURRENT_SANDBOX_USER_HOME]).some(
44098
- (home) => isSafePathUnderHome(value2, home)
44099
- );
44100
- }
44101
- function isSafePathUnderHome(value2, home) {
44102
- const prefix = `${home}/`;
44103
- if (!value2.startsWith(prefix)) {
44104
- return false;
44105
- }
44106
- const relative2 = value2.slice(prefix.length);
44107
- return relative2.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..");
44108
- }
44109
- function isSafeRelativePath(value2) {
44110
- if (!value2 || value2.startsWith("/")) {
44111
- return false;
44112
- }
44113
- return value2.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..");
44114
- }
44115
- function isSafeBaseImageRef(value2) {
44116
- return !value2.startsWith("-") && /^[^\s#\\]+$/.test(value2);
44117
- }
44118
- function isSetupCacheTtl(value2) {
44119
- return /^[1-9][0-9]*(s|m|h|d)$/.test(value2);
44120
- }
44121
-
44122
44250
  // ../../packages/schemas/src/environment-setup-failures.ts
44123
44251
  var EnvironmentSetupStepFailureDiagnosticSchema = external_exports.object({
44124
44252
  kind: external_exports.literal("environment_setup_step_failure"),
@@ -83225,9 +83353,170 @@ var defaultDownload2 = createDownload();
83225
83353
 
83226
83354
  // src/commands/agent-bridge/harness/envelope-bounds.ts
83227
83355
  import { Buffer as Buffer2 } from "buffer";
83356
+
83357
+ // src/commands/agent-bridge/harness/mcp-result-canonicalization.ts
83358
+ function canonicalizeEnvelopeMcpResults(envelope) {
83359
+ switch (envelope.type) {
83360
+ case "conversation.entry": {
83361
+ const content = canonicalizeMcpResultValue(envelope.content);
83362
+ return toCanonicalizedEnvelope(
83363
+ envelope,
83364
+ { ...envelope, content: content.value },
83365
+ content.deduplicatedBranches
83366
+ );
83367
+ }
83368
+ case "conversation.delta": {
83369
+ const delta = canonicalizeMcpResultValue(envelope.delta);
83370
+ return toCanonicalizedEnvelope(
83371
+ envelope,
83372
+ { ...envelope, delta: delta.value },
83373
+ delta.deduplicatedBranches
83374
+ );
83375
+ }
83376
+ case "ui.message.chunk": {
83377
+ const chunk = canonicalizeMcpResultValue(envelope.chunk);
83378
+ return toCanonicalizedEnvelope(
83379
+ envelope,
83380
+ { ...envelope, chunk: chunk.value },
83381
+ chunk.deduplicatedBranches
83382
+ );
83383
+ }
83384
+ case "ui.message.part": {
83385
+ const part = canonicalizeMcpResultValue(envelope.part);
83386
+ const metadata = canonicalizeMcpResultValue(envelope.messageMetadata);
83387
+ const deduplicatedBranches = part.deduplicatedBranches + metadata.deduplicatedBranches;
83388
+ return toCanonicalizedEnvelope(
83389
+ envelope,
83390
+ {
83391
+ ...envelope,
83392
+ part: part.value,
83393
+ ...envelope.messageMetadata === void 0 ? {} : { messageMetadata: metadata.value }
83394
+ },
83395
+ deduplicatedBranches
83396
+ );
83397
+ }
83398
+ case "ui.message.completed": {
83399
+ const message = canonicalizeMcpResultValue(envelope.message);
83400
+ return toCanonicalizedEnvelope(
83401
+ envelope,
83402
+ { ...envelope, message: message.value },
83403
+ message.deduplicatedBranches
83404
+ );
83405
+ }
83406
+ case "runtime.liveness":
83407
+ case "runtime.usage_turn":
83408
+ return { value: envelope, deduplicatedBranches: 0 };
83409
+ }
83410
+ }
83411
+ function toCanonicalizedEnvelope(original, candidate, deduplicatedBranches) {
83412
+ return {
83413
+ value: deduplicatedBranches > 0 ? RuntimeBridgeOutputEnvelopeSchema.parse(candidate) : original,
83414
+ deduplicatedBranches
83415
+ };
83416
+ }
83417
+ function canonicalizeMcpResultValue(value2) {
83418
+ if (Array.isArray(value2)) {
83419
+ let deduplicatedBranches2 = 0;
83420
+ let changed2 = false;
83421
+ const items = value2.map((item) => {
83422
+ const canonical2 = canonicalizeMcpResultValue(item);
83423
+ deduplicatedBranches2 += canonical2.deduplicatedBranches;
83424
+ changed2 ||= canonical2.value !== item;
83425
+ return canonical2.value;
83426
+ });
83427
+ return {
83428
+ value: changed2 ? items : value2,
83429
+ deduplicatedBranches: deduplicatedBranches2
83430
+ };
83431
+ }
83432
+ if (typeof value2 !== "object" || value2 === null) {
83433
+ return { value: value2, deduplicatedBranches: 0 };
83434
+ }
83435
+ const record2 = value2;
83436
+ const duplicateContentIndexes = equivalentMcpTextContentIndexes(record2);
83437
+ let deduplicatedBranches = duplicateContentIndexes.size;
83438
+ let changed = duplicateContentIndexes.size > 0;
83439
+ const canonical = /* @__PURE__ */ Object.create(null);
83440
+ for (const [key, item] of Object.entries(record2)) {
83441
+ if (key === "content" && Array.isArray(item)) {
83442
+ const retainedContent = duplicateContentIndexes.size > 0 ? item.filter(
83443
+ (_contentItem, index) => !duplicateContentIndexes.has(index)
83444
+ ) : item;
83445
+ if (retainedContent.length === 0 && duplicateContentIndexes.size > 0) {
83446
+ continue;
83447
+ }
83448
+ const content = canonicalizeMcpResultValue(retainedContent);
83449
+ canonical[key] = content.value;
83450
+ deduplicatedBranches += content.deduplicatedBranches;
83451
+ changed ||= content.value !== item;
83452
+ continue;
83453
+ }
83454
+ const child = canonicalizeMcpResultValue(item);
83455
+ canonical[key] = child.value;
83456
+ deduplicatedBranches += child.deduplicatedBranches;
83457
+ changed ||= child.value !== item;
83458
+ }
83459
+ return {
83460
+ value: changed ? canonical : value2,
83461
+ deduplicatedBranches
83462
+ };
83463
+ }
83464
+ function equivalentMcpTextContentIndexes(value2) {
83465
+ if (!Array.isArray(value2.content) || !Object.hasOwn(value2, "structuredContent") || value2.structuredContent === void 0) {
83466
+ return /* @__PURE__ */ new Set();
83467
+ }
83468
+ const indexes = /* @__PURE__ */ new Set();
83469
+ for (const [index, item] of value2.content.entries()) {
83470
+ if (!isPlainMcpTextBlock(item)) {
83471
+ continue;
83472
+ }
83473
+ const parsed = parseJson(item.text);
83474
+ if (parsed.parsed && jsonValuesEqual(parsed.value, value2.structuredContent)) {
83475
+ indexes.add(index);
83476
+ }
83477
+ }
83478
+ return indexes;
83479
+ }
83480
+ function isPlainMcpTextBlock(value2) {
83481
+ if (typeof value2 !== "object" || value2 === null || Array.isArray(value2)) {
83482
+ return false;
83483
+ }
83484
+ const record2 = value2;
83485
+ const keys = Object.keys(record2);
83486
+ return keys.length === 2 && record2.type === "text" && typeof record2.text === "string";
83487
+ }
83488
+ function parseJson(value2) {
83489
+ try {
83490
+ return { parsed: true, value: JSON.parse(value2) };
83491
+ } catch {
83492
+ return { parsed: false, value: null };
83493
+ }
83494
+ }
83495
+ function jsonValuesEqual(left, right) {
83496
+ if (Object.is(left, right)) {
83497
+ return true;
83498
+ }
83499
+ if (Array.isArray(left) || Array.isArray(right)) {
83500
+ if (!Array.isArray(left) || !Array.isArray(right)) {
83501
+ return false;
83502
+ }
83503
+ return left.length === right.length && left.every((item, index) => jsonValuesEqual(item, right[index]));
83504
+ }
83505
+ if (typeof left !== "object" || left === null || typeof right !== "object" || right === null) {
83506
+ return false;
83507
+ }
83508
+ const leftRecord = left;
83509
+ const rightRecord = right;
83510
+ const leftKeys = Object.keys(leftRecord);
83511
+ const rightKeys = Object.keys(rightRecord);
83512
+ return leftKeys.length === rightKeys.length && leftKeys.every(
83513
+ (key) => Object.hasOwn(rightRecord, key) && jsonValuesEqual(leftRecord[key], rightRecord[key])
83514
+ );
83515
+ }
83516
+
83517
+ // src/commands/agent-bridge/harness/envelope-bounds.ts
83228
83518
  var AGENT_BRIDGE_OUTPUT_MAX_ENVELOPE_BYTES = 512 * 1024;
83229
83519
  var AGENT_BRIDGE_OUTPUT_QUARANTINE_MAX_ENVELOPE_BYTES = 8 * 1024;
83230
- var MAX_TARGETED_PAYLOAD_NOTICES = 4;
83231
83520
  var PAYLOAD_FIELD_RULES = {
83232
83521
  output: { label: "tool output", priority: 0 },
83233
83522
  errorText: { label: "tool error", priority: 0 },
@@ -83262,48 +83551,97 @@ var STRUCTURAL_STRING_FIELDS = /* @__PURE__ */ new Set([
83262
83551
  "completedAt"
83263
83552
  ]);
83264
83553
  function boundOutputEnvelope(envelope, maxBytes = AGENT_BRIDGE_OUTPUT_MAX_ENVELOPE_BYTES) {
83265
- const originalBytes = serializedByteLength(envelope);
83554
+ const original = envelopeSerializationInfo(envelope);
83555
+ const originalBytes = original.bytes;
83266
83556
  if (originalBytes <= maxBytes) {
83267
- return { envelope, originalBytes, truncated: false };
83557
+ return {
83558
+ envelope,
83559
+ originalBytes,
83560
+ boundedBytes: originalBytes,
83561
+ kind: "none",
83562
+ deduplicatedMcpResultBranches: 0,
83563
+ truncated: false
83564
+ };
83268
83565
  }
83269
- const targeted = truncatePayloads(envelope, maxBytes);
83566
+ const canonicalized = original.hasStructuredContent ? canonicalizeEnvelopeMcpResults(envelope) : { value: envelope, deduplicatedBranches: 0 };
83567
+ const canonicalEnvelope = canonicalized.value;
83568
+ const canonicalBytes = serializedByteLength(canonicalEnvelope);
83569
+ if (canonicalBytes <= maxBytes) {
83570
+ return {
83571
+ envelope: canonicalEnvelope,
83572
+ originalBytes,
83573
+ boundedBytes: canonicalBytes,
83574
+ kind: "mcp-result-deduplicated",
83575
+ deduplicatedMcpResultBranches: canonicalized.deduplicatedBranches,
83576
+ truncated: true
83577
+ };
83578
+ }
83579
+ const targeted = truncatePayloads(canonicalEnvelope, maxBytes);
83270
83580
  if (targeted) {
83581
+ const boundedEnvelope = RuntimeBridgeOutputEnvelopeSchema.parse(targeted);
83271
83582
  return {
83272
- envelope: RuntimeBridgeOutputEnvelopeSchema.parse(targeted),
83583
+ envelope: boundedEnvelope,
83273
83584
  originalBytes,
83585
+ boundedBytes: serializedByteLength(boundedEnvelope),
83586
+ kind: canonicalized.deduplicatedBranches > 0 ? "mcp-result-deduplicated+targeted-truncation" : "targeted-truncation",
83587
+ deduplicatedMcpResultBranches: canonicalized.deduplicatedBranches,
83274
83588
  truncated: true
83275
83589
  };
83276
83590
  }
83591
+ const fallbackEnvelope = RuntimeBridgeOutputEnvelopeSchema.parse(
83592
+ replacePayloadWithMarker(canonicalEnvelope)
83593
+ );
83277
83594
  return {
83278
- envelope: RuntimeBridgeOutputEnvelopeSchema.parse(
83279
- replacePayloadWithMarker(envelope)
83280
- ),
83595
+ envelope: fallbackEnvelope,
83281
83596
  originalBytes,
83597
+ boundedBytes: serializedByteLength(fallbackEnvelope),
83598
+ kind: canonicalized.deduplicatedBranches > 0 ? "mcp-result-deduplicated+payload-fallback" : "payload-fallback",
83599
+ deduplicatedMcpResultBranches: canonicalized.deduplicatedBranches,
83282
83600
  truncated: true
83283
83601
  };
83284
83602
  }
83285
83603
  function truncatePayloads(envelope, maxBytes) {
83286
83604
  const candidateEnvelope = structuredClone(envelope);
83287
83605
  const candidates = collectPayloadCandidates(envelope);
83288
- for (let noticeCount = 0; noticeCount < MAX_TARGETED_PAYLOAD_NOTICES; noticeCount += 1) {
83606
+ const truncatedCandidates = [];
83607
+ while (true) {
83289
83608
  const currentBytes = serializedByteLength(candidateEnvelope);
83290
83609
  if (currentBytes <= maxBytes) {
83291
83610
  return candidateEnvelope;
83292
83611
  }
83293
83612
  const candidate = takePayloadCandidate(candidates, currentBytes - maxBytes);
83294
83613
  if (!candidate) {
83295
- return null;
83614
+ break;
83296
83615
  }
83297
83616
  setValueAtPath(
83298
83617
  candidateEnvelope,
83299
83618
  candidate.path,
83300
83619
  truncationNotice(candidate, "")
83301
83620
  );
83302
- if (serializedByteLength(candidateEnvelope) <= maxBytes) {
83621
+ const truncatedBytes = serializedByteLength(candidateEnvelope);
83622
+ if (truncatedBytes >= currentBytes) {
83623
+ setValueAtPath(candidateEnvelope, candidate.path, candidate.value);
83624
+ continue;
83625
+ }
83626
+ truncatedCandidates.push(candidate);
83627
+ if (truncatedBytes <= maxBytes) {
83303
83628
  maximizePreview(candidateEnvelope, candidate, maxBytes);
83304
83629
  return candidateEnvelope;
83305
83630
  }
83306
83631
  }
83632
+ for (const candidate of truncatedCandidates) {
83633
+ setValueAtPath(
83634
+ candidateEnvelope,
83635
+ candidate.path,
83636
+ compactTruncationNotice(candidate)
83637
+ );
83638
+ }
83639
+ if (serializedByteLength(candidateEnvelope) <= maxBytes) {
83640
+ return candidateEnvelope;
83641
+ }
83642
+ for (const candidate of truncatedCandidates) {
83643
+ setValueAtPath(candidateEnvelope, candidate.path, "");
83644
+ }
83307
83645
  return serializedByteLength(candidateEnvelope) <= maxBytes ? candidateEnvelope : null;
83308
83646
  }
83309
83647
  function collectPayloadCandidates(envelope) {
@@ -83468,10 +83806,20 @@ function truncationNotice(candidate, preview) {
83468
83806
  const separator = preview.length > 0 ? "\n" : "";
83469
83807
  return `${preview}${separator}[agent-bridge ${candidate.label} truncated: original ${candidate.originalBytes} UTF-8 bytes; kept ${keptBytes}; omitted ${omittedBytes}. Omitted content was not persisted in this transcript.]`;
83470
83808
  }
83809
+ function compactTruncationNotice(candidate) {
83810
+ return `[agent-bridge ${candidate.label} truncated: original ${candidate.originalBytes} UTF-8 bytes.]`;
83811
+ }
83471
83812
  function serializedByteLength(value2) {
83472
83813
  const serialized = JSON.stringify(value2);
83473
83814
  return serialized === void 0 ? 0 : Buffer2.byteLength(serialized, "utf8");
83474
83815
  }
83816
+ function envelopeSerializationInfo(envelope) {
83817
+ const serialized = JSON.stringify(envelope);
83818
+ return {
83819
+ bytes: Buffer2.byteLength(serialized, "utf8"),
83820
+ hasStructuredContent: serialized.includes('"structuredContent":')
83821
+ };
83822
+ }
83475
83823
  function replacePayloadWithMarker(envelope) {
83476
83824
  switch (envelope.type) {
83477
83825
  case "conversation.entry": {
@@ -84432,6 +84780,9 @@ var AgentBridgeOutputBuffer = class {
84432
84780
  "agent_bridge_output_envelope_truncated",
84433
84781
  this.outputLogContext(bounded.envelope, {
84434
84782
  original_bytes: bounded.originalBytes,
84783
+ bounded_bytes: bounded.boundedBytes,
84784
+ bound_kind: bounded.kind,
84785
+ deduplicated_mcp_result_branches: bounded.deduplicatedMcpResultBranches,
84435
84786
  pending_count: this.pendingOutputs.size
84436
84787
  })
84437
84788
  );
@@ -84465,6 +84816,9 @@ var AgentBridgeOutputBuffer = class {
84465
84816
  this.outputLogContext(bounded.envelope, {
84466
84817
  exhausts,
84467
84818
  original_bytes: bounded.originalBytes,
84819
+ bounded_bytes: bounded.boundedBytes,
84820
+ bound_kind: bounded.kind,
84821
+ deduplicated_mcp_result_branches: bounded.deduplicatedMcpResultBranches,
84468
84822
  truncated: bounded.truncated,
84469
84823
  pending_count: this.pendingOutputs.size
84470
84824
  })