@koda-sl/baker-cli 0.868.0-dev.5be0a9a76 → 0.868.0-dev.dd070597a

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.
Files changed (34) hide show
  1. package/README.md +2 -3
  2. package/dist/{account-reads-SUWXGTGW.js → account-reads-3LP4F3L4.js} +2 -2
  3. package/dist/{add-TKHBYZF6.js → add-ZMOFKHFR.js} +2 -2
  4. package/dist/{ads-U33JFGCR.js → ads-O76TVWHX.js} +2 -2
  5. package/dist/{chunk-TY4MTOTL.js → chunk-MIIY3MVK.js} +1 -22
  6. package/dist/chunk-MIIY3MVK.js.map +1 -0
  7. package/dist/{chunk-LZ5DS4UB.js → chunk-N366L5EF.js} +32 -4
  8. package/dist/chunk-N366L5EF.js.map +1 -0
  9. package/dist/cli.js +3 -3
  10. package/dist/cli.js.map +1 -1
  11. package/dist/{conversion-upload-command-Y4ABNNAT.js → conversion-upload-command-HJOVSWZD.js} +2 -2
  12. package/dist/{draft-CLNMIQXV.js → draft-OLSFLDME.js} +2 -2
  13. package/dist/{flows-FRWZWHXZ.js → flows-PP6BRBD7.js} +3 -3
  14. package/dist/{forecast-JAPRYH4F.js → forecast-AQDB4LLG.js} +2 -2
  15. package/dist/{google-HHKFDH7I.js → google-HLE7YIYM.js} +57 -40
  16. package/dist/google-HLE7YIYM.js.map +1 -0
  17. package/dist/{search-terms-WLOW2FPP.js → search-terms-WKEPRHN2.js} +2 -2
  18. package/dist/{tags-DFCLKJX7.js → tags-IQ6BCRLE.js} +15 -26
  19. package/dist/tags-IQ6BCRLE.js.map +1 -0
  20. package/dist/{themes-Q5CSF6TJ.js → themes-2T5BOIZU.js} +2 -2
  21. package/package.json +1 -1
  22. package/dist/chunk-LZ5DS4UB.js.map +0 -1
  23. package/dist/chunk-TY4MTOTL.js.map +0 -1
  24. package/dist/google-HHKFDH7I.js.map +0 -1
  25. package/dist/tags-DFCLKJX7.js.map +0 -1
  26. /package/dist/{account-reads-SUWXGTGW.js.map → account-reads-3LP4F3L4.js.map} +0 -0
  27. /package/dist/{add-TKHBYZF6.js.map → add-ZMOFKHFR.js.map} +0 -0
  28. /package/dist/{ads-U33JFGCR.js.map → ads-O76TVWHX.js.map} +0 -0
  29. /package/dist/{conversion-upload-command-Y4ABNNAT.js.map → conversion-upload-command-HJOVSWZD.js.map} +0 -0
  30. /package/dist/{draft-CLNMIQXV.js.map → draft-OLSFLDME.js.map} +0 -0
  31. /package/dist/{flows-FRWZWHXZ.js.map → flows-PP6BRBD7.js.map} +0 -0
  32. /package/dist/{forecast-JAPRYH4F.js.map → forecast-AQDB4LLG.js.map} +0 -0
  33. /package/dist/{search-terms-WLOW2FPP.js.map → search-terms-WKEPRHN2.js.map} +0 -0
  34. /package/dist/{themes-Q5CSF6TJ.js.map → themes-2T5BOIZU.js.map} +0 -0
@@ -9,7 +9,7 @@ import {
9
9
  keywordEntries,
10
10
  listFlag,
11
11
  requireCustomerId
12
- } from "./chunk-LZ5DS4UB.js";
12
+ } from "./chunk-N366L5EF.js";
13
13
  import "./chunk-RHN5FEWA.js";
14
14
  import "./chunk-XD7C5OE7.js";
15
15
  import "./chunk-UKENQSZ2.js";
@@ -409,4 +409,4 @@ export {
409
409
  searchTermsHints,
410
410
  searchTermsRequest
411
411
  };
412
- //# sourceMappingURL=search-terms-WLOW2FPP.js.map
412
+ //# sourceMappingURL=search-terms-WKEPRHN2.js.map
@@ -1,11 +1,9 @@
1
1
  import {
2
- COLLAPSED_HINT,
3
2
  failApi,
4
3
  failValidation,
5
- listedTag,
6
4
  renderEffectiveEntry,
7
5
  tagsListHints
8
- } from "./chunk-TY4MTOTL.js";
6
+ } from "./chunk-MIIY3MVK.js";
9
7
  import {
10
8
  CHAT_READ_ARG
11
9
  } from "./chunk-X32MFGWW.js";
@@ -36,32 +34,26 @@ import "./chunk-YQSBHWOI.js";
36
34
 
37
35
  // src/commands/tags/index.ts
38
36
  import { defineCommand } from "citty";
39
- var LIST_OUTPUT_DESCRIPTION = "Output format: json|md. Default: json (the envelope); md prints one readable block per tag";
40
- var LIST_FULL_DESCRIPTION = "Print every config value whole, a custom `code` script included (by default a long value shows as its size)";
41
- var LIST_JSON_DESCRIPTION = "Same as the default: the JSON envelope (kept for older calls)";
42
37
  registerSchema({
43
38
  command: "tags.list",
44
- description: "Effective marketing tags for this chat: production tags overlaid with the changes staged in this chat, as the JSON envelope (`data` is one row per tag; `--output md` for a readable block per tag). Each tag's readable config is included (secrets are never included) \u2014 e.g. the Clarity projectId or GA4 measurementId \u2014 so reuse a stored value to pre-fill a follow-up change instead of asking the user for something we already have. A long value (a custom `code` script) shows as its size under `collapsed`; `--full` prints it whole. The printed refs (tag ids or tag_temp_*) are exactly what flow side-effect tagIds should reference. Read-only \u2014 every tag change (create, edit, delete) goes through the request_tag_input approval tool; `baker tags unstage` takes back one this chat staged.",
39
+ description: "Effective marketing tags for this chat: production tags overlaid with the changes staged in this chat. Prints each tag's readable config in full (secrets are never included) \u2014 e.g. the Clarity projectId, GA4 measurementId, or the entire custom `code` snippet \u2014 so reuse a stored value to pre-fill a follow-up change instead of asking the user for something we already have. The printed refs (tag ids or tag_temp_*) are exactly what flow side-effect tagIds should reference. Read-only \u2014 every tag change (create, edit, delete) goes through the request_tag_input approval tool; `baker tags unstage` takes back one this chat staged.",
45
40
  args: {
46
- output: { type: "string", description: LIST_OUTPUT_DESCRIPTION, required: false, default: "json" },
47
- full: { type: "boolean", description: LIST_FULL_DESCRIPTION, required: false },
48
- json: { type: "boolean", description: LIST_JSON_DESCRIPTION, required: false }
41
+ json: { type: "boolean", description: "Print the raw JSON envelope instead of the readable list", required: false }
49
42
  }
50
43
  });
