deepline 0.3.63 → 0.3.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -585,6 +585,8 @@ var ConfigError = class extends DeeplineError {
585
585
  // src/config.ts
586
586
  var HOST_URL_ENV = "DEEPLINE_HOST_URL";
587
587
  var API_KEY_ENV = "DEEPLINE_API_KEY";
588
+ var ACTIVE_ORG_ID_ENV = "DEEPLINE_ACTIVE_ORG_ID";
589
+ var ACTIVE_ORG_NAME_ENV = "DEEPLINE_ACTIVE_ORG_NAME";
588
590
  var PROD_URL = "https://code.deepline.com";
589
591
  var DEFAULT_TIMEOUT = 6e4;
590
592
  var DEFAULT_MAX_RETRIES = 3;
@@ -605,6 +607,12 @@ var COWORK_PROJECT_MARKERS = [
605
607
  "package.json",
606
608
  "pyproject.toml"
607
609
  ];
610
+ var CLI_ENV_ALLOWED_KEYS = /* @__PURE__ */ new Set([
611
+ HOST_URL_ENV,
612
+ API_KEY_ENV,
613
+ ACTIVE_ORG_ID_ENV,
614
+ ACTIVE_ORG_NAME_ENV
615
+ ]);
608
616
  function baseUrlSlug(baseUrl) {
609
617
  let url;
610
618
  try {
@@ -631,7 +639,13 @@ function parseEnvFile(filePath) {
631
639
  if (eqIndex < 0) continue;
632
640
  const key = trimmed.slice(0, eqIndex).trim();
633
641
  let value = trimmed.slice(eqIndex + 1).trim();
634
- if (value.length >= 2 && (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'"))) {
642
+ if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
643
+ try {
644
+ value = JSON.parse(value);
645
+ } catch {
646
+ value = value.slice(1, -1);
647
+ }
648
+ } else if (value.length >= 2 && value.startsWith("'") && value.endsWith("'")) {
635
649
  value = value.slice(1, -1);
636
650
  }
637
651
  if (key && value) {
@@ -789,6 +803,23 @@ function firstNonEmpty(...values) {
789
803
  }
790
804
  return "";
791
805
  }
806
+ function formatEnvFileValue(value) {
807
+ return /^[a-zA-Z0-9_./:@%+=,-]+$/.test(value) ? value : JSON.stringify(value);
808
+ }
809
+ function mergePersistedEnvValues(existing, values) {
810
+ const merged = { ...existing, ...values };
811
+ const nextApiKey = values[API_KEY_ENV];
812
+ if (nextApiKey !== void 0 && nextApiKey !== existing[API_KEY_ENV] && values[ACTIVE_ORG_ID_ENV] === void 0) {
813
+ delete merged[ACTIVE_ORG_ID_ENV];
814
+ delete merged[ACTIVE_ORG_NAME_ENV];
815
+ }
816
+ return merged;
817
+ }
818
+ function persistedEnvLines(values) {
819
+ return Object.entries(values).filter(
820
+ ([key, value]) => CLI_ENV_ALLOWED_KEYS.has(key) && value.trim() !== ""
821
+ ).map(([key, value]) => `${key}=${formatEnvFileValue(value)}`);
822
+ }
792
823
  function sdkCliConfigDir(baseUrl) {
793
824
  const home = process.env.HOME?.trim() || (0, import_node_os.homedir)();
794
825
  return (0, import_node_path.join)(home, ".local", "deepline", baseUrlSlug(baseUrl || PROD_URL));
@@ -821,9 +852,8 @@ function saveHostEnvValues(baseUrl, values) {
821
852
  (0, import_node_fs.mkdirSync)(dir, { recursive: true });
822
853
  }
823
854
  const existing = parseEnvFile(filePath);
824
- const merged = { ...existing, ...values };
825
- const allowedKeys = /* @__PURE__ */ new Set([HOST_URL_ENV, API_KEY_ENV]);
826
- const lines = Object.entries(merged).filter(([key, value]) => allowedKeys.has(key) && value !== "").map(([key, value]) => `${key}=${value}`);
855
+ const merged = mergePersistedEnvValues(existing, values);
856
+ const lines = persistedEnvLines(merged);
827
857
  (0, import_node_fs.writeFileSync)(filePath, `${lines.join("\n")}
828
858
  `, "utf-8");
829
859
  }
@@ -899,12 +929,11 @@ function resolveConfig(options) {
899
929
  }
900
930
  function mergeProjectEnvFile(filePath, values) {
901
931
  const existing = parseEnvFile(filePath);
902
- const merged = { ...existing, ...values };
932
+ const merged = mergePersistedEnvValues(existing, values);
903
933
  const dir = (0, import_node_path.dirname)(filePath);
904
934
  if (!(0, import_node_fs.existsSync)(dir)) (0, import_node_fs.mkdirSync)(dir, { recursive: true });
905
935
  ensureProjectEnvIsIgnored(dir);
906
- const allowedKeys = /* @__PURE__ */ new Set([HOST_URL_ENV, API_KEY_ENV]);
907
- const lines = Object.entries(merged).filter(([key, value]) => allowedKeys.has(key) && value !== "").map(([key, value]) => `${key}=${value}`);
936
+ const lines = persistedEnvLines(merged);
908
937
  (0, import_node_fs.writeFileSync)(filePath, `${lines.join("\n")}
909
938
  `, "utf-8");
910
939
  }
@@ -1070,6 +1099,71 @@ function resolveCliAuthProvenance(config, startDir = process.cwd()) {
1070
1099
  folderAuthPath: folderAuth?.filePath ?? null
1071
1100
  };
1072
1101
  }
1102
+ function activeOrganizationFromEnv(env) {
1103
+ const orgId = env[ACTIVE_ORG_ID_ENV]?.trim();
1104
+ if (!orgId) return null;
1105
+ const orgName = env[ACTIVE_ORG_NAME_ENV]?.trim() || null;
1106
+ return { org_id: orgId, org_name: orgName };
1107
+ }
1108
+ function resolveCliCommandContext(inputConfig, requestedScope) {
1109
+ let config = inputConfig;
1110
+ if (!config) {
1111
+ try {
1112
+ config = resolveConfig();
1113
+ } catch {
1114
+ return {
1115
+ active_organization: null,
1116
+ auth_scope: null,
1117
+ metadata_source: null
1118
+ };
1119
+ }
1120
+ }
1121
+ const contextForScope = (scope) => {
1122
+ if (scope === "env") {
1123
+ const processApiKey = process.env[API_KEY_ENV]?.trim();
1124
+ return processApiKey && processApiKey === config.apiKey ? {
1125
+ active_organization: activeOrganizationFromEnv(process.env),
1126
+ auth_scope: "env",
1127
+ metadata_source: "process_env"
1128
+ } : null;
1129
+ }
1130
+ if (scope === "folder") {
1131
+ const projectAuth = getResolvedProjectAuthSource(
1132
+ config.baseUrl,
1133
+ config.apiKey
1134
+ );
1135
+ return projectAuth ? {
1136
+ active_organization: activeOrganizationFromEnv(projectAuth.env),
1137
+ auth_scope: "folder",
1138
+ metadata_source: "folder_env"
1139
+ } : null;
1140
+ }
1141
+ const hostEnv = loadCliEnv(config.baseUrl);
1142
+ return (hostEnv[API_KEY_ENV] ?? "").trim() === config.apiKey ? {
1143
+ active_organization: activeOrganizationFromEnv(hostEnv),
1144
+ auth_scope: "global",
1145
+ metadata_source: "host_env"
1146
+ } : null;
1147
+ };
1148
+ const processContext = contextForScope("env");
1149
+ if (processContext) return processContext;
1150
+ if (requestedScope) {
1151
+ return contextForScope(requestedScope) ?? {
1152
+ active_organization: null,
1153
+ auth_scope: requestedScope,
1154
+ metadata_source: null
1155
+ };
1156
+ }
1157
+ for (const scope of ["folder", "global"]) {
1158
+ const context = contextForScope(scope);
1159
+ if (context) return context;
1160
+ }
1161
+ return {
1162
+ active_organization: null,
1163
+ auth_scope: null,
1164
+ metadata_source: null
1165
+ };
1166
+ }
1073
1167
 
1074
1168
  // ../plays/artifact-contract-version.ts
1075
1169
  var CURRENT_PLAY_ARTIFACT_CONTRACT_VERSION = 2;
@@ -1120,7 +1214,7 @@ var SDK_RELEASE = {
1120
1214
  // available at toolResponse.rawV2 while toolResponse.raw and all declared
1121
1215
  // getters keep their established compatibility behavior.
1122
1216
  // 0.3.1 deprecated the legacy `deepline enrich` command in favor of Plays.
1123
- version: "0.3.63",
1217
+ version: "0.3.64",
1124
1218
  updateSummary: "Automatic CLI updates are now enabled by default. To opt out, run `deepline settings autoupdate off`; use `deepline settings autoupdate on` to re-enable updates or `deepline settings autoupdate pin <version>` to hold an exact release. This release also adds raw-v2 tool responses at toolResponse.rawV2 while preserving existing toolResponse.raw and declared getters.",
1125
1219
  packageCapabilities: {
1126
1220
  updatePreferences: 1
@@ -7999,8 +8093,21 @@ function markdownTableFromRows(rows, preferredColumns = []) {
7999
8093
  return `${[header, separator, ...body].join("\n")}
8000
8094
  `;
8001
8095
  }
8096
+ function withAgentCommandContext(value) {
8097
+ const valueRecord = value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
8098
+ return detectAgentRuntime() !== "unknown" && valueRecord && !Object.prototype.hasOwnProperty.call(valueRecord, "command_context") ? {
8099
+ ...valueRecord,
8100
+ command_context: resolveCliCommandContext()
8101
+ } : value;
8102
+ }
8002
8103
  function printJson(value) {
8003
- process.stdout.write(`${JSON.stringify(value, null, 2)}
8104
+ process.stdout.write(
8105
+ `${JSON.stringify(withAgentCommandContext(value), null, 2)}
8106
+ `
8107
+ );
8108
+ }
8109
+ function printCompactJson(value) {
8110
+ process.stdout.write(`${JSON.stringify(withAgentCommandContext(value))}
8004
8111
  `);
8005
8112
  }
8006
8113
  function errorToJsonPayload(error) {
@@ -8224,7 +8331,9 @@ function shouldWaitForRegisterClaim(mode) {
8224
8331
  function saveEnvValues(values, baseUrl, scope) {
8225
8332
  const filtered = {
8226
8333
  ...values[HOST_URL_ENV] ? { [HOST_URL_ENV]: values[HOST_URL_ENV] } : {},
8227
- ...values[API_KEY_ENV] ? { [API_KEY_ENV]: values[API_KEY_ENV] } : {}
8334
+ ...values[API_KEY_ENV] ? { [API_KEY_ENV]: values[API_KEY_ENV] } : {},
8335
+ ...values[ACTIVE_ORG_ID_ENV] ? { [ACTIVE_ORG_ID_ENV]: values[ACTIVE_ORG_ID_ENV] } : {},
8336
+ ...Object.prototype.hasOwnProperty.call(values, ACTIVE_ORG_NAME_ENV) ? { [ACTIVE_ORG_NAME_ENV]: values[ACTIVE_ORG_NAME_ENV] } : {}
8228
8337
  };
8229
8338
  if (scope === "folder") {
8230
8339
  saveProjectDeeplineEnvValues(filtered);
@@ -8232,6 +8341,15 @@ function saveEnvValues(values, baseUrl, scope) {
8232
8341
  saveHostEnvValues(baseUrl, filtered);
8233
8342
  }
8234
8343
  }
8344
+ function activeOrgEnvValues(data) {
8345
+ const orgId = typeof data.org_id === "string" ? data.org_id.trim() : "";
8346
+ if (!orgId) return {};
8347
+ const orgName = typeof data.org_name === "string" ? data.org_name.trim() : "";
8348
+ return {
8349
+ [ACTIVE_ORG_ID_ENV]: orgId,
8350
+ [ACTIVE_ORG_NAME_ENV]: orgName
8351
+ };
8352
+ }
8235
8353
  async function httpJson(method, url, apiKey, body) {
8236
8354
  const headers = {
8237
8355
  "Content-Type": "application/json",
@@ -8467,7 +8585,8 @@ async function handleRegister(args) {
8467
8585
  saveEnvValues(
8468
8586
  {
8469
8587
  [HOST_URL_ENV]: baseUrl,
8470
- [API_KEY_ENV]: apiKey
8588
+ [API_KEY_ENV]: apiKey,
8589
+ ...activeOrgEnvValues(statusData)
8471
8590
  },
8472
8591
  baseUrl,
8473
8592
  authScope
@@ -8548,7 +8667,8 @@ async function handleWait(args) {
8548
8667
  saveEnvValues(
8549
8668
  {
8550
8669
  [HOST_URL_ENV]: baseUrl,
8551
- [API_KEY_ENV]: apiKey
8670
+ [API_KEY_ENV]: apiKey,
8671
+ ...activeOrgEnvValues(data)
8552
8672
  },
8553
8673
  baseUrl,
8554
8674
  authScope
@@ -8731,7 +8851,8 @@ async function handleStatus(args) {
8731
8851
  saveEnvValues(
8732
8852
  {
8733
8853
  [HOST_URL_ENV]: baseUrl,
8734
- [API_KEY_ENV]: apiKeyResp
8854
+ [API_KEY_ENV]: apiKeyResp,
8855
+ ...activeOrgEnvValues(data)
8735
8856
  },
8736
8857
  baseUrl,
8737
8858
  resolvedAuthScope
@@ -8747,6 +8868,12 @@ async function handleStatus(args) {
8747
8868
  printCommandEnvelope(
8748
8869
  {
8749
8870
  ...payload,
8871
+ ...detectAgentRuntime() !== "unknown" ? {
8872
+ command_context: resolveCliCommandContext(
8873
+ { baseUrl, apiKey },
8874
+ resolvedAuthScope
8875
+ )
8876
+ } : {},
8750
8877
  ...savedApiKeyPath ? { saved_api_key_path: savedApiKeyPath } : {},
8751
8878
  render: {
8752
8879
  sections: [
@@ -21633,8 +21760,7 @@ async function handlePlayCheck(args) {
21633
21760
  note: "Named/prebuilt play contract is available. No run was started."
21634
21761
  };
21635
21762
  if (options.jsonOutput) {
21636
- process.stdout.write(`${JSON.stringify(result)}
21637
- `);
21763
+ printCompactJson(result);
21638
21764
  } else {
21639
21765
  console.log(`\u2713 ${result.reference} passed named play contract check`);
21640
21766
  console.log(" no run started; no Deepline credits spent");
@@ -21652,14 +21778,11 @@ async function handlePlayCheck(args) {
21652
21778
  const resolved = (0, import_node_path14.resolve)(options.target);
21653
21779
  const message = error instanceof Error && error.message ? error.message : `File not found: ${resolved}`;
21654
21780
  if (options.jsonOutput) {
21655
- process.stdout.write(
21656
- `${JSON.stringify({
21657
- valid: false,
21658
- target: options.target,
21659
- errors: [message]
21660
- })}
21661
- `
21662
- );
21781
+ printCompactJson({
21782
+ valid: false,
21783
+ target: options.target,
21784
+ errors: [message]
21785
+ });
21663
21786
  } else {
21664
21787
  console.error(message);
21665
21788
  }
@@ -21682,8 +21805,7 @@ async function handlePlayCheck(args) {
21682
21805
  }
21683
21806
  const merged = mergePlayCheckExportOutcomes(outcomes);
21684
21807
  if (options.jsonOutput) {
21685
- process.stdout.write(`${JSON.stringify(merged.json)}
21686
- `);
21808
+ printCompactJson(merged.json);
21687
21809
  } else {
21688
21810
  printPlayCheckOutcomes(outcomes, options.target);
21689
21811
  }
@@ -22894,21 +23016,18 @@ async function handlePlayGet(args) {
22894
23016
  }
22895
23017
  const loadedMessage = materializedFile ? formatLoadedPlayMessage(materializedFile) : null;
22896
23018
  if (jsonOutput) {
22897
- process.stdout.write(
22898
- `${JSON.stringify({
22899
- ...detail,
22900
- ...materializedFile ? {
22901
- message: loadedMessage,
22902
- materializedFile: {
22903
- path: materializedFile.path,
22904
- created: materializedFile.created,
22905
- status: materializedFile.status,
22906
- message: loadedMessage
22907
- }
22908
- } : {}
22909
- })}
22910
- `
22911
- );
23019
+ printCompactJson({
23020
+ ...detail,
23021
+ ...materializedFile ? {
23022
+ message: loadedMessage,
23023
+ materializedFile: {
23024
+ path: materializedFile.path,
23025
+ created: materializedFile.created,
23026
+ status: materializedFile.status,
23027
+ message: loadedMessage
23028
+ }
23029
+ } : {}
23030
+ });
22912
23031
  return 0;
22913
23032
  }
22914
23033
  if (sourceOutput) {
@@ -22993,8 +23112,7 @@ async function handlePlayVersions(args) {
22993
23112
  parseReferencedPlayTarget2(playName).playName
22994
23113
  );
22995
23114
  if (jsonOutput) {
22996
- process.stdout.write(`${JSON.stringify({ versions })}
22997
- `);
23115
+ printCompactJson({ versions });
22998
23116
  return 0;
22999
23117
  }
23000
23118
  if (versions.length === 0) {
@@ -23080,13 +23198,11 @@ async function handlePlayPin(args, pinned) {
23080
23198
  const name = parsedTarget.playName;
23081
23199
  const plan = { name, pinned, dryRun };
23082
23200
  if (dryRun) {
23083
- process.stdout.write(`${JSON.stringify(plan)}
23084
- `);
23201
+ printCompactJson(plan);
23085
23202
  return 0;
23086
23203
  }
23087
23204
  const result = await new DeeplineClient().setPlayPinned(name, pinned);
23088
- if (jsonOutput) process.stdout.write(`${JSON.stringify(result)}
23089
- `);
23205
+ if (jsonOutput) printCompactJson(result);
23090
23206
  else console.log(`${result.pinned ? "Pinned" : "Unpinned"} ${result.name}.`);
23091
23207
  return 0;
23092
23208
  }
@@ -23288,21 +23404,18 @@ async function handlePlaySearch(args) {
23288
23404
  ...play,
23289
23405
  inputSchema: compactPlaySchema(play.inputSchema)
23290
23406
  })) : plays;
23291
- process.stdout.write(
23292
- `${JSON.stringify({
23293
- disclaimer,
23294
- search_policy: {
23295
- default_scope: "prebuilt",
23296
- included_origins: options.scope === "all" ? ["prebuilt", "owned"] : ["prebuilt"],
23297
- owned_plays_omitted: options.scope === "prebuilt",
23298
- include_owned_flag: "--all"
23299
- },
23300
- plays: jsonPlays,
23301
- total: jsonPlays.length,
23302
- truncated: false
23303
- })}
23304
- `
23305
- );
23407
+ printCompactJson({
23408
+ disclaimer,
23409
+ search_policy: {
23410
+ default_scope: "prebuilt",
23411
+ included_origins: options.scope === "all" ? ["prebuilt", "owned"] : ["prebuilt"],
23412
+ owned_plays_omitted: options.scope === "prebuilt",
23413
+ include_owned_flag: "--all"
23414
+ },
23415
+ plays: jsonPlays,
23416
+ total: jsonPlays.length,
23417
+ truncated: false
23418
+ });
23306
23419
  return 0;
23307
23420
  }
23308
23421
  const displayPlays = options.scope === "prebuilt" ? plays.slice(0, 5) : plays;
@@ -23391,15 +23504,12 @@ async function handlePlayGrep(args) {
23391
23504
  )
23392
23505
  ).map((play) => summarizePlayListItemForCli(play, { compact }));
23393
23506
  if (argsWantJson(args)) {
23394
- process.stdout.write(
23395
- `${JSON.stringify({
23396
- plays,
23397
- count: plays.length,
23398
- query,
23399
- grep: { mode, terms: parsePlayGrepTerms(query, mode) }
23400
- })}
23401
- `
23402
- );
23507
+ printCompactJson({
23508
+ plays,
23509
+ count: plays.length,
23510
+ query,
23511
+ grep: { mode, terms: parsePlayGrepTerms(query, mode) }
23512
+ });
23403
23513
  return 0;
23404
23514
  }
23405
23515
  process.stdout.write(`${plays.length} plays found:
@@ -23445,14 +23555,11 @@ async function handlePlayDescribe(args) {
23445
23555
  ...definedName ? [`deepline plays describe <workspace>/${definedName}`] : []
23446
23556
  ];
23447
23557
  if (argsWantJson(args)) {
23448
- process.stdout.write(
23449
- `${JSON.stringify({
23450
- ok: false,
23451
- error: { message },
23452
- next
23453
- })}
23454
- `
23455
- );
23558
+ printCompactJson({
23559
+ ok: false,
23560
+ error: { message },
23561
+ next
23562
+ });
23456
23563
  } else {
23457
23564
  console.error(message);
23458
23565
  console.error(`Try: ${next[0]}`);
@@ -23473,8 +23580,7 @@ async function handlePlayDescribe(args) {
23473
23580
  }
23474
23581
  );
23475
23582
  if (argsWantJson(args)) {
23476
- process.stdout.write(`${JSON.stringify(play)}
23477
- `);
23583
+ printCompactJson(play);
23478
23584
  return 0;
23479
23585
  }
23480
23586
  printPlayDescription(play);
@@ -23518,8 +23624,7 @@ async function handlePlaySave(args) {
23518
23624
  next: `deepline plays check ${shellQuote2(options.target)}`
23519
23625
  };
23520
23626
  if (options.jsonOutput) {
23521
- process.stdout.write(`${JSON.stringify(result)}
23522
- `);
23627
+ printCompactJson(result);
23523
23628
  } else {
23524
23629
  console.error(result.message);
23525
23630
  console.error(` checked artifact: ${result.expectedArtifactHash}`);
@@ -23541,8 +23646,7 @@ async function handlePlaySave(args) {
23541
23646
  };
23542
23647
  if (options.dryRun) {
23543
23648
  if (options.jsonOutput) {
23544
- process.stdout.write(`${JSON.stringify(dryRun)}
23545
- `);
23649
+ printCompactJson(dryRun);
23546
23650
  } else {
23547
23651
  console.log(`Dry run: ${playName}`);
23548
23652
  console.log(` source: ${dryRun.sourceHash}`);
@@ -23587,8 +23691,7 @@ async function handlePlaySave(args) {
23587
23691
  }
23588
23692
  };
23589
23693
  if (options.jsonOutput) {
23590
- process.stdout.write(`${JSON.stringify(result)}
23591
- `);
23694
+ printCompactJson(result);
23592
23695
  } else {
23593
23696
  console.log(
23594
23697
  `\u2713 Saved ${playName} working draft as v${result.version ?? "?"}`
@@ -23646,8 +23749,7 @@ async function handlePlayPublish(args) {
23646
23749
  next: `deepline plays check ${shellQuote2(playName)}`
23647
23750
  };
23648
23751
  if (options.jsonOutput) {
23649
- process.stdout.write(`${JSON.stringify(result3)}
23650
- `);
23752
+ printCompactJson(result3);
23651
23753
  } else {
23652
23754
  console.error(result3.message);
23653
23755
  console.error(` checked artifact: ${result3.expectedArtifactHash}`);
@@ -23670,8 +23772,7 @@ async function handlePlayPublish(args) {
23670
23772
  };
23671
23773
  if (options.dryRun) {
23672
23774
  if (options.jsonOutput) {
23673
- process.stdout.write(`${JSON.stringify(dryRun)}
23674
- `);
23775
+ printCompactJson(dryRun);
23675
23776
  } else {
23676
23777
  console.log(`Dry run: ${rootPlayName}`);
23677
23778
  console.log(` source: ${dryRun.sourceHash}`);
@@ -23739,8 +23840,7 @@ async function handlePlayPublish(args) {
23739
23840
  triggerBindings: published.triggerBindings ?? []
23740
23841
  };
23741
23842
  if (options.jsonOutput) {
23742
- process.stdout.write(`${JSON.stringify(result2)}
23743
- `);
23843
+ printCompactJson(result2);
23744
23844
  } else {
23745
23845
  printPublishReceipt({
23746
23846
  name: rootPlayName,
@@ -23771,8 +23871,7 @@ async function handlePlayPublish(args) {
23771
23871
  revisionId: revisionId ?? null,
23772
23872
  latest: useLatest
23773
23873
  };
23774
- process.stdout.write(`${JSON.stringify(result2)}
23775
- `);
23874
+ printCompactJson(result2);
23776
23875
  return 0;
23777
23876
  }
23778
23877
  const resolvedName = parseReferencedPlayTarget2(playName).playName;
@@ -23796,8 +23895,7 @@ async function handlePlayPublish(args) {
23796
23895
  revisionId ? { revisionId } : {}
23797
23896
  );
23798
23897
  if (options.jsonOutput) {
23799
- process.stdout.write(`${JSON.stringify(result)}
23800
- `);
23898
+ printCompactJson(result);
23801
23899
  } else {
23802
23900
  printPublishReceipt({
23803
23901
  name: result.name,
@@ -23862,8 +23960,7 @@ async function handlePlayDelete(args) {
23862
23960
  plannedMutation: "move saved org-owned play to Trash and stop triggers"
23863
23961
  };
23864
23962
  if (argsWantJson(args)) {
23865
- process.stdout.write(`${JSON.stringify(result2)}
23866
- `);
23963
+ printCompactJson(result2);
23867
23964
  } else {
23868
23965
  process.stdout.write(
23869
23966
  `Dry run: would move ${result2.name} to Trash and stop its active triggers.
@@ -23874,8 +23971,7 @@ async function handlePlayDelete(args) {
23874
23971
  }
23875
23972
  const result = await client2.deletePlay(resolvedName);
23876
23973
  if (argsWantJson(args)) {
23877
- process.stdout.write(`${JSON.stringify(result)}
23878
- `);
23974
+ printCompactJson(result);
23879
23975
  return result.archived || result.alreadyArchived ? 0 : 4;
23880
23976
  }
23881
23977
  if (result.alreadyArchived) {
@@ -23920,8 +24016,7 @@ async function handlePlayRestore(args) {
23920
24016
  parseReferencedPlayTarget2(playName).playName
23921
24017
  );
23922
24018
  if (argsWantJson(args)) {
23923
- process.stdout.write(`${JSON.stringify(result)}
23924
- `);
24019
+ printCompactJson(result);
23925
24020
  return result.restored || result.alreadyActive ? 0 : 4;
23926
24021
  }
23927
24022
  if (result.alreadyActive) {
@@ -24807,8 +24902,7 @@ async function handlePlayShareStatus(args) {
24807
24902
  const status = await new DeeplineClient().getSharePage(name);
24808
24903
  const outputStatus = shareStatusForOutput(status);
24809
24904
  if (argsWantJson(args)) {
24810
- process.stdout.write(`${JSON.stringify(outputStatus)}
24811
- `);
24905
+ printCompactJson(outputStatus);
24812
24906
  return 0;
24813
24907
  }
24814
24908
  if (!outputStatus.share) {
@@ -24879,10 +24973,12 @@ async function handlePlaySharePublish(args) {
24879
24973
  if (!hasCompleted) {
24880
24974
  const message = `No completed run for ${name}. Publish a play only after it has run successfully. (Override with --no-run-check.)`;
24881
24975
  if (argsWantJson(args)) {
24882
- process.stdout.write(
24883
- `${JSON.stringify({ ok: false, code: "NO_SUCCESSFUL_RUN", message, next: `deepline plays run ${name} --wait` })}
24884
- `
24885
- );
24976
+ printCompactJson({
24977
+ ok: false,
24978
+ code: "NO_SUCCESSFUL_RUN",
24979
+ message,
24980
+ next: `deepline plays run ${name} --wait`
24981
+ });
24886
24982
  } else {
24887
24983
  console.error(message);
24888
24984
  console.error(` deepline plays run ${name} --wait`);
@@ -24902,8 +24998,7 @@ async function handlePlaySharePublish(args) {
24902
24998
  if (args.includes("--dry-run")) {
24903
24999
  const plan = { dryRun: true, name, version: resolvedVersion, ...request };
24904
25000
  if (argsWantJson(args)) {
24905
- process.stdout.write(`${JSON.stringify(plan)}
24906
- `);
25001
+ printCompactJson(plan);
24907
25002
  } else {
24908
25003
  console.log(
24909
25004
  `Would publish ${name}${resolvedVersion ? ` v${resolvedVersion}` : ""} (revision ${revisionId}).`
@@ -24914,8 +25009,7 @@ async function handlePlaySharePublish(args) {
24914
25009
  const status = await client2.publishSharePage(name, request);
24915
25010
  const outputStatus = shareStatusForOutput(status);
24916
25011
  if (argsWantJson(args)) {
24917
- process.stdout.write(`${JSON.stringify(outputStatus)}
24918
- `);
25012
+ printCompactJson(outputStatus);
24919
25013
  return 0;
24920
25014
  }
24921
25015
  const urls = shareUrlFields(outputStatus);
@@ -24948,8 +25042,7 @@ async function handlePlayShareUpdate(args) {
24948
25042
  };
24949
25043
  const status = await new DeeplineClient().updateSharePage(name, request);
24950
25044
  if (argsWantJson(args)) {
24951
- process.stdout.write(`${JSON.stringify(status)}
24952
- `);
25045
+ printCompactJson(status);
24953
25046
  return 0;
24954
25047
  }
24955
25048
  console.log(`Updated ${name} share settings.`);
@@ -24982,8 +25075,7 @@ async function handlePlayShareRegenerate(args) {
24982
25075
  );
24983
25076
  const outputStatus = shareStatusForOutput(status);
24984
25077
  if (argsWantJson(args)) {
24985
- process.stdout.write(`${JSON.stringify(outputStatus)}
24986
- `);
25078
+ printCompactJson(outputStatus);
24987
25079
  return 0;
24988
25080
  }
24989
25081
  const urls = shareUrlFields(outputStatus);
@@ -25010,8 +25102,7 @@ async function handlePlayShareUnpublish(args) {
25010
25102
  const name = parseReferencedPlayTarget2(target).playName;
25011
25103
  const status = await new DeeplineClient().unpublishSharePage(name);
25012
25104
  if (argsWantJson(args)) {
25013
- process.stdout.write(`${JSON.stringify(status)}
25014
- `);
25105
+ printCompactJson(status);
25015
25106
  return 0;
25016
25107
  }
25017
25108
  console.log(`Unpublished ${name}; the public page has been removed.`);
@@ -33571,6 +33662,27 @@ function redactApiKey(value) {
33571
33662
  function processEnvValue(name) {
33572
33663
  return process.env[name]?.trim() ?? "";
33573
33664
  }
33665
+ function organizationAuthValues(input2) {
33666
+ return {
33667
+ [HOST_URL_ENV]: input2.baseUrl,
33668
+ [API_KEY_ENV]: input2.apiKey,
33669
+ [ACTIVE_ORG_ID_ENV]: input2.orgId,
33670
+ [ACTIVE_ORG_NAME_ENV]: input2.orgName
33671
+ };
33672
+ }
33673
+ function organizationCommandContext(input2) {
33674
+ return {
33675
+ active_organization: {
33676
+ org_id: input2.orgId,
33677
+ org_name: input2.orgName
33678
+ },
33679
+ auth_scope: input2.authScope,
33680
+ metadata_source: input2.authScope === "folder" ? "folder_env" : "host_env"
33681
+ };
33682
+ }
33683
+ function agentCommandContext(commandContext) {
33684
+ return detectAgentRuntime() !== "unknown" ? { command_context: commandContext } : {};
33685
+ }
33574
33686
  function resolveOrgSwitchAuthTarget(scope, config) {
33575
33687
  const activeProject = getResolvedProjectAuthSource(
33576
33688
  config.baseUrl,
@@ -33767,10 +33879,16 @@ async function handleOrgSwitch(selection, options) {
33767
33879
  const config = resolveConfig();
33768
33880
  const provenance = resolveCliAuthProvenance(config);
33769
33881
  if (!selection && !options.orgId && authScope === "folder" && provenance.scope === "global" && provenance.project.state === "project") {
33882
+ const commandContext = resolveCliCommandContext(config);
33883
+ const activeOrganization = commandContext.active_organization;
33770
33884
  const project_env_paths2 = saveProjectDeeplineEnvValues(
33771
33885
  {
33772
33886
  [HOST_URL_ENV]: config.baseUrl,
33773
- [API_KEY_ENV]: config.apiKey
33887
+ [API_KEY_ENV]: config.apiKey,
33888
+ ...activeOrganization ? {
33889
+ [ACTIVE_ORG_ID_ENV]: activeOrganization.org_id,
33890
+ [ACTIVE_ORG_NAME_ENV]: activeOrganization.org_name ?? ""
33891
+ } : {}
33774
33892
  },
33775
33893
  provenance.project.dir
33776
33894
  );
@@ -33781,6 +33899,13 @@ async function handleOrgSwitch(selection, options) {
33781
33899
  requested_auth_scope: "folder",
33782
33900
  effective_auth_scope: "folder",
33783
33901
  auth_scope: "folder",
33902
+ ...agentCommandContext(
33903
+ activeOrganization ? organizationCommandContext({
33904
+ orgId: activeOrganization.org_id,
33905
+ orgName: activeOrganization.org_name,
33906
+ authScope: "folder"
33907
+ }) : resolveCliCommandContext(config, "folder")
33908
+ ),
33784
33909
  project_env_paths: project_env_paths2,
33785
33910
  next: { status: "deepline org status --json" },
33786
33911
  render: {
@@ -33843,10 +33968,12 @@ async function handleOrgSwitch(selection, options) {
33843
33968
  const authTarget = resolveOrgSwitchAuthTarget(authScope, config);
33844
33969
  if (target.is_current) {
33845
33970
  let project_env_paths2 = [];
33846
- const authValues2 = {
33847
- [HOST_URL_ENV]: config.baseUrl,
33848
- [API_KEY_ENV]: config.apiKey
33849
- };
33971
+ const authValues2 = organizationAuthValues({
33972
+ baseUrl: config.baseUrl,
33973
+ apiKey: config.apiKey,
33974
+ orgId: target.org_id,
33975
+ orgName: target.name
33976
+ });
33850
33977
  if (authTarget.kind === "folder") {
33851
33978
  project_env_paths2 = saveProjectDeeplineEnvValues(authValues2);
33852
33979
  } else {
@@ -33883,6 +34010,13 @@ async function handleOrgSwitch(selection, options) {
33883
34010
  effective_auth_scope: authTarget.effective_scope,
33884
34011
  auth_scope_reason: authTarget.reason,
33885
34012
  auth_scope: authTarget.effective_scope,
34013
+ ...agentCommandContext(
34014
+ organizationCommandContext({
34015
+ orgId: target.org_id,
34016
+ orgName: target.name,
34017
+ authScope: authTarget.effective_scope
34018
+ })
34019
+ ),
33886
34020
  host_env_path: authTarget.kind === "global" ? hostEnvFilePath(config.baseUrl) : null,
33887
34021
  project_env_paths: project_env_paths2,
33888
34022
  deprecated_command: options.deprecatedSwitch ? "org switch" : null,
@@ -33901,18 +34035,16 @@ async function handleOrgSwitch(selection, options) {
33901
34035
  org_id: target.org_id
33902
34036
  });
33903
34037
  let project_env_paths = [];
33904
- const authValues = {
33905
- [HOST_URL_ENV]: config.baseUrl,
33906
- [API_KEY_ENV]: switched.api_key
33907
- };
34038
+ const authValues = organizationAuthValues({
34039
+ baseUrl: config.baseUrl,
34040
+ apiKey: switched.api_key,
34041
+ orgId: switched.org_id,
34042
+ orgName: switched.org_name
34043
+ });
33908
34044
  if (authTarget.kind === "folder") {
33909
34045
  project_env_paths = saveProjectDeeplineEnvValues(authValues);
33910
34046
  } else {
33911
- saveHostEnvValues(config.baseUrl, {
33912
- ...authValues,
33913
- DEEPLINE_ACTIVE_ORG_ID: switched.org_id,
33914
- DEEPLINE_ACTIVE_ORG_NAME: switched.org_name
33915
- });
34047
+ saveHostEnvValues(config.baseUrl, authValues);
33916
34048
  }
33917
34049
  const { api_key: _apiKey, ...publicSwitched } = switched;
33918
34050
  const renderLines = [`Switched to ${switched.org_name}.`];
@@ -33947,6 +34079,13 @@ async function handleOrgSwitch(selection, options) {
33947
34079
  effective_auth_scope: authTarget.effective_scope,
33948
34080
  auth_scope_reason: authTarget.reason,
33949
34081
  auth_scope: authTarget.effective_scope,
34082
+ ...agentCommandContext(
34083
+ organizationCommandContext({
34084
+ orgId: switched.org_id,
34085
+ orgName: switched.org_name,
34086
+ authScope: authTarget.effective_scope
34087
+ })
34088
+ ),
33950
34089
  deprecated_command: options.deprecatedSwitch ? "org switch" : null,
33951
34090
  replacement_command: options.deprecatedSwitch ? "deepline org set" : null,
33952
34091
  warnings,
@@ -33969,15 +34108,13 @@ async function handleOrgCreate(name, options) {
33969
34108
  api_key: config.apiKey,
33970
34109
  name
33971
34110
  });
33972
- const authValues = {
33973
- [HOST_URL_ENV]: config.baseUrl,
33974
- [API_KEY_ENV]: created.api_key
33975
- };
33976
- saveHostEnvValues(config.baseUrl, {
33977
- ...authValues,
33978
- DEEPLINE_ACTIVE_ORG_ID: created.org_id,
33979
- DEEPLINE_ACTIVE_ORG_NAME: created.org_name
34111
+ const authValues = organizationAuthValues({
34112
+ baseUrl: config.baseUrl,
34113
+ apiKey: created.api_key,
34114
+ orgId: created.org_id,
34115
+ orgName: created.org_name
33980
34116
  });
34117
+ saveHostEnvValues(config.baseUrl, authValues);
33981
34118
  const { api_key: _apiKey, ...publicCreated } = created;
33982
34119
  printCommandEnvelope(
33983
34120
  {
@@ -33986,6 +34123,13 @@ async function handleOrgCreate(name, options) {
33986
34123
  api_key_saved: true,
33987
34124
  switched: true,
33988
34125
  host_env_path: hostEnvFilePath(config.baseUrl),
34126
+ ...agentCommandContext(
34127
+ organizationCommandContext({
34128
+ orgId: created.org_id,
34129
+ orgName: created.org_name,
34130
+ authScope: "global"
34131
+ })
34132
+ ),
33989
34133
  render: {
33990
34134
  sections: [
33991
34135
  {
@@ -39839,26 +39983,20 @@ async function getTool(toolId, options = {}) {
39839
39983
  return 2;
39840
39984
  }
39841
39985
  if (options.contractJson) {
39842
- process.stdout.write(
39843
- `${JSON.stringify({
39844
- ...toolContractJsonForDescribe(tool, toolId),
39845
- ...modelDescription ? { modelOptions: modelDescription } : {},
39846
- ...inferenceQuote ? { inferenceQuote } : {}
39847
- })}
39848
- `
39849
- );
39986
+ printCompactJson({
39987
+ ...toolContractJsonForDescribe(tool, toolId),
39988
+ ...modelDescription ? { modelOptions: modelDescription } : {},
39989
+ ...inferenceQuote ? { inferenceQuote } : {}
39990
+ });
39850
39991
  return 0;
39851
39992
  }
39852
39993
  const emitJson = options.json === true;
39853
39994
  if (emitJson) {
39854
- process.stdout.write(
39855
- `${JSON.stringify({
39856
- ...toolMetadataJsonForDescribe(tool, toolId),
39857
- ...modelDescription ? { modelOptions: modelDescription } : {},
39858
- ...inferenceQuote ? { inferenceQuote } : {}
39859
- })}
39860
- `
39861
- );
39995
+ printCompactJson({
39996
+ ...toolMetadataJsonForDescribe(tool, toolId),
39997
+ ...modelDescription ? { modelOptions: modelDescription } : {},
39998
+ ...inferenceQuote ? { inferenceQuote } : {}
39999
+ });
39862
40000
  return 0;
39863
40001
  }
39864
40002
  const onlyModes = [
@@ -39903,14 +40041,11 @@ ${formatModelDescription(modelDescription)}`);
39903
40041
  return 0;
39904
40042
  }
39905
40043
  if (shouldEmitJson()) {
39906
- process.stdout.write(
39907
- `${JSON.stringify({
39908
- ...toolContractJsonForDescribe(tool, toolId),
39909
- ...modelDescription ? { modelOptions: modelDescription } : {},
39910
- ...inferenceQuote ? { inferenceQuote } : {}
39911
- })}
39912
- `
39913
- );
40044
+ printCompactJson({
40045
+ ...toolContractJsonForDescribe(tool, toolId),
40046
+ ...modelDescription ? { modelOptions: modelDescription } : {},
40047
+ ...inferenceQuote ? { inferenceQuote } : {}
40048
+ });
39914
40049
  return 0;
39915
40050
  }
39916
40051
  printCompactToolContract(tool, toolId);
@@ -42581,8 +42716,7 @@ Examples:
42581
42716
  ).action(async (options) => {
42582
42717
  const data = await runPreflightCheck();
42583
42718
  if (shouldEmitJson(options.json)) {
42584
- process.stdout.write(`${JSON.stringify(data, null, 2)}
42585
- `);
42719
+ printJson(data);
42586
42720
  } else {
42587
42721
  printPreflightHuman(data);
42588
42722
  }
@@ -42607,14 +42741,12 @@ Examples:
42607
42741
  try {
42608
42742
  if (options.playRunner) {
42609
42743
  const data2 = await runPlayRunnerHealthCheck();
42610
- process.stdout.write(`${JSON.stringify(data2, null, 2)}
42611
- `);
42744
+ printJson(data2);
42612
42745
  return;
42613
42746
  }
42614
42747
  const client2 = new DeeplineClient();
42615
42748
  const data = await client2.health();
42616
- process.stdout.write(`${JSON.stringify(data, null, 2)}
42617
- `);
42749
+ printJson(data);
42618
42750
  } catch (error) {
42619
42751
  throw new Error(
42620
42752
  `Cannot reach Deepline API: ${error instanceof Error ? error.message : String(error)}`
@@ -42635,8 +42767,7 @@ Examples:
42635
42767
  `
42636
42768
  ).option("--json", "Emit JSON output").action((options) => {
42637
42769
  if (options.json) {
42638
- process.stdout.write(`${JSON.stringify({ version: SDK_VERSION })}
42639
- `);
42770
+ printCompactJson({ version: SDK_VERSION });
42640
42771
  return;
42641
42772
  }
42642
42773
  process.stdout.write(`deepline ${SDK_VERSION}