51
- async function listTags(output, full) {
44
+ async function listTags(json) {
52
45
  try {
53
46
  const chatId = requireChatId();
54
47
  const response = await apiPost("/api/tags/list", { chatId });
55
- const tags = full ? response.tags : response.tags.map(listedTag);
56
- const hints = [...tagsListHints(), ...tags.some((tag) => tag.collapsed) ? [COLLAPSED_HINT] : []];
57
- if (output !== "md") {
58
- writeJson({ ok: true, ...rowsAsData({ tags }, "tags"), hints });
48
+ const hints = tagsListHints();
49
+ if (json) {
50
+ writeJson({ ok: true, ...rowsAsData(response, "tags"), hints });
59
51
  return;
60
52
  }
61
- if (tags.length === 0) {
53
+ if (response.tags.length === 0) {
62
54
  process.stdout.write("No tags configured.\n");
63
55
  } else {
64
- process.stdout.write(`${tags.map(renderEffectiveEntry).join("\n")}
56
+ process.stdout.write(`${response.tags.map(renderEffectiveEntry).join("\n")}
65
57
  `);
66
58
  }
67
59
  for (const hint of hints) {
@@ -73,18 +65,16 @@ async function listTags(output, full) {
73
65
  }
74
66
  }
75
67
  var listArgs = {
76
- output: { type: "string", description: LIST_OUTPUT_DESCRIPTION, default: "json" },
77
- full: { type: "boolean", description: LIST_FULL_DESCRIPTION },
78
- json: { type: "boolean", description: LIST_JSON_DESCRIPTION }
68
+ json: { type: "boolean", description: "Print the raw JSON envelope instead of the readable list" }
79
69
  };
80
70
  var listCommand = defineCommand({
81
71
  meta: {
82
72
  name: "list",
83
- description: "Effective tags for this chat (production + staged) as the JSON envelope, with each tag's readable config (secrets excluded) \u2014 reuse a stored value to pre-fill a change rather than asking the user. Refs printed here are what flow side-effect tagIds should use. A custom `code` script shows as its size; --full prints it. Start here: baker tags list | baker tags list --output md"
73
+ description: "Effective tags for this chat (production + staged), with each tag's full readable config (secrets excluded) \u2014 reuse a stored value to pre-fill a change rather than asking the user. Refs printed here are what flow side-effect tagIds should use. Example: baker tags list"
84
74
  },
85
75
  args: listArgs,
86
76
  run: async ({ args }) => {
87
- await listTags(args.output, args.full === true);
77
+ await listTags(args.json === true);
88
78
  }
89
79
  });
90
80
  async function listDraft(chat) {
@@ -164,13 +154,12 @@ Every tag change \u2014 create, edit, or delete \u2014 goes through the request_
164
154
 
165
155
  Refs: \`baker tags list\` prints each tag's ref \u2014 a real tag id, or tag_temp_* for creates staged in this chat. Use these refs as flow side-effect tagIds; they keep resolving after publish.
166
156
 
167
- \`baker tags list\` prints the JSON envelope (\`--output md\` to read it), with each tag's readable config (secrets excluded) \u2014 the Clarity projectId, GA4 measurementId, etc.; a custom \`code\` script shows as its size until \`--full\`. Reuse a stored value to pre-fill a follow-up change instead of asking the user for something already installed.
157
+ \`baker tags list\` prints each tag's readable config in full (secrets excluded) \u2014 the Clarity projectId, GA4 measurementId, the whole custom \`code\` snippet, etc. Reuse a stored value to pre-fill a follow-up change instead of asking the user for something already installed.
168
158
 
169
159
  To take back a change this chat staged (before Publish), \`baker tags unstage <ref>\` \u2014 the ref \`baker tags draft\` prints \u2014 or \`--all\`. It never touches a live tag.
170
160
 
171
161
  Examples:
172
- baker tags list # production + staged, config + secret status, as the JSON envelope
173
- baker tags list --output md --full # readable, custom code scripts whole
162
+ baker tags list # production + staged, full readable config + secret status
174
163
  baker tags draft # review the staged changes awaiting publish
175
164
  baker tags unstage tag_temp_abc123 # take back one staged change
176
165
  Full guide: __tooling__/docs/tools/baker/tags.md`
@@ -191,4 +180,4 @@ export {
191
180
  tagsCommand,
192
181
  unstageBody
193
182
  };
194
- //# sourceMappingURL=tags-DFCLKJX7.js.map
183
+ //# sourceMappingURL=tags-IQ6BCRLE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/tags/index.ts"],"sourcesContent":["import type { TagsDraftListResponse, TagsListResponse, TagsUnstageRequest, TagsUnstageResponse } from \"@baker/api\";\nimport { defineCommand } from \"citty\";\nimport { apiPost } from \"../../client.ts\";\nimport { requireChatId, resolveChatId } from \"../../env.ts\";\nimport { rowsAsData, writeJson } from \"../../output.ts\";\nimport { registerSchema } from \"../../schemas.ts\";\nimport { CHAT_READ_ARG } from \"../chat-arg.ts\";\nimport { failApi, failValidation, renderEffectiveEntry, tagsListHints } from \"./shared.ts\";\n\nregisterSchema({\n command: \"tags.list\",\n description:\n \"Effective marketing tags for this chat: production tags overlaid with the changes staged in this chat. Prints each tag's readable config in full (secrets are never included) — e.g. the Clarity projectId, GA4 measurementId, or the entire custom `code` snippet — so reuse a stored value to pre-fill a follow-up change instead of asking the user for something we already have. The printed refs (tag ids or tag_temp_*) are exactly what flow side-effect tagIds should reference. Read-only — every tag change (create, edit, delete) goes through the request_tag_input approval tool; `baker tags unstage` takes back one this chat staged.\",\n args: {\n json: { type: \"boolean\", description: \"Print the raw JSON envelope instead of the readable list\", required: false },\n },\n});\n\nasync function listTags(json: boolean): Promise<void> {\n try {\n const chatId = requireChatId();\n const response = await apiPost<TagsListResponse>(\"/api/tags/list\", { chatId });\n const hints = tagsListHints();\n if (json) {\n writeJson({ ok: true, ...rowsAsData(response, \"tags\"), hints });\n return;\n }\n if (response.tags.length === 0) {\n process.stdout.write(\"No tags configured.\\n\");\n } else {\n process.stdout.write(`${response.tags.map(renderEffectiveEntry).join(\"\\n\")}\\n`);\n }\n // stdout stays the list and nothing else, so a reader piping it keeps\n // parsing it; the hints go to stderr, where the agent still reads them.\n for (const hint of hints) {\n process.stderr.write(`${hint}\\n`);\n }\n } catch (err) {\n failApi(err);\n }\n}\n\nconst listArgs = {\n json: { type: \"boolean\", description: \"Print the raw JSON envelope instead of the readable list\" },\n} as const;\n\nconst listCommand = defineCommand({\n meta: {\n name: \"list\",\n description:\n \"Effective tags for this chat (production + staged), with each tag's full readable config (secrets excluded) — reuse a stored value to pre-fill a change rather than asking the user. Refs printed here are what flow side-effect tagIds should use. Example: baker tags list\",\n },\n args: listArgs,\n run: async ({ args }) => {\n await listTags(args.json === true);\n },\n});\n\nasync function listDraft(chat?: unknown): Promise<void> {\n try {\n const chatId = resolveChatId(chat);\n const response = await apiPost<TagsDraftListResponse>(\"/api/tags/draft\", { chatId });\n writeJson({ ok: true, data: response, hints: tagsListHints() });\n } catch (err) {\n failApi(err);\n }\n}\n\nconst draftCommand = defineCommand({\n meta: {\n name: \"draft\",\n description:\n \"Review the tag changes staged in this chat (read-only). Staged changes were approved via request_tag_input and apply when the chat is published. To drop one, `baker tags unstage <ref>` with the ref printed here (or --all); to amend one, propose a follow-up change through the same tool. Takes --chat <id> to read an earlier chat's staged changes instead.\",\n },\n args: { chat: CHAT_READ_ARG },\n run: async ({ args }) => {\n await listDraft(args.chat);\n },\n});\n\nregisterSchema({\n command: \"tags.unstage\",\n description:\n \"Take back a tag change this chat staged, before Publish — the same as discarding its row in the change review. Pass the ref `baker tags draft` prints (a tag id, or tag_temp_* for a staged create), or --all for every staged tag change. Taking back a staged create also drops the secrets the user entered for it. Never touches a live tag: to change or remove one, propose the change through request_tag_input.\",\n args: {\n ref: { type: \"string\", description: \"The staged change's ref, from `baker tags draft`\", required: false },\n all: { type: \"boolean\", description: \"Take back every tag change staged in this chat\", required: false },\n },\n});\n\n/** The request for one unstage, checked before the round trip. */\nexport function unstageBody(args: { ref?: string; all?: boolean }, chatId: string): TagsUnstageRequest {\n const ref = args.ref?.trim();\n if (args.all === true && ref) {\n failValidation(\"Pass one ref to take back that change, or --all for every staged tag change — not both.\");\n }\n if (args.all === true) {\n return { chatId, all: true };\n }\n if (!ref) {\n failValidation(\"Pass the ref of the staged change (from `baker tags draft`), or --all.\");\n }\n return { chatId, ref };\n}\n\nconst unstageCommand = defineCommand({\n meta: {\n name: \"unstage\",\n description:\n \"Take back a tag change this chat staged, before Publish. Examples: baker tags unstage tag_temp_abc123 | baker tags unstage --all\",\n },\n args: {\n ref: { type: \"positional\", description: \"The staged change's ref, from `baker tags draft`\", required: false },\n all: { type: \"boolean\", description: \"Take back every tag change staged in this chat\", required: false },\n },\n run: async ({ args }) => {\n try {\n const body = unstageBody(\n {\n ...(typeof args.ref === \"string\" ? { ref: args.ref } : {}),\n ...(args.all === true ? { all: true } : {}),\n },\n requireChatId(),\n );\n const response = await apiPost<TagsUnstageResponse>(\"/api/tags/draft-op/remove\", body);\n writeJson({\n ...response,\n hints: [\"Taken back: it does not apply when the chat is published. Live tags are unchanged.\"],\n });\n } catch (err) {\n failApi(err);\n }\n },\n});\n\nexport const tagsCommand = defineCommand({\n meta: {\n name: \"tags\",\n description: `Read the client's marketing/analytics tags (Meta pixel, GA4, Google Ads, GTM, Clarity, Hotjar, …) — production tags plus the changes staged in this chat.\n\nEvery tag change — create, edit, or delete — goes through the request_tag_input tool (baker_ui MCP server): propose one or more changes (each becomes a tab in one approval form), pre-fill the non-secret fields you know, and the user reviews, fills secrets, and approves or skips each. Secret values (accessToken, apiSecret, authorizationToken, apiKey, conversionToken, OAuth connections) never pass through the CLI or the chat.\n\nRefs: \\`baker tags list\\` prints each tag's ref — a real tag id, or tag_temp_* for creates staged in this chat. Use these refs as flow side-effect tagIds; they keep resolving after publish.\n\n\\`baker tags list\\` prints each tag's readable config in full (secrets excluded) — the Clarity projectId, GA4 measurementId, the whole custom \\`code\\` snippet, etc. Reuse a stored value to pre-fill a follow-up change instead of asking the user for something already installed.\n\nTo take back a change this chat staged (before Publish), \\`baker tags unstage <ref>\\` — the ref \\`baker tags draft\\` prints — or \\`--all\\`. It never touches a live tag.\n\nExamples:\n baker tags list # production + staged, full readable config + secret status\n baker tags draft # review the staged changes awaiting publish\n baker tags unstage tag_temp_abc123 # take back one staged change\nFull guide: __tooling__/docs/tools/baker/tags.md`,\n },\n subCommands: {\n list: listCommand,\n draft: draftCommand,\n unstage: unstageCommand,\n },\n // Bare `baker tags` lists the effective tags. `args` stays so citty knows this\n // command's flags when it scans rawArgs for a subcommand name, and `default` (not\n // `run`) dispatches the bare invocation — citty falls through to `run` after a\n // subcommand, so a `run` here would also list on every `baker tags draft`.\n args: listArgs,\n default: \"list\",\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAS,qBAAqB;AAQ9B,eAAe;AAAA,EACb,SAAS;AAAA,EACT,aACE;AAAA,EACF,MAAM;AAAA,IACJ,MAAM,EAAE,MAAM,WAAW,aAAa,4DAA4D,UAAU,MAAM;AAAA,EACpH;AACF,CAAC;AAED,eAAe,SAAS,MAA8B;AACpD,MAAI;AACF,UAAM,SAAS,cAAc;AAC7B,UAAM,WAAW,MAAM,QAA0B,kBAAkB,EAAE,OAAO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;AAEM,IAAM,cAAc,cAAc;AAAA,EACvC,MAAM;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAef;AAAA,EACA,aAAa;AAAA,IACX,MAAM;AAAA,IACN,OAAO;AAAA,IACP,SAAS;AAAA,EACX;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM;AAAA,EACN,SAAS;AACX,CAAC;","names":[]}
@@ -5,7 +5,7 @@ import {
5
5
  failWriteValidation,
6
6
  listFlag,
7
7
  requireCustomerId
8
- } from "./chunk-LZ5DS4UB.js";
8
+ } from "./chunk-N366L5EF.js";
9
9
  import "./chunk-RHN5FEWA.js";
10
10
  import "./chunk-XD7C5OE7.js";
11
11
  import "./chunk-UKENQSZ2.js";
@@ -99,4 +99,4 @@ Example:
99
99
  export {
100
100
  themesCommand
101
101
  };
102
- //# sourceMappingURL=themes-Q5CSF6TJ.js.map
102
+ //# sourceMappingURL=themes-2T5BOIZU.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koda-sl/baker-cli",
3
- "version": "0.868.0-dev.5be0a9a76",
3
+ "version": "0.868.0-dev.dd070597a",
4
4
  "description": "AI-agent-first CLI for interacting with Baker, including the Baker creative canvas.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/ads/google/draft-account.ts","../src/commands/ads/google/write-shared.ts","../src/commands/ads/google/copy-list-usage.ts","../src/commands/ads/google/draft-status.ts","../src/commands/ads/google/stage-streak.ts"],"sourcesContent":["import type { GoogleDraftListResponse } from \"@baker/api/ads-google\";\n\n/**\n * `--customer-id` on the draft reads. A draft belongs to the chat, not to an account, and may span\n * several; every other Google Ads command takes the flag, so agents carry it here (BAKER-497).\n * `list` narrows to that account and says what the others still hold; `validate` and `show` keep\n * their whole answer, because publish sends every account together and a ref names one op.\n */\n\nfunction changes(n: number, staged: boolean): string {\n const noun = staged ? \"staged change\" : \"change\";\n return n === 1 ? `1 ${noun}` : `${n} ${noun}s`;\n}\n\n/**\n * The draft as one account holds it, with what the rest of the chat's draft holds. `empty` is the\n * readable line for an account holding none of it, where the whole-chat \"nothing staged\" would be false.\n * Only an active draft's other changes are still to publish; a published one's are already done.\n */\nexport function draftInAccount(\n data: GoogleDraftListResponse,\n customerId: string,\n): { data: GoogleDraftListResponse; hints: string[]; empty?: string } {\n const ops = data.ops.filter((op) => op.customerId === customerId);\n const narrowed = {\n ...data,\n count: ops.length,\n ops,\n ...(data.tree ? { tree: data.tree.filter((node) => node.customerId === customerId) } : {}),\n };\n const others = data.ops.filter((op) => op.customerId !== customerId);\n if (others.length === 0) return { data: narrowed, hints: [] };\n const staged = data.status === \"active\";\n const accounts = [...new Set(others.map((op) => op.customerId))];\n const where = `account${accounts.length === 1 ? \"\" : \"s\"} ${accounts.join(\", \")}`;\n const one = others.length === 1;\n if (ops.length === 0) {\n return {\n data: narrowed,\n empty: `No Google Ads changes in account ${customerId} on this chat.`,\n hints: [`This chat's ${changes(others.length, staged)} ${one ? \"is\" : \"are\"} in ${where}, not ${customerId}.`],\n };\n }\n const more = `${others.length} more ${staged ? \"staged \" : \"\"}change${one ? \"\" : \"s\"}`;\n const verb = staged ? (one ? \"publishes\" : \"publish\") : one ? \"is\" : \"are\";\n return {\n data: narrowed,\n hints: [\n `Showing account ${customerId} only. ${more} in ${where} ${verb} ${staged ? \"with this chat too\" : \"on this chat too\"}; \\`baker ads google draft list\\` without --customer-id shows ${one ? \"it\" : \"them\"}.`,\n ],\n };\n}\n\n/** `draft validate --customer-id`: said back, since the verdicts still cover every account. */\nexport function validateAccountHint(customerId: string): string {\n return `Validated this chat's whole draft, not only account ${customerId}: publish sends every account's changes together, so each verdict above counts.`;\n}\n\n/** `draft show --customer-id` naming another account than the op's own. */\nexport function showAccountHint(customerId: string, opCustomerId: string): string | undefined {\n return opCustomerId === customerId ? undefined : `This op is staged in account ${opCustomerId}, not ${customerId}.`;\n}\n","import { readFileSync } from \"node:fs\";\nimport {\n GOOGLE_DRAFT_BATCH_MAX,\n type GoogleDraftListResponse,\n type GoogleDraftOpKind,\n type GoogleDraftStageBatchResponse,\n type GoogleDraftStageResponse,\n googleDraftBatchOpSchema,\n googleDraftOpInputSchema,\n OP_TOO_LARGE_FIX,\n OP_TOO_LARGE_MESSAGE_START,\n toMicros,\n} from \"@baker/api/ads-google\";\nimport { defineCommand } from \"citty\";\nimport { ApiError, apiPost } from \"../../../client.ts\";\nimport { requireChatId, resolveChatId } from \"../../../env.ts\";\nimport { handleConnectionError, isNotConnectedError } from \"../../../error-handler.ts\";\nimport { repeatedValues } from \"../../../lib/repeatedFlags.ts\";\nimport { type CommandEffectDeclaration, type PayloadSource, payloadArg, withEffect } from \"../../../schemas.ts\";\nimport { payloadFix } from \"../../capabilities/fix.ts\";\nimport { type DraftWhere, draftListWhere, wholeDraftHints } from \"../../draft-where.ts\";\nimport { booleanWordPositionalError } from \"../boolean-word-positional.ts\";\nimport { adCopyHints } from \"../copy-hints.ts\";\nimport { hintLines, withHints } from \"../hints.ts\";\nimport { bareCustomerId, writeJsonEnvelope } from \"../output.ts\";\nimport { termsRefusalFix } from \"../terms-output.ts\";\nimport { copyListCountFix } from \"./copy-list-usage.ts\";\nimport { draftInAccount } from \"./draft-account.ts\";\nimport { renderDraftStatus } from \"./draft-status.ts\";\nimport { recordSingleStage, recordTreeStage } from \"./stage-streak.ts\";\n\n/**\n * Shared plumbing for the staged Google Ads write commands. Writes NEVER hit\n * the Google Ads API directly: every command stages an op against this chat's\n * draft (`/api/ads/google/draft/stage`), the dashboard shows it as a pending\n * Google Ads change, and the draft applies as one `GoogleAdsService.Mutate`\n * request per advertiser account when the chat is published. `--customer-id` is\n * required on every write — a draft may span several accounts, so nothing is\n * picked for you.\n */\n\n/** What a staged Google Ads write command does: one op of these kinds onto this chat's draft. */\nexport function googleStaged(...kinds: GoogleDraftOpKind[]): CommandEffectDeclaration {\n return { effect: \"stage\", routes: [\"POST /api/ads/google/draft/stage\"], stages: kinds };\n}\n\n/** A staged write that takes one op or many: several go as one batch (`stageGoogleOps`). */\nexport function googleStagedBatch(...kinds: GoogleDraftOpKind[]): CommandEffectDeclaration {\n return {\n effect: \"stage\",\n routes: [\"POST /api/ads/google/draft/stage\", \"POST /api/ads/google/draft/stage-batch\"],\n stages: kinds,\n };\n}\n\nexport function failWriteValidation(message: string): never {\n writeJsonEnvelope({ ok: false, error: { code: \"VALIDATION_ERROR\", message } });\n process.exit(1);\n}\n\nexport function requireCustomerId(args: Record<string, unknown>): string {\n const given = (args[\"customer-id\"] ?? args.customerId) as string | undefined;\n const raw = given === undefined ? undefined : bareCustomerId(String(given));\n if (!raw || !/^\\d{10}$/.test(raw)) {\n failWriteValidation(\"pass --customer-id as the 10-digit Google Ads customer id (386-508-3115 or 3865083115)\");\n }\n return raw;\n}\n\nexport function requireTarget(args: Record<string, unknown>, entity: string): string {\n // `--flag false` is refused, not documented: citty parses it as the flag set to TRUE plus a stray\n // positional nobody consumes, so on `conversions update --primary` it silently PROMOTES an action\n // into what every Maximize Conversions campaign bids toward. Caught here because this is the only\n // place on this surface that reads positionals, and every target-taking command goes through it.\n const booleanWord = booleanWordPositionalError(args, entity);\n if (booleanWord) {\n failWriteValidation(booleanWord);\n }\n const positional = Array.isArray(args._) ? args._[0] : undefined;\n const target = args.id ?? args.target ?? args.ref ?? positional;\n if (typeof target !== \"string\" || target.length === 0) {\n failWriteValidation(`pass the ${entity} resource name or id as the positional argument`);\n }\n return target;\n}\n\n/**\n * The targets a bulk status command was given: every positional (comma-separated ones split), plus\n * `--file` with one target per line (blank lines and `#` comments skipped), deduped in order. One\n * call then stages them all as one batch instead of one command per row.\n */\nexport function targetEntries(args: Record<string, unknown>, entity: string): string[] {\n const booleanWord = booleanWordPositionalError(args, entity);\n if (booleanWord) {\n failWriteValidation(booleanWord);\n }\n const positionals = Array.isArray(args._) ? args._.filter((v): v is string => typeof v === \"string\") : [];\n const raw = [...positionals.flatMap((v) => v.split(\",\")), ...rawFileEntries(args.file)]\n .map((v) => v.trim())\n .filter(Boolean);\n const targets = [...new Set(raw)];\n if (targets.length === 0) {\n failWriteValidation(`pass the ${entity} resource name(s) as positional arguments and/or --file (one per line)`);\n }\n if (targets.length > GOOGLE_DRAFT_BATCH_MAX) {\n failWriteValidation(`${targets.length} targets exceeds the batch limit of ${GOOGLE_DRAFT_BATCH_MAX} — split them`);\n }\n return targets;\n}\n\n/**\n * The targets an update command was given: one, or several (space- or comma-separated) that each get\n * the same payload, staged as one batch. `--file` here is the payload, never a list of targets.\n */\nexport function updateTargets(args: Record<string, unknown>, entity: string): string[] {\n return Array.isArray(args._) && args._.length > 0\n ? targetEntries({ ...args, file: undefined }, entity)\n : [requireTarget(args, entity)];\n}\n\nexport function requireStringFlag(value: unknown, flag: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n failWriteValidation(`${flag} is required`);\n }\n return value;\n}\n\n/** Money flag in major currency units → micros. */\nexport function microsFlag(value: unknown, flag: string): number | undefined {\n if (value === undefined || value === null || value === \"\") {\n return undefined;\n }\n const num = Number(value);\n if (Number.isNaN(num) || num <= 0) {\n failWriteValidation(`${flag} must be a positive amount (major currency units, e.g. 50 or 50.00)`);\n }\n return toMicros(num);\n}\n\n/** Split a comma-separated flag into trimmed non-empty values. */\nexport function listFlag(value: unknown): string[] | undefined {\n if (typeof value !== \"string\" || value.length === 0) {\n return undefined;\n }\n const items = value\n .split(\",\")\n .map((v) => v.trim())\n .filter(Boolean);\n return items.length > 0 ? items : undefined;\n}\n\nexport interface KeywordEntry {\n text: string;\n matchType: string;\n}\n\nconst MATCH_TYPES = new Set([\"EXACT\", \"PHRASE\", \"BROAD\"]);\n\n/**\n * One raw keyword entry → { text, matchType }. A trailing `:EXACT|:PHRASE|:BROAD`\n * suffix overrides the default match type; colons and commas aren't legal in Google\n * keyword text, so the syntax is unambiguous.\n */\nfunction parseKeywordEntry(raw: string, defaultMatch: string | undefined): KeywordEntry {\n const colon = raw.lastIndexOf(\":\");\n if (colon > 0) {\n const suffix = raw\n .slice(colon + 1)\n .trim()\n .toUpperCase();\n if (MATCH_TYPES.has(suffix)) {\n return { text: raw.slice(0, colon).trim(), matchType: suffix };\n }\n failWriteValidation(`\"${raw}\": \":${raw.slice(colon + 1)}\" is not a match type (EXACT | PHRASE | BROAD)`);\n }\n if (!defaultMatch) {\n failWriteValidation(`\"${raw}\" has no match type — add a :EXACT/:PHRASE/:BROAD suffix or pass --match-type`);\n }\n return { text: raw, matchType: defaultMatch };\n}\n\n/**\n * Raw --text value(s) → individual entries: repeated flags and comma-separated\n * both work. The repeats have to come off `rawArgs`, because citty parses a\n * repeated flag down to its last value alone.\n */\nfunction rawTextEntries(value: unknown, rawArgs: readonly string[] | undefined): string[] {\n return repeatedValues(rawArgs, \"text\", value)\n .flatMap((v) => v.split(\",\"))\n .map((v) => v.trim())\n .filter(Boolean);\n}\n\n/** Newline-separated keyword file: one `text[:MATCH_TYPE]` per line; blank lines and `#` comments skipped. */\nfunction rawFileEntries(path: unknown): string[] {\n return typeof path === \"string\" && path.length > 0 ? fileLines(path) : [];\n}\n\n/** A text file's entries: one per line, trimmed; blank lines and `#` comments skipped. */\nexport function fileLines(path: string): string[] {\n return readFileSync(path, \"utf8\")\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0 && !line.startsWith(\"#\"));\n}\n\n/**\n * The keyword batch a command was invoked with: comma-separated `--text` entries\n * (optional `:MATCH_TYPE` suffix each) plus `--file` lines, deduped, each falling\n * back to `--match-type`. One entry stages exactly like before; many stage as one batch.\n */\nexport function keywordEntries(args: Record<string, unknown>, rawArgs?: readonly string[]): KeywordEntry[] {\n const defaultMatch = typeof args[\"match-type\"] === \"string\" ? args[\"match-type\"].toUpperCase() : undefined;\n const raw = [...rawTextEntries(args.text, rawArgs), ...rawFileEntries(args.file)];\n if (raw.length === 0) {\n failWriteValidation(\"pass keywords via --text (comma-separated) and/or --file (one per line)\");\n }\n if (raw.length > GOOGLE_DRAFT_BATCH_MAX) {\n failWriteValidation(`${raw.length} keywords exceeds the batch limit of ${GOOGLE_DRAFT_BATCH_MAX}`);\n }\n const entries: KeywordEntry[] = [];\n const seen = new Set<string>();\n for (const item of raw) {\n const entry = parseKeywordEntry(item, defaultMatch);\n const key = JSON.stringify([entry.text, entry.matchType]);\n if (!seen.has(key)) {\n seen.add(key);\n entries.push(entry);\n }\n }\n return entries;\n}\n\n/**\n * The payloads behind `--file`: a path to a JSON file, or the JSON written inline. The file holds one\n * payload object, a JSON array of them, or JSON Lines (one object per line) — many payloads stage as\n * one batch, which is how a bulk change lands in one call instead of hundreds.\n *\n * Inline is here because every doc example already writes it that way — `packages/cli/README.md`\n * and the scaffold's `ads-google.md` both show `--file '{\"type\":\"image\",…}'` — while the arg only\n * ever read a path, so following the documentation answered with a raw ENOENT stack trace. Reading\n * a leading `{` or `[` as the payload makes those examples true rather than making the agent re-learn\n * the one shape that works.\n */\nexport function loadJsonPayloads(path: unknown): Array<Record<string, unknown>> {\n if (typeof path !== \"string\" || path.length === 0) {\n return [];\n }\n const inline = /^\\s*[[{]/.test(path);\n const source = inline ? \"inline JSON\" : path;\n const text = inline ? path : readFileSync(path, \"utf8\");\n return parsedPayloads(text, source).map((item, index, all) => {\n if (item === null || typeof item !== \"object\" || Array.isArray(item)) {\n failWriteValidation(\n all.length === 1 ? `${source} must contain a JSON object` : `${source}: item ${index} must be a JSON object`,\n );\n }\n return item as Record<string, unknown>;\n });\n}\n\n/** One JSON value (an array spreads into its items), else JSON Lines; the JSON error when neither parses. */\nfunction parsedPayloads(text: string, source: string): unknown[] {\n try {\n const parsed = JSON.parse(text) as unknown;\n return Array.isArray(parsed) ? parsed : [parsed];\n } catch (err) {\n if (!(err instanceof SyntaxError)) {\n throw err;\n }\n const lines = text.split(/\\r?\\n/).filter((line) => line.trim().length > 0);\n if (lines.length > 1) {\n return lines.map((line, index) => parseJsonLine(line, index, source));\n }\n failWriteValidation(`${source} is not valid JSON: ${err.message}`);\n }\n}\n\n/** One JSON Lines entry, or the line's own error naming where it is. */\nfunction parseJsonLine(line: string, index: number, source: string): unknown {\n try {\n return JSON.parse(line) as unknown;\n } catch (err) {\n return failWriteValidation(\n `${source} line ${index + 1} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\n/** The ONE op payload behind `--file`, for commands that change a single entity. */\nexport function loadJsonFileArg(path: unknown): Record<string, unknown> {\n const payloads = loadJsonPayloads(path);\n if (payloads.length > 1) {\n failWriteValidation(\n `this command changes one entity, and --file holds ${payloads.length} payloads — stage many changes from one file with \\`baker ads google draft stage --file\\` (one op per item: {\"kind\",\"customerId\",\"target\"?,\"payload\"?})`,\n );\n }\n return payloads[0] ?? {};\n}\n\n/** Flags override file keys — the file is the base, flags are the overrides. */\nexport function mergePayload(file: Record<string, unknown>, flags: Record<string, unknown>): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...file };\n for (const [key, value] of Object.entries(flags)) {\n if (value !== undefined) {\n merged[key] = value;\n }\n }\n return merged;\n}\n\n/**\n * The `draft amend` patch: exactly one of `--file <path>` (JSON file) or `--patch '<json>'`\n * (inline string), and it must parse to a JSON object — RFC-7386 merge-patch needs an object to\n * merge, and a stray array/scalar would silently no-op or replace the whole payload.\n */\nexport function loadPatchArg(args: Record<string, unknown>): Record<string, unknown> {\n const file = typeof args.file === \"string\" && args.file.length > 0 ? args.file : undefined;\n const inline = typeof args.patch === \"string\" && args.patch.length > 0 ? args.patch : undefined;\n if (Boolean(file) === Boolean(inline)) {\n failWriteValidation(\"pass exactly one of --file <patch.json> or --patch '<json>'\");\n }\n if (file) {\n return loadJsonFileArg(file);\n }\n try {\n const parsed = JSON.parse(inline as string) as unknown;\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n failWriteValidation(\"--patch must be a JSON object\");\n }\n return parsed as Record<string, unknown>;\n } catch (err) {\n if (err instanceof SyntaxError) {\n failWriteValidation(`--patch is not valid JSON: ${err.message}`);\n }\n throw err;\n }\n}\n\nexport function handleGoogleError(err: unknown): never {\n if (err instanceof ApiError) {\n // Covers both \"no connection\" and staging's 403 for an account this company\n // never connected — same remedy either way: connect, and pick the account.\n if (isNotConnectedError(err.code, err.message)) {\n handleConnectionError(\"google_ads\", err.message);\n }\n const terms = termsRefusalFix(err.code, err.message);\n if (terms) {\n writeJsonEnvelope({\n ok: false,\n error: { code: terms.code, message: err.message, retryable: false, fix: terms.fix },\n });\n process.exit(1);\n }\n if (err.message.includes(OP_TOO_LARGE_MESSAGE_START)) {\n writeJsonEnvelope({\n ok: false,\n error: {\n code: \"OP_TOO_LARGE\",\n message: err.message,\n retryable: false,\n fix: { action: \"split_the_change\", explanation: OP_TOO_LARGE_FIX },\n },\n });\n process.exit(1);\n }\n writeJsonEnvelope({ ok: false, error: { code: err.code ?? \"API_ERROR\", message: err.message } });\n process.exit(1);\n }\n writeJsonEnvelope({\n ok: false,\n error: { code: \"UNKNOWN\", message: err instanceof Error ? err.message : String(err) },\n });\n process.exit(1);\n}\n\ninterface StageEnvelope extends Record<string, unknown> {\n ok: true;\n data: GoogleDraftStageResponse;\n}\n\n/**\n * A no-op response isn't a failure — the change was already in place, so nothing was\n * staged. Say so explicitly, otherwise the agent re-stages it or reports work it\n * didn't do.\n */\nfunction noopHints(data: GoogleDraftStageResponse): string[] {\n return data.staged\n ? []\n : [`NOT STAGED — ${data.reason}. Nothing to publish for this change; say so rather than reporting it as done.`];\n}\n\n/**\n * What to tell the agent about the ops a batch didn't stage.\n *\n * Two different things land in `skipped`: a change already in place, and a change Google refuses\n * outright (editing an experiment campaign's status, dates or budget). This hint used to assert the\n * first — \"already in the requested state\" — which read as \"done\" for a refusal the user never heard\n * about. So it leads with each op's own reason and asks for the refusals to be passed on.\n */\nexport function skippedHints(skipped: Array<{ summary: string; reason: string }>, total: number): string[] {\n if (skipped.length === 0) {\n return [];\n }\n const detail = skipped.map((s) => `${s.summary} — ${s.reason}`).join(\"; \");\n return [\n `${skipped.length} of ${total} op(s) NOT STAGED: ${detail}. Don't re-stage them; tell the user which changes couldn't be made and why, then carry on with the rest.`,\n ];\n}\n\n/**\n * Preflight-validates the op against the shared `@baker/api/ads-google`\n * contract (the same schema the backend enforces), then stages it. Prints the\n * staged envelope — ref, mode (always `live`: publishing reaches the real\n * account), summary, warnings.\n */\nexport async function stageGoogleOp(raw: Record<string, unknown>, hints?: string[]): Promise<void> {\n const preflight = googleDraftOpInputSchema.safeParse(raw);\n if (!preflight.success) {\n const fields = preflight.error.issues.map((issue) => ({ path: issue.path.join(\".\"), message: issue.message }));\n writeJsonEnvelope({\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: fields.map((f) => (f.path ? `${f.path}: ${f.message}` : f.message)).join(\"; \"),\n fields,\n fix: copyListCountFix(raw, preflight.error.issues) ?? payloadFix(\"google-ads\", googleDraftOpInputSchema, raw),\n },\n });\n process.exit(1);\n }\n try {\n const chatId = requireChatId();\n const response = await apiPost<StageEnvelope>(\"/api/ads/google/draft/stage\", { chatId, op: preflight.data });\n const allHints = [\n ...noopHints(response.data),\n ...recordSingleStage(chatId, preflight.data.kind),\n ...recordTreeStage(chatId, response.data),\n ...(hints ?? []),\n ...(await adCopyHints(preflight.data)),\n ];\n writeJsonEnvelope(withHints(response, allHints));\n } catch (err) {\n handleGoogleError(err);\n }\n}\n\n/** Stage a create op: `{ kind, customerId, payload }`. */\nexport async function stageCreate(\n kind: string,\n customerId: string,\n payload: Record<string, unknown>,\n hints?: string[],\n): Promise<void> {\n await stageGoogleOp({ kind, customerId, payload }, hints);\n}\n\ninterface StageBatchEnvelope extends Record<string, unknown> {\n ok: true;\n data: GoogleDraftStageBatchResponse;\n}\n\n/**\n * A batch reads every target's before-state and checks each op against the account, which for a few\n * hundred removals outlasts the default 60 s. Timing out early reported a batch as failed that went on\n * to stage, so a retry then collided with the ops it had already staged.\n */\nconst STAGE_BATCH_TIMEOUT_MS = 5 * 60_000;\n\n/** `--full` on every command that stages a batch: the compact result lists only the ops that need a look. */\nexport const STAGE_FULL_ARG = {\n type: \"boolean\",\n description:\n \"List every staged op with its ref and summary (default: counts, the `as` → ref names, and only the ops with warnings)\",\n} as const;\n\n/**\n * What a batch stage prints by default: counts by kind, the ref each `\"as\"` name became (later calls\n * name the ref), and only the ops that carry a warning. A batch of 384 negatives printed one object\n * per op — 85 KB of the agent's own input echoed back with `\"warnings\": []` — so agents cut it with\n * `head`, which also cuts a late op's warning and the hints (BAKER-4005, BAKER-3464).\n */\nfunction stageBatchView(\n data: GoogleDraftStageBatchResponse,\n full: boolean,\n): GoogleDraftStageBatchResponse & { byKind?: Record<string, number>; refs?: Record<string, string> } {\n if (full) {\n return data;\n }\n const { ops, ...rest } = data;\n const byKind: Record<string, number> = {};\n const refs: Record<string, string> = {};\n for (const op of ops) {\n byKind[op.kind] = (byKind[op.kind] ?? 0) + 1;\n if (op.as) refs[op.as] = op.ref;\n }\n return {\n ...rest,\n byKind,\n ...(Object.keys(refs).length > 0 ? { refs } : {}),\n ops: ops.filter((op) => op.warnings.length > 0),\n };\n}\n\n/**\n * Stage several ops as ONE request (`/stage-batch`) — all-or-nothing on the backend,\n * one rate-limit hit instead of one per keyword. A single op falls through to the\n * plain stage path so its envelope (and amend behavior) stays exactly as before.\n * Prints `stageBatchView`: compact unless `full`.\n */\nexport async function stageGoogleOps(\n rawOps: Array<Record<string, unknown>>,\n hints?: string[],\n full = false,\n): Promise<void> {\n if (rawOps.length === 1 && rawOps[0]) {\n await stageGoogleOp(rawOps[0], hints);\n return;\n }\n const ops: unknown[] = [];\n for (const [index, raw] of rawOps.entries()) {\n const preflight = googleDraftBatchOpSchema.safeParse(raw);\n if (!preflight.success) {\n const fields = preflight.error.issues.map((issue) => ({\n path: `ops[${index}].${issue.path.join(\".\")}`,\n message: issue.message,\n }));\n writeJsonEnvelope({\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: fields.map((f) => `${f.path}: ${f.message}`).join(\"; \"),\n fields,\n fix: copyListCountFix(raw, preflight.error.issues) ?? payloadFix(\"google-ads\", googleDraftOpInputSchema, raw),\n },\n });\n process.exit(1);\n }\n ops.push(preflight.data);\n }\n try {\n const chatId = requireChatId();\n const response = await apiPost<StageBatchEnvelope>(\n \"/api/ads/google/draft/stage-batch\",\n { chatId, ops },\n { timeoutMs: STAGE_BATCH_TIMEOUT_MS },\n );\n const view = stageBatchView(response.data, full);\n const omitted = response.data.ops.length - view.ops.length;\n const allHints = [\n ...skippedHints(response.data.skipped ?? [], ops.length),\n ...(omitted > 0\n ? [\n `${omitted} staged ops without a warning are left out. They are already staged — do not stage them again; read their refs with \\`baker ads google draft list --json\\` (pass --full on a later stage to print every op).`,\n ]\n : []),\n ...(hints ?? []),\n ...(await adCopyHints(ops)),\n ];\n writeJsonEnvelope(withHints({ ...response, data: view }, allHints));\n } catch (err) {\n handleGoogleError(err);\n }\n}\n\n/** Stage an update op: `{ kind, customerId, target, payload }`. */\nexport async function stageUpdate(\n kind: string,\n customerId: string,\n target: string,\n payload: Record<string, unknown>,\n hints?: string[],\n): Promise<void> {\n await stageGoogleOp({ kind, customerId, target, payload }, hints);\n}\n\n/** Stage a target-only op (pause/resume/remove/detach): `{ kind, customerId, target }`. */\nexport async function stageTarget(kind: string, customerId: string, target: string, hints?: string[]): Promise<void> {\n await stageGoogleOp({ kind, customerId, target }, hints);\n}\n\nexport async function draftAction(path: string, body: Record<string, unknown>, chat?: unknown): Promise<void> {\n try {\n const chatId = resolveChatId(chat);\n const response = await apiPost<Record<string, unknown>>(path, { chatId, ...body });\n writeJsonEnvelope(response);\n } catch (err) {\n handleGoogleError(err);\n }\n}\n\ninterface DraftListEnvelope extends Record<string, unknown> {\n ok: boolean;\n data?: GoogleDraftListResponse;\n}\n\n/**\n * List the staged draft. By default renders a readable campaign ▸ ad group ▸ ad status tree so the\n * agent can review everything it has staged at a glance; `--json` returns the raw envelope for tools,\n * and `--full` that envelope with every op's payload.\n */\nexport async function draftListAction(\n json: boolean,\n chat?: unknown,\n full = false,\n customerId?: string,\n selected?: { where: DraftWhere; selector: string },\n): Promise<void> {\n try {\n const chatId = resolveChatId(chat);\n const listed = await apiPost<DraftListEnvelope>(\"/api/ads/google/draft\", {\n chatId,\n ...(full || selected ? { full: true } : {}),\n });\n const inAccount =\n customerId !== undefined && listed.ok && listed.data ? draftInAccount(listed.data, customerId) : undefined;\n const response = inAccount ? withHints({ ...listed, data: inAccount.data }, inAccount.hints) : listed;\n if (selected && response.ok && response.data) {\n const narrowed = draftListWhere(response.data, selected.where, selected.selector);\n writeJsonEnvelope(withHints({ ...response, data: narrowed.data }, narrowed.hints));\n return;\n }\n if (json || full || !response.ok || !response.data) {\n const whole =\n response.ok && response.data\n ? wholeDraftHints(response.data.ops, \"baker ads google draft list\", \"google.\")\n : [];\n writeJsonEnvelope(withHints(response, whole));\n return;\n }\n process.stdout.write(`${inAccount?.empty ?? renderDraftStatus(response.data)}${hintLines(response)}\\n`);\n } catch (err) {\n handleGoogleError(err);\n }\n}\n\nexport const customerIdArg = {\n \"customer-id\": { type: \"string\" as const, description: \"10-digit Google Ads customer id\" },\n};\n/** The entity a command changes, read by position the way `requireTarget` reads it — declared so --help shows it. */\nexport function targetArg(entity: string) {\n return {\n id: {\n type: \"positional\" as const,\n description: `The ${entity} to change: its id or resource name (customers/…)`,\n required: false,\n },\n };\n}\n\nconst PAYLOAD_FIELDS = \"run `baker schema` on this command for every field the payload takes\";\n\nfunction payloadShape(kind: string): () => PayloadSource {\n return () => ({ union: googleDraftOpInputSchema, kind });\n}\n\n/** `--file` for a command that stages one `kind` op; `baker schema` prints that op's payload shape. */\nexport function fileArg(kind: string) {\n return {\n file: payloadArg(\n {\n type: \"string\" as const,\n description: `The op payload: a JSON file path, or the JSON object inline (flags override it) — ${PAYLOAD_FIELDS}`,\n },\n payloadShape(kind),\n ),\n };\n}\n\n/** `--file` that stages one or many `kind` ops; `baker schema` prints that op's payload shape. */\nexport function fileBatchArg(kind: string) {\n return {\n file: payloadArg(\n {\n type: \"string\" as const,\n description: `The op payload: a JSON file path or inline JSON — one object, or a JSON array / JSON Lines of objects to stage many in one call (up to 500) — ${PAYLOAD_FIELDS}`,\n },\n payloadShape(kind),\n ),\n };\n}\n\n/** A create command whose payload is a JSON file or inline JSON — one object or an array staged as one batch. */\nexport function fileCreateCommand(\n name: string,\n kind: GoogleDraftOpKind,\n description: string,\n hints?: string[] | ((payload: Record<string, unknown>) => string[]),\n) {\n return withEffect(\n googleStagedBatch(kind),\n defineCommand({\n meta: { name, description },\n args: { ...customerIdArg, ...fileBatchArg(kind), full: STAGE_FULL_ARG },\n run: async ({ args }) => {\n const customerId = requireCustomerId(args);\n const payloads = loadJsonPayloads(args.file);\n if (payloads.length === 0 || payloads.some((payload) => Object.keys(payload).length === 0)) {\n failWriteValidation(`${kind} needs --file with the op payload (one object, or a JSON array to stage many)`);\n }\n if (payloads.length > GOOGLE_DRAFT_BATCH_MAX) {\n failWriteValidation(\n `${payloads.length} payloads exceeds the batch limit of ${GOOGLE_DRAFT_BATCH_MAX} — split the file`,\n );\n }\n const payloadHints = [\n ...new Set(payloads.flatMap((payload) => (typeof hints === \"function\" ? hints(payload) : (hints ?? [])))),\n ];\n await stageGoogleOps(\n payloads.map((payload) => ({ kind, customerId, payload })),\n payloadHints,\n args.full === true,\n );\n },\n }),\n );\n}\n\n/**\n * `--bid-modifier` as a number, validated against the range Google actually accepts.\n *\n * Rejecting the (0, 0.1) gap here rather than at the backend is the point: 0 and 0.1 are a hundredth\n * apart in value and mean \"never serve\" versus \"bid a tenth\", so a typo between them is a real spend\n * decision, and the error should arrive before anything is staged.\n */\nexport function bidModifierFlag(value: unknown): number {\n if (value === undefined || value === null || value === \"\") {\n failWriteValidation(\n \"--bid-modifier is required: 1 for no adjustment, 1.25 to bid 25% more, 0.9 to bid 10% less, 0 to stop serving on a device\",\n );\n }\n const num = Number(value);\n if (Number.isNaN(num) || num < 0 || num > 10 || (num > 0 && num < 0.1)) {\n failWriteValidation(\"--bid-modifier must be 0 (stop serving on it) or between 0.1 and 10.0\");\n }\n return num;\n}\n","import type { z } from \"zod\";\n\n/** Appended to each copy flag's help, so `--help` and `baker schema` say how to pass a comma. */\nexport const AD_COPY_LIST_USAGE =\n \"repeat the flag once per item, or pass one comma-separated list and wrap an item that contains a comma in double quotes: '\\\"Fast, free quotes\\\",Book today'. A flag given once is read as a list, so a lone item with a comma needs its double quotes too: '\\\"Fast, free quotes\\\"'\";\n\n/** The op's copy-list fields, by the flag an agent passes them with. */\nconst COPY_LIST_FLAG: Readonly<Record<string, string>> = {\n headlines: \"--headlines\",\n descriptions: \"--descriptions\",\n longHeadlines: \"--long-headlines\",\n};\n\ninterface CountRefusal {\n flag: string;\n count: number | undefined;\n bound: string;\n tooMany: boolean;\n}\n\nfunction valueAt(root: unknown, path: readonly PropertyKey[]): unknown {\n let node = root;\n for (const key of path) {\n if (node === null || typeof node !== \"object\") return undefined;\n node = (node as Record<PropertyKey, unknown>)[key];\n }\n return node;\n}\n\nfunction countRefusal(op: unknown, issue: z.core.$ZodIssue): CountRefusal | undefined {\n if ((issue.code !== \"too_big\" && issue.code !== \"too_small\") || issue.origin !== \"array\") return undefined;\n const flag = COPY_LIST_FLAG[String(issue.path.at(-1))];\n if (!flag) return undefined;\n const value = valueAt(op, issue.path);\n const count = Array.isArray(value) ? value.length : undefined;\n return issue.code === \"too_big\"\n ? { flag, count, bound: `at most ${issue.maximum}`, tooMany: true }\n : { flag, count, bound: `at least ${issue.minimum}`, tooMany: false };\n}\n\n/**\n * The fix for a stage refused only for how many headlines, descriptions or long headlines it has.\n *\n * That is a limit on a field the agent named correctly, so the generic \"read `baker capabilities`,\n * do not guess another field name\" sent it through draft list, schema and --help before it saw the\n * cause. Too many items is usually copy cut at its commas — a flag given once is a comma-separated\n * list, so \"Rated 4,5/5\" becomes two items — which is why that case names the forms that keep a\n * comma. Undefined when anything else was refused too, so the capabilities pointer still covers it.\n */\nexport function copyListCountFix(\n op: unknown,\n issues: readonly z.core.$ZodIssue[],\n): { action: string; explanation: string } | undefined {\n const refusals = issues.map((issue) => countRefusal(op, issue));\n if (refusals.length === 0 || refusals.some((refusal) => refusal === undefined)) return undefined;\n const counted = refusals.filter((refusal): refusal is CountRefusal => refusal !== undefined);\n const limits = counted\n .map(({ flag, count, bound }) => `${flag} has ${count ?? \"the wrong number of\"} items; this ad takes ${bound}.`)\n .join(\" \");\n const commaCause = counted.some((refusal) => refusal.tooMany)\n ? ' If you meant fewer items, the copy was cut at its commas: a flag given once is read as a comma-separated list, so an item with a comma in it (\"Fast, free quotes\", a decimal like \"4,5/5\") becomes two. To keep a comma, ' +\n `${AD_COPY_LIST_USAGE} — or put the content in --file as JSON.`\n : \"\";\n return {\n action: \"fix_copy_list_count\",\n explanation: `${limits}${commaCause} ${commaCause ? \"Otherwise add\" : \"Add\"} or drop items to fit the limit, then stage again; the field names are right.`,\n };\n}\n","import type {\n GoogleDraftListResponse,\n GoogleDraftStatusCollection,\n GoogleDraftStatusNode,\n} from \"@baker/api/ads-google\";\n\n/**\n * Render the staged Google Ads draft as a readable campaign ▸ ad group ▸ ad tree — the CLI\n * counterpart to the dashboard's Google Ads tab, so an agent can review everything it has staged\n * with one command instead of reading raw JSON. Pure: takes the draft-list response, returns text.\n */\n\nconst OPERATION_LABELS: Record<string, string> = {\n create: \"Creating\",\n update: \"Updating\",\n pause: \"Pausing\",\n resume: \"Resuming\",\n remove: \"Removing\",\n upload: \"Uploading\",\n};\n\n/** The same verbs once the publish has run: a published draft reports what happened, not what is staged. */\nconst APPLIED_LABELS: Record<string, string> = {\n create: \"Created\",\n update: \"Updated\",\n pause: \"Paused\",\n resume: \"Resumed\",\n remove: \"Removed\",\n upload: \"Uploaded\",\n};\n\n/** Folded changes that did not land (\"1 change failed\", \"2 changes skipped\"), named beside the node's own outcome. */\nfunction notAppliedText(node: GoogleDraftStatusNode): string | undefined {\n const { failed = 0, skipped = 0 } = node.foldedNotApplied ?? {};\n const changes = (n: number) => `${n} change${n === 1 ? \"\" : \"s\"}`;\n const parts = [\n ...(failed > 0 ? [`${changes(failed)} failed`] : []),\n ...(skipped > 0 ? [`${changes(skipped)} skipped`] : []),\n ];\n return parts.length > 0 ? parts.join(\", \") : undefined;\n}\n\nfunction outcomeBadge(node: GoogleDraftStatusNode, result: NonNullable<GoogleDraftStatusNode[\"result\"]>): string {\n const verb = node.operation ?? \"update\";\n if (result === \"applied\") {\n return node.operation ? (APPLIED_LABELS[verb] ?? \"Applied\") : \"Changes applied\";\n }\n if (result === \"simulated\") {\n return `Simulated (${verb})`;\n }\n if (result === \"failed\") {\n return node.operation ? `Failed to ${verb}` : \"Failed\";\n }\n return \"Skipped\";\n}\n\nfunction badge(node: GoogleDraftStatusNode): string {\n const label = node.result\n ? outcomeBadge(node, node.result)\n : ((node.operation ? OPERATION_LABELS[node.operation] : undefined) ?? (node.existing ? \"on Google Ads\" : \"staged\"));\n const parts = [label, ...(node.status && node.status !== label ? [node.status] : [])];\n const notApplied = notAppliedText(node);\n return [...parts, ...(notApplied ? [notApplied] : [])].join(\" · \");\n}\n\nfunction collectionLine(collection: GoogleDraftStatusCollection): string | undefined {\n const parts: string[] = [];\n if (collection.added > 0) {\n parts.push(`+${collection.added}`);\n }\n if (collection.existing > 0) {\n parts.push(`${collection.existing} existing`);\n }\n if (collection.removed > 0) {\n parts.push(`-${collection.removed}`);\n }\n // Neither an add nor a remove — a member that stays in the set with a changed value (a device's\n // bid adjustment). Left out, a draft whose only criterion change is one printed no line at all.\n if ((collection.updated ?? 0) > 0) {\n parts.push(`~${collection.updated}`);\n }\n return parts.length > 0 ? `${collection.label}: ${parts.join(\", \")}` : undefined;\n}\n\n/**\n * Every advertiser account the tree touches. A draft may legitimately span\n * several, and a criterion id is derived from the keyword's text and match type\n * — so the same keyword carries the same id in every account. The account is\n * printed on each node once there is more than one, and left off when there is not.\n */\nfunction accountsInTree(nodes: readonly GoogleDraftStatusNode[]): Set<string> {\n const accounts = new Set<string>();\n const walk = (node: GoogleDraftStatusNode): void => {\n accounts.add(node.customerId);\n for (const child of node.children) {\n walk(child);\n }\n };\n for (const node of nodes) {\n walk(node);\n }\n return accounts;\n}\n\nfunction renderNode(node: GoogleDraftStatusNode, depth: number, lines: string[], showAccount: boolean): void {\n const indent = \" \".repeat(depth);\n const account = showAccount ? ` · account ${node.customerId}` : \"\";\n const ref = node.ref ? ` · ${node.ref}` : \"\";\n lines.push(`${indent}• ${node.name} · ${badge(node)}${account}${ref}`);\n for (const warning of node.warnings ?? []) {\n lines.push(`${indent} ⚠ ${warning}`);\n }\n for (const folded of node.folded ?? []) {\n lines.push(`${indent} ${folded.summary} · ${folded.ref}`);\n }\n for (const collection of node.collections) {\n const line = collectionLine(collection);\n if (line) {\n lines.push(`${indent} ${line}`);\n }\n }\n for (const child of node.children) {\n renderNode(child, depth + 1, lines, showAccount);\n }\n}\n\nconst RESOURCE_ENTITIES = new Set([\n \"sharedSet\",\n \"biddingStrategy\",\n \"audience\",\n \"conversionAction\",\n \"label\",\n \"budget\",\n \"asset\",\n]);\n\nfunction renderSection(title: string, nodes: GoogleDraftStatusNode[], lines: string[], showAccount: boolean): void {\n if (nodes.length === 0) {\n return;\n }\n lines.push(\"\");\n lines.push(title);\n for (const node of nodes) {\n renderNode(node, 1, lines, showAccount);\n }\n}\n\nfunction renderAdvisories(data: GoogleDraftListResponse, lines: string[]): void {\n const advisories = data.advisories ?? [];\n // Every advisory is phrased as something to settle BEFORE publishing. On a published draft there\n // is nothing left to settle here, and printing them reads as work still outstanding on this chat.\n if (advisories.length === 0 || data.status === \"applied\") {\n return;\n }\n lines.push(\"\");\n // Two kinds of finding share this block: build-out nudges (\"this ad group has one ad\") and\n // whole-draft coherence findings (\"this campaign will report zero conversions\", \"two of your\n // campaigns bid on the same keyword\"). The coherence ones come first and cost money, so the\n // heading no longer frames the block as optional polish.\n lines.push(\"Advisories (non-blocking, checked across the whole draft — settle these before you publish)\");\n for (const advisory of advisories) {\n lines.push(` • ${advisory.message}`);\n }\n}\n\n/**\n * What the publish did, once there is a publish to report.\n *\n * A published Google Ads draft rendered exactly like a staged one — same count, every op still\n * reading \"Creating\" — so the surface `.claude/rules/cli-env.md` sends an agent to for the outcome\n * could not answer, and a failed op was invisible in the human output while sitting in the JSON\n * envelope the whole time. Found by publishing a BUSINESS_LOGO link that Google refused with\n * \"Customer is not verified\": the draft still read \"4 staged changes\". LinkedIn fixed the same\n * shape first; this is its counterpart.\n */\nfunction renderOutcome(data: GoogleDraftListResponse, lines: string[]): void {\n const counts = new Map<string, number>();\n for (const op of data.ops) {\n const status = op.result?.status ?? \"pending\";\n counts.set(status, (counts.get(status) ?? 0) + 1);\n }\n const summary = [...counts].map(([status, count]) => `${count} ${status}`).join(\", \");\n lines.push(`Google Ads — published · ${summary || `${data.count} op(s)`} · ${data.mode}`);\n // A failure is the reason to read this at all, so it is named with its error rather than left as\n // a number to go and look up.\n for (const op of data.ops) {\n const status = op.result?.status;\n if (status !== \"failed\" && status !== \"skipped\") {\n continue;\n }\n const reason = op.result?.error ?? op.result?.skippedBecause ?? \"no reason recorded\";\n lines.push(` ✗ ${op.summary} — ${status}: ${reason}`);\n }\n // Google answers \"applied\" to a field it accepted and never stored (a portfolio's bid ceiling),\n // so the read-back after publish is the only thing that knows the change did not land as sent.\n for (const op of data.ops) {\n const verification = op.result?.verification;\n if (op.result?.status === \"applied\" && verification?.status === \"drifted\") {\n lines.push(` ⚠ ${op.summary} — not as sent: ${verification.note ?? \"Google Ads shows something else\"}`);\n }\n }\n}\n\nexport function renderDraftStatus(data: GoogleDraftListResponse): string {\n if (data.status === \"none\" || data.count === 0) {\n return \"No staged Google Ads changes on this chat.\";\n }\n const modeNote =\n data.mode === \"live\"\n ? \"Live — publishing writes directly to Google Ads.\"\n : \"Simulated — publishing completes the whole draft without calling Google Ads.\";\n const lines: string[] = [];\n if (data.status === \"applied\") {\n renderOutcome(data, lines);\n } else if (data.status === \"publishing\") {\n lines.push(`Google Ads — publishing ${data.count} change${data.count === 1 ? \"\" : \"s\"} · ${data.mode}`);\n } else {\n lines.push(`Google Ads — ${data.count} staged change${data.count === 1 ? \"\" : \"s\"} · ${data.mode}`);\n }\n lines.push(modeNote);\n\n const tree = data.tree ?? [];\n const showAccount = accountsInTree(tree).size > 1;\n renderSection(\n \"Shared resources\",\n tree.filter((node) => RESOURCE_ENTITIES.has(node.entity)),\n lines,\n showAccount,\n );\n renderSection(\n \"Campaigns\",\n tree.filter((node) => node.entity === \"campaign\"),\n lines,\n showAccount,\n );\n const rest = tree.filter((node) => !RESOURCE_ENTITIES.has(node.entity) && node.entity !== \"campaign\");\n renderSection(\"Other\", rest, lines, showAccount);\n renderAdvisories(data, lines);\n\n return lines.join(\"\\n\");\n}\n","import { type GoogleDraftStageResponse, isCreateKind } from \"@baker/api/ads-google\";\nimport { cacheGet, cacheSet } from \"../cache.ts\";\nimport { loopWarnings } from \"../output.ts\";\n\n/**\n * Bulk work done as a loop of single commands — one `keywords update` per keyword, one\n * `negative-keywords remove` per term — is one request, one rate-limit hit and one tool call per row;\n * production saw 1,284 of them. The CLI cannot see the loop from inside one call, so it remembers the\n * last few single stages per chat and, once the same kind repeats, says how to do the rest in one call.\n */\n\nexport interface StageStreak {\n kind: string;\n count: number;\n lastAt: number;\n}\n\n/** Singles further apart than this are separate decisions, not a loop. */\nconst STREAK_WINDOW_MS = 5 * 60_000;\n/** The streak length that reads as a loop. */\nconst STREAK_THRESHOLD = 5;\n\nexport function nextStageStreak(previous: StageStreak | undefined, kind: string, now: number): StageStreak {\n const continues = previous && previous.kind === kind && now - previous.lastAt <= STREAK_WINDOW_MS;\n return { kind, count: continues ? previous.count + 1 : 1, lastAt: now };\n}\n\n/** The one-call form of a kind, where a command has one beside `draft stage --file`. */\nconst BATCH_FORMS: Record<string, string> = {\n \"google.keyword.add\": \"`keywords add --file keywords.txt` (one term[:MATCH_TYPE] per line)\",\n \"google.keyword.update\":\n \"`keywords pause|resume <resource name> <resource name>…` (or --file, one per line) for status\",\n \"google.keyword.remove\": \"`draft stage --file` with one google.keyword.remove per target\",\n \"google.negativeKeyword.add\":\n \"`negative-keywords add --ad-group-id <id>,<id> --file terms.txt` (every term on every ad group)\",\n \"google.sharedSetMember.add\": \"`keyword-lists add --file terms.txt`\",\n \"google.sharedSetMember.remove\": '`keyword-lists remove --list-ref <id> --text \"a,b,c\"`',\n};\n\nexport function stageStreakHints(streak: StageStreak): string[] {\n if (streak.count < STREAK_THRESHOLD) {\n return [];\n }\n const form = BATCH_FORMS[streak.kind];\n return [\n `LOOP: that is ${streak.count} ${streak.kind} ops staged one command at a time. Stop looping — put every remaining change in one file and stage them in ONE call: \\`baker ads google draft stage --file ops.json --customer-id <id>\\` (a JSON array of {\"kind\",\"target\"?,\"payload\"?}, up to 500, any mix of kinds)${form ? `, or ${form}` : \"\"}. Fix staged ops together with \\`draft amend --file\\`.`,\n ];\n}\n\nconst STREAK_CACHE = \"stage-streak\";\n\n/** Record one single stage on this chat and return the nudge it earns, if any. Never throws. */\nexport function recordSingleStage(chatId: string, kind: string): string[] {\n try {\n const streak = nextStageStreak(cacheGet<StageStreak>(STREAK_CACHE, chatId)?.data, kind, Date.now());\n cacheSet(STREAK_CACHE, chatId, streak, STREAK_WINDOW_MS);\n const hints = stageStreakHints(streak);\n // Also on stderr: agents pipe each stage through a filter that keeps only `ok`, which drops the\n // hint from the JSON — 26 times in one Session. stderr reaches the agent past any such filter.\n for (const hint of hints) process.stderr.write(`${hint}\\n`);\n return hints;\n } catch {\n return [];\n }\n}\n\nconst TREE_CACHE = \"stage-tree\";\n\n/**\n * A single create (not an update merged into a staged one) that depends on a create staged earlier in this chat is a new campaign tree being\n * built one level at a time. Each level changes kind, so the LOOP streak never fires; this says once\n * per chat (per window) how to stage the rest in one call. Never throws.\n */\nexport function recordTreeStage(chatId: string, staged: GoogleDraftStageResponse): string[] {\n try {\n if (!staged.staged || staged.amended || !isCreateKind(staged.kind) || staged.dependsOn.length === 0) {\n return [];\n }\n if (cacheGet<boolean>(TREE_CACHE, chatId)?.data) {\n return [];\n }\n cacheSet(TREE_CACHE, chatId, true, STREAK_WINDOW_MS);\n return loopWarnings([\n `TREE: this ${staged.kind} hangs off a create staged earlier in this chat — a new campaign tree built one command per entity. Stage everything still to build (ad groups, keywords, ads, assets and their links) in ONE call: \\`baker ads google draft stage --file ops.json --customer-id <id>\\`, giving each create a name with \"as\": \"g_temp_<name>\" so later ops in the same file can point at it (refs staged earlier still work).`,\n ]);\n } catch {\n return [];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,SAAS,QAAQ,GAAW,QAAyB;AACnD,QAAM,OAAO,SAAS,kBAAkB;AACxC,SAAO,MAAM,IAAI,KAAK,IAAI,KAAK,GAAG,CAAC,IAAI,IAAI;AAC7C;AAOO,SAAS,eACd,MACA,YACoE;AACpE,QAAM,MAAM,KAAK,IAAI,OAAO,CAAC,OAAO,GAAG,eAAe,UAAU;AAChE,QAAM,WAAW;AAAA,IACf,GAAG;AAAA,IACH,OAAO,IAAI;AAAA,IACX;AAAA,IACA,GAAI,KAAK,OAAO,EAAE,MAAM,KAAK,KAAK,OAAO,CAAC,SAAS,KAAK,eAAe,UAAU,EAAE,IAAI,CAAC;AAAA,EAC1F;AACA,QAAM,SAAS,KAAK,IAAI,OAAO,CAAC,OAAO,GAAG,eAAe,UAAU;AACnE,MAAI,OAAO,WAAW,EAAG,QAAO,EAAE,MAAM,UAAU,OAAO,CAAC,EAAE;AAC5D,QAAM,SAAS,KAAK,WAAW;AAC/B,QAAM,WAAW,CAAC,GAAG,IAAI,IAAI,OAAO,IAAI,CAAC,OAAO,GAAG,UAAU,CAAC,CAAC;AAC/D,QAAM,QAAQ,UAAU,SAAS,WAAW,IAAI,KAAK,GAAG,IAAI,SAAS,KAAK,IAAI,CAAC;AAC/E,QAAM,MAAM,OAAO,WAAW;AAC9B,MAAI,IAAI,WAAW,GAAG;AACpB,WAAO;AAAA,MACL,MAAM;AAAA,MACN,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S,WAAW,KAAK,SAAS,KAAK,CAAC,YAAY,OAAO,KAAK,OAAO,EAAE,WAAW,CAAC,GAAG;AAC1F,8BAAoB,GAAG,IAAI,+EAA+E;AAAA,QAC5G;AACA,YAAI,SAAS,SAAS,wBAAwB;AAC5C;AAAA,YACE,GAAG,SAAS,MAAM,wCAAwC,sBAAsB;AAAA,UAClF;AAAA,QACF;AACA,cAAM,eAAe;AAAA,UACnB,GAAG,IAAI,IAAI,SAAS,QAAQ,CAAC,YAAa,OAAO,UAAU,aAAa,MAAM,OAAO,IAAK,SAAS,CAAC,CAAG,CAAC;AAAA,QAC1G;AACA,cAAM;AAAA,UACJ,SAAS,IAAI,CAAC,aAAa,EAAE,MAAM,YAAY,QAAQ,EAAE;AAAA,UACzD;AAAA,UACA,KAAK,SAAS;AAAA,QAChB;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;AASO,SAAS,gBAAgB,OAAwB;AACtD,MAAI,UAAU,UAAa,UAAU,QAAQ,UAAU,IAAI;AACzD;AAAA,MACE;AAAA,IACF;AAAA,EACF;AACA,QAAM,MAAM,OAAO,KAAK;AACxB,MAAI,OAAO,MAAM,GAAG,KAAK,MAAM,KAAK,MAAM,MAAO,MAAM,KAAK,MAAM,KAAM;AACtE,wBAAoB,uEAAuE;AAAA,EAC7F;AACA,SAAO;AACT;","names":["changes"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/tags/shared.ts"],"sourcesContent":["import { TAG_IDENTIFYING_FIELD, type TagsEffectiveEntry } from \"@baker/api\";\nimport { ApiError } from \"../../client.ts\";\nimport { writeJson } from \"../../output.ts\";\n\nexport function failApi(err: unknown): never {\n if (err instanceof ApiError) {\n writeJson({ ok: false, error: { code: err.code, message: err.message } });\n process.exit(1);\n }\n if (err instanceof Error) {\n writeJson({ ok: false, error: { code: \"INTERNAL_ERROR\", message: err.message } });\n process.exit(1);\n }\n writeJson({ ok: false, error: { code: \"INTERNAL_ERROR\", message: \"Unexpected error\" } });\n process.exit(1);\n}\n\nexport function failValidation(message: string): never {\n writeJson({ ok: false, error: { code: \"VALIDATION_ERROR\", message } });\n process.exit(1);\n}\n\n/** Indent a possibly multi-line config value so long snippets (the `code` tag) stay readable. */\nfunction renderConfigValue(value: string): string {\n return value.includes(\"\\n\") ? value.replace(/\\n/g, \"\\n \") : value;\n}\n\n/** A config value longer than this, or on more than one line, is a script: shown by its size unless `--full`. */\nconst LONG_VALUE_CHARS = 200;\n\n/** A listed tag, its scripts shown by size so one custom `code` body does not bury the other tags. */\nexport type ListedTag = TagsEffectiveEntry & { collapsed?: Record<string, string> };\n\nfunction sizeOf(value: string): string {\n const lines = value.split(\"\\n\").length;\n return `${lines} ${lines === 1 ? \"line\" : \"lines\"}, ${value.length} chars`;\n}\n\n/** `entry` with each long config value moved to `collapsed` as its size; `--full` keeps it whole. */\nexport function listedTag(entry: TagsEffectiveEntry): ListedTag {\n const long = Object.entries(entry.config).filter(\n ([, value]) => value.includes(\"\\n\") || value.length > LONG_VALUE_CHARS,\n );\n if (long.length === 0) {\n return entry;\n }\n const config = Object.fromEntries(Object.entries(entry.config).filter(([key]) => !long.some(([k]) => k === key)));\n return { ...entry, config, collapsed: Object.fromEntries(long.map(([key, value]) => [key, sizeOf(value)])) };\n}\n\nexport const COLLAPSED_HINT =\n \"A long config value (a custom `code` script) shows as its size under `collapsed`; `baker tags list --full` prints it whole, to reuse in a follow-up change.\";\n\nexport function renderEffectiveEntry(entry: ListedTag): string {\n const parts = [entry.ref, entry.type];\n if (entry.identifier !== undefined) {\n parts.push(entry.identifier);\n }\n if (entry.staged !== undefined) {\n parts.push(`[staged: ${entry.staged}]`);\n }\n const secretBits = [\n ...entry.secretsSet.map((field) => `${field} ✓ set`),\n ...entry.secretsPending.map((field) => `${field} ⏳ pending`),\n ];\n if (secretBits.length > 0) {\n parts.push(`[secrets: ${secretBits.join(\", \")}]`);\n }\n const header = parts.join(\" \");\n // All config values here are already redacted server-side (secrets stripped),\n // so every field printed is safe to read and reuse to pre-fill a follow-up\n // change instead of asking the user for a value we store.\n // Skip the identifying field — it's already on the header line as `identifier`.\n const identifyingField = TAG_IDENTIFYING_FIELD[entry.type];\n const configLines = Object.entries(entry.config)\n .filter(([key]) => key !== identifyingField)\n .map(([key, value]) => ` ${key}: ${renderConfigValue(value)}`);\n for (const [key, size] of Object.entries(entry.collapsed ?? {})) {\n configLines.push(` ${key}: (${size} — --full prints it)`);\n }\n return configLines.length > 0 ? `${header}\\n${configLines.join(\"\\n\")}` : header;\n}\n\n/**\n * The write path, restated on every read.\n *\n * This family is read-only, so `list` is where a chat decides what to do about\n * a tag — and a production chat decided, from its tool list alone, that the\n * approval form did not exist, never called it, and filed the change as a Task\n * the user had to carry out by hand. The form is attached to every turn\n * (`baker_ui` rides along on each query), so \"it isn't there\" is a conclusion\n * only a failed call may reach.\n */\nexport function tagsListHints(): string[] {\n return [\n \"To create, edit or delete a tag, call the `request_tag_input` approval form (tool `mcp__baker_ui__request_tag_input`, server `baker_ui`) — it is attached to every turn of this chat and collects any secret values itself.\",\n \"Don't conclude the form is unavailable from your tool list: call it, and report what it returns. And never file a tag change as a Task — a Task hands the user work this chat can stage in one call.\",\n ];\n}\n"],"mappings":";;;;;;;;;;;AAIO,SAAS,QAAQ,KAAqB;AAC3C,MAAI,eAAe,UAAU;AAC3B,cAAU,EAAE,IAAI,OAAO,OAAO,EAAE,MAAM,IAAI,MAAM,SAAS,IAAI,QAAQ,EAAE,CAAC;AACxE,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,MAAI,eAAe,OAAO;AACxB,cAAU,EAAE,IAAI,OAAO,OAAO,EAAE,MAAM,kBAAkB,SAAS,IAAI,QAAQ,EAAE,CAAC;AAChF,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,YAAU,EAAE,IAAI,OAAO,OAAO,EAAE,MAAM,kBAAkB,SAAS,mBAAmB,EAAE,CAAC;AACvF,UAAQ,KAAK,CAAC;AAChB;AAEO,SAAS,eAAe,SAAwB;AACrD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