@toloka-platform/sdk 0.25.1 → 0.25.2

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.
Binary file
@@ -1 +1 @@
1
- f482e57e094029195964d1433e1a7bc63da0a9e0bce99a579e038382014798ee toloka.js.jsc
1
+ 57c88a84ba9a4d4ceac33418745608ded49a9a2e9c03dbbd9b5ad054e3c73ec8 toloka.js.jsc
@@ -1 +1 @@
1
- 009f7c1380e24c037c52f8c6bdff873f24f759537f1bb7a7e64587712da2e38a toloka.js
1
+ bfb6d985a69d84c78d78800cf75600a6673b1ffc75408a4dfd0dd28f0072a80a toloka.js
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@toloka-platform/sdk",
3
- "version": "0.25.1",
3
+ "version": "0.25.2",
4
4
  "private": false,
5
5
  "description": "Build, inspect, and operate Toloka pipeline projects as TypeScript source. The public API may change between minor versions before 1.0.",
6
6
  "license": "Apache-2.0",
@@ -78,6 +78,6 @@
78
78
  "bun": ">=1.4.0"
79
79
  },
80
80
  "tolokaBuild": {
81
- "commit": "d7c2aab3ab8df79603e8a63e13e27390f91b0a8c"
81
+ "commit": "2b7e508889baaced4d54250c90c7233cd98dd433"
82
82
  }
83
83
  }
@@ -11,8 +11,8 @@
11
11
  "testing",
12
12
  "checks"
13
13
  ],
14
- "version": "0.25.1",
15
- "digest": "edb0562c0c1678340b5185af32f99576a5a50775ddea943a65e8209602e571dd",
14
+ "version": "0.25.2",
15
+ "digest": "91ea5f0e85b18609e8e4d82f0f67f70e4bda06b82e83cbb1de2a53b6f56647de",
16
16
  "files": [
17
17
  "SKILL.md",
18
18
  "references/human-work.md",
@@ -33,7 +33,7 @@
33
33
  "bug",
34
34
  "report"
35
35
  ],
36
- "version": "0.25.1",
36
+ "version": "0.25.2",
37
37
  "digest": "70f0bd2c80b32f87896aeb27c363b8a2d37f40e22424f57fe1aad142e125ad67",
38
38
  "files": [
39
39
  "SKILL.md",
@@ -50,7 +50,7 @@
50
50
  "getting-started",
51
51
  "agent"
52
52
  ],
53
- "version": "0.25.1",
53
+ "version": "0.25.2",
54
54
  "digest": "2278adeb46a792356579395fcf73c42322cb23bcd0c61e20856ccabdad6762d1",
55
55
  "files": [
56
56
  "SKILL.md"
@@ -67,7 +67,7 @@
67
67
  "sft",
68
68
  "models"
69
69
  ],
70
- "version": "0.25.1",
70
+ "version": "0.25.2",
71
71
  "digest": "3ce10dee5d3c283d8b5fdea15134a58fc738c7af2c1bb19eb5a0bf70ea0bca13",
72
72
  "files": [
73
73
  "SKILL.md"
@@ -84,7 +84,7 @@
84
84
  "prompt",
85
85
  "models"
86
86
  ],
87
- "version": "0.25.1",
87
+ "version": "0.25.2",
88
88
  "digest": "be8bce8d9cf7241ccb60d2b2a9b7cc07d7755a76e8ff8ec1b0847c49efbb3469",
89
89
  "files": [
90
90
  "SKILL.md"
@@ -34,14 +34,10 @@ For an applied change, the dependencies are read → edit → check/validate →
34
34
 
35
35
  1. Read `toloka.json` when present, then read the relevant `pipelines/**/pipeline.ts` module and everything it imports.
36
36
  2. Edit the TypeScript source. Treat it as authoritative desired state.
37
- 3. Iterate with `toloka check <pipeline> --node <name-or-id>` while you edit, then validate each changed pipeline against the platform:
38
- ```sh
39
- toloka validate
40
- ```
41
- Step 5 runs the complete local gate: do not run the unfiltered `toloka check` separately right before `toloka apply`.
42
- 4. Run `toloka plan`. Read the complete diff and resolve every conflict or missing prerequisite.
43
- 5. Show the plan and run `toloka apply` when its changes match the requested work. Resolve removals, immutable-field conflicts, or changes outside that scope with the user first. Apply reruns the complete local gate and proceeds only when it passes. It takes no options and never asks for confirmation, so run it as plain `toloka apply`.
44
- 6. Run `toloka plan` again and require `No changes.`, then run `toloka validate --wait` and act on the lint findings it reports.
37
+ 3. Iterate with `toloka check <pipeline> --node <name-or-id>` while you edit. `toloka apply` runs the complete local gate: do not run the unfiltered `toloka check` separately right before it.
38
+ 4. Run `toloka plan` when you need to review the diff without applying it, such as for a change that may reach beyond the request. Resolve every conflict or missing prerequisite it reports.
39
+ 5. Run `toloka apply && toloka validate --wait` as one command when the changes match the requested work. Apply reruns the complete local gate and writes nothing when it fails, prints the plan it applies before writing, and prints the plan again after writing, which must say `No changes.`; when it does not converge it says so and exits 1. It holds back a pipeline whose plan removes a node or graph field (a rewired connection is applied), lists what it skipped, and exits 1: resolve removals, immutable-field conflicts, or changes outside the scope with the user first, then run `toloka apply --allow-removals`, or pass it from the start when the user asked for the removal. It never asks for confirmation.
40
+ 6. Act on the source/spec errors and lint findings `toloka validate --wait` reports.
45
41
 
46
42
  The CLI reads source, compares it with live state, and reconciles the platform. Edit files; never mutate a pipeline through raw HTTP, SDK client methods, or internal platform tool calls. Do not make a live edit and then reverse-engineer it into source.
47
43
 
@@ -105,7 +101,7 @@ Choose representative fixtures from available data, redacting sensitive values w
105
101
 
106
102
  ## Recover from expected failures
107
103
 
108
- When plan, apply, or validate fails, follow [Recover safely](references/workflow-and-cli.md#recover-safely). It covers a dataset field schema conflict, an unreadable field schema, a missing secret, a 409 stale graph version, node drift after apply, a server 400 after a partial apply, and a lost platform connection. Never retry blindly, and never work around reconciliation with raw API calls.
104
+ When plan, apply, or validate fails, follow [Recover safely](references/workflow-and-cli.md#recover-safely). It covers a dataset field schema conflict, an unreadable field schema, a missing secret, a 409 stale graph version, a 409 for an active or finalizing run, node drift after apply, a server 400 after a partial apply, and a lost platform connection. Never retry blindly, and never work around reconciliation with raw API calls.
109
105
 
110
106
  ## Run an applied pipeline
111
107
 
@@ -28,7 +28,7 @@ All commands accept `--source-root <directory>`. Prefer running from the source
28
28
 
29
29
  ## Find commands and catalogs
30
30
 
31
- Run `toloka --help` and `toloka <command> --help` for the exact commands and options of the installed version. The commands fall into these groups:
31
+ Run `toloka help --all` once for the usage and every option of all commands of the installed version, and `toloka <command> --help` for one command with its notes. The commands fall into these groups:
32
32
 
33
33
  - sign-in and settings: `login`, `logout`, `auth-status` (`whoami`), `config`, `version`;
34
34
  - projects and tokens: `project` (`list`, `add`, `switch`, `current`, `url`, `remove`, `create`, `untrack`, `token`, `tokens`, `revoke-token`, `revoke-tokens`), `delivery-order list`;
@@ -45,6 +45,7 @@ Run `toloka --help` and `toloka <command> --help` for the exact commands and opt
45
45
 
46
46
  `toloka pipeline cost [name] [--item-limit <n>]` forecasts what a run of a live, validated pipeline would bill. It does not start a run or change the graph. If any billed node is marked `skipped`, the displayed total is incomplete and must not be presented as the pipeline price. Compute and label a labor floor for each skipped billed node as `items × pricePerTask × annotations per item`, using `1` for generation and `overlap` for quorum. Also report `maxEntities`, quality-criteria count, and only exclusions applicable to the authored QA and workflow. Apply accepting a rate does not prove its final billed value.
47
47
 
48
+
48
49
  ## Manage model checkpoints
49
50
 
50
51
  The global Base Model Catalog is read-only and uses `toloka base-model`. `base-model list` prints aligned ID, name, provider, upstream-model, revision (first 12 characters) and upstream-snapshot URL columns by default; `base-model get` prints the full pinned revision and the `https://huggingface.co/<model>/tree/<revision>` snapshot URL, which is the exact base every Training Run trains on. `toloka model` manages project-owned lineages; creation requires one catalog `baseModelId` and creates metadata without a Model Version. Every Base Model and Model command accepts `--json` for machine-readable output. `toloka model version download <model-version> --out <directory>` downloads and verifies a Model Version's content; uploading and validating a Model Version have no command yet.
@@ -65,14 +66,12 @@ Use `training cost` to validate inputs and show the maximum charge before `train
65
66
 
66
67
  ## Check locally and validate against the platform
67
68
 
68
- Check the nodes you edit locally, validate every bound pipeline remotely, then apply, which runs the complete local gate itself:
69
+ Check the nodes you edit locally, then apply and validate every bound pipeline in one command; apply runs the complete local gate itself:
69
70
 
70
71
  ```sh
71
72
  toloka check <pipeline> --node <name-or-id> # while you edit a node
72
- toloka validate # before apply
73
- toloka apply # runs the unfiltered toloka check first and writes nothing when it fails
74
- toloka validate --wait # after apply: waits for the platform's lints
75
- toloka pipeline lint <name> --wait # after dataset changes or a failed lint: reruns the lints
73
+ toloka apply && toloka validate --wait # runs the unfiltered toloka check first, writes nothing when it fails, then waits for the platform's lints
74
+ toloka pipeline lint <name> --wait # after dataset changes or a failed lint: reruns the lints
76
75
  ```
77
76
 
78
77
  Run the unfiltered `toloka check` on its own only when you are not about to apply, since apply would run it again. `toloka check` requires no credentials or live pipeline; SKILL.md describes what it runs and what its statuses mean. Use `toloka check <pipeline> --node <name-or-id>` for a focused edit loop, `--watch` for serialized reruns, and `--json` for automation.
@@ -95,7 +94,7 @@ The authored API still supplies extra local safety:
95
94
  Treat every plan line as evidence of what apply will attempt. `toloka plan --json` prints the same plan as `{ "changes": [...], "missingSecrets": [...] }`, where each change has `kind`, `action`, `label`, and, when they apply, `pipeline`, `dataset`, and `id`.
96
95
 
97
96
  - Confirm additions and changes match the request.
98
- - Stop on an unexpected removal. Apply refuses to delete tracked pipelines or datasets merely because their source entry disappeared.
97
+ - Stop on an unexpected removal. Apply refuses to delete tracked pipelines or datasets merely because their source entry disappeared, and holds back a pipeline whose plan removes a node or graph field until you pass `--allow-removals`; rewired connections apply without it.
99
98
  - Stop on a dataset field marked changed. Existing field schemas cannot be rewritten.
100
99
  - Set every secret listed as missing before apply.
101
100
  - If imported source contains live IDs, preserve them while editing around them.
@@ -208,6 +207,10 @@ Use the exact name reported by plan. Set it with `toloka secret set`, rerun plan
208
207
 
209
208
  A 409 means live graph state changed after apply read it. Run plan again, compare the new live diff with the source, incorporate intentional live changes into source when required, and apply once more. Never add `expectedVersion` to source and never loop retries.
210
209
 
210
+ ### Active or finalizing run
211
+
212
+ A 409 that says the pipeline has an active run, or that a run is being finalized, means the platform takes no graph change or cancel until that run ends. Check it with `toloka pipeline status <name>`, tell the user the change applies once the run ends, and apply again then. Never wait for it in a sleep loop.
213
+
211
214
  ### Unexplained node drift after apply
212
215
 
213
216
  Object settings preserve omitted live keys, but list-valued settings such as conditions, predicates, entities, steps, and rules can be compared as whole values after the server adds defaults inside an element. If plan reports an unnamed node change after a clean apply, run `toloka import` into a scratch directory outside the source root, compare that node with source, and declare only the materialized key needed for convergence. Delete the scratch directory afterward and never re-apply blindly.
@@ -184,8 +184,13 @@ export const registerSourceCommands = (program: Command, host: CommandHost): voi
184
184
 
185
185
  program
186
186
  .command("apply")
187
- .description("check source, then make the platform match it")
188
- .action(async () => {
187
+ .option(
188
+ "--allow-removals",
189
+ "also apply pipelines whose plan removes nodes or graph fields",
190
+ false,
191
+ )
192
+ .description("check source, print the plan, make the platform match it, then plan again")
193
+ .action(async (options: { allowRemovals: boolean }) => {
189
194
  const sourceRoot = await resolveSourceRoot(globals(), context.io);
190
195
  const { result: checked, interruptedExitCode } = await runChecksInterruptibly(
191
196
  {
@@ -209,7 +214,11 @@ export const registerSourceCommands = (program: Command, host: CommandHost): voi
209
214
  sourceRoot,
210
215
  source: checked.source,
211
216
  ...(projectId === undefined ? {} : { projectId }),
217
+ ...(options.allowRemovals ? { allowRemovals: true } : {}),
218
+ onPlan: (plan) => context.io.stdout(plan),
212
219
  });
213
220
  context.io.stdout(result.output);
221
+ const diverged = result.remainingChanges !== undefined && !result.converged;
222
+ if (result.skipped.length > 0 || diverged) exitCode.value = 1;
214
223
  });
215
224
  };
@@ -21,6 +21,12 @@ const apiErrorHint = (error: PotatoApiError): string | undefined => {
21
21
  if (error.status === 404) {
22
22
  return "Hint: Check the id against toloka project current and the matching list command; ids belong to one project on one platform.";
23
23
  }
24
+ if (
25
+ error.status === 409 &&
26
+ /because it has an active run|cannot be canceled while it is being finalized/u.test(apiErrorDetails(error) ?? "")
27
+ ) {
28
+ return "Hint: A run of this pipeline is still active or being finalized, and the platform takes no graph change or cancel until it ends. Check it with toloka pipeline status <name>, and apply again once the run has ended; do not retry in a sleep loop.";
29
+ }
24
30
  if (error.status === 429) {
25
31
  return "Hint: The platform is rate limiting this key; wait a moment and retry.";
26
32
  }
@@ -0,0 +1,32 @@
1
+ import type { Command } from "commander";
2
+
3
+ const runsItself = (command: Command): boolean =>
4
+ command.commands.length === 0 || Reflect.get(command, "_actionHandler") !== null;
5
+
6
+ const commandLines = (command: Command): string[] => {
7
+ const help = command.createHelp();
8
+ const options = help
9
+ .visibleOptions(command)
10
+ .filter((option) => option.long !== "--help")
11
+ .map((option) => ` ${help.optionTerm(option)} ${help.optionDescription(option).replace(" (default: false)", "")}`);
12
+ const usage = help.commandUsage(command).replace(" [options]", "");
13
+ const own = runsItself(command) ? [`${usage} ${command.description()}`, ...options] : [];
14
+ return [
15
+ ...own,
16
+ ...help.visibleCommands(command).filter((child) => child.name() !== "help").flatMap(commandLines),
17
+ ];
18
+ };
19
+
20
+ export const formatAllCommandsHelp = (program: Command): string => {
21
+ const help = program.createHelp();
22
+ const globals = help
23
+ .visibleOptions(program)
24
+ .filter((option) => option.long !== "--help" && option.long !== "--version")
25
+ .map((option) => help.optionTerm(option))
26
+ .join(", ");
27
+ return [
28
+ `Every command also takes ${globals}. Run toloka <command> --help for one command with its notes.`,
29
+ "",
30
+ ...help.visibleCommands(program).filter((child) => child.name() !== "help").flatMap(commandLines),
31
+ ].join("\n");
32
+ };
package/src/cli/index.ts CHANGED
@@ -22,6 +22,7 @@ export {
22
22
  export type {
23
23
  ApplyProjectOptions,
24
24
  ApplyProjectResult,
25
+ SkippedPipelineRemovals,
25
26
  ImportProjectOptions,
26
27
  ImportProjectResult,
27
28
  PipelinePlanChange,
@@ -39,6 +39,8 @@ import {
39
39
  } from "./context";
40
40
  import { normalizeEnvironment } from "./environment";
41
41
  import { formatCliError } from "./format-error";
42
+ import { formatAllCommandsHelp } from "./help-all";
43
+ import { assertCli } from "./cli-error";
42
44
  import { readAgentSkillStalenessWarning } from "./init";
43
45
  import { SDK_VERSION } from "./sdk-version";
44
46
  import { terminalIo } from "./terminal-io";
@@ -68,7 +70,8 @@ export function createProgram(context: ProgramContext): CreatedProgram {
68
70
  writeOut: (text) => context.io.stdout(text.replace(/\n$/u, "")),
69
71
  writeErr: (text) => context.io.stderr(text.replace(/\n$/u, "")),
70
72
  })
71
- .exitOverride();
73
+ .exitOverride()
74
+ .helpCommand(false);
72
75
 
73
76
  const globals = (): GlobalOptions => program.opts<GlobalOptions>();
74
77
  const host = { context, exitCode, globals };
@@ -117,6 +120,29 @@ export function createProgram(context: ProgramContext): CreatedProgram {
117
120
  registerSkillCommands(program, host);
118
121
  registerUiCommands(program, host);
119
122
 
123
+ program
124
+ .command("help")
125
+ .argument("[command...]", "command to describe, such as dataset upload")
126
+ .option("--all", "print the usage and every option of all commands at once", false)
127
+ .description("display help for toloka or one of its commands")
128
+ .action((path: string[], options: { all: boolean }) => {
129
+ if (options.all) {
130
+ context.io.stdout(formatAllCommandsHelp(program));
131
+ return;
132
+ }
133
+ let command = program;
134
+ for (const name of path) {
135
+ const child = command.commands.find(
136
+ (candidate) => candidate.name() === name || candidate.aliases().includes(name),
137
+ );
138
+ assertCli(child, `Unknown command: toloka ${path.join(" ")}.`, {
139
+ hint: { description: "Run toloka help --all to list every command." },
140
+ });
141
+ command = child;
142
+ }
143
+ command.outputHelp();
144
+ });
145
+
120
146
  return { program, exitCode };
121
147
  }
122
148
 
@@ -73,12 +73,23 @@ export type ProjectStatusResult = {
73
73
  readonly output: string;
74
74
  };
75
75
 
76
- export type ApplyProjectOptions = PlanProjectOptions;
76
+ export type ApplyProjectOptions = PlanProjectOptions & {
77
+ readonly allowRemovals?: boolean;
78
+ readonly onPlan?: (output: string) => void;
79
+ };
80
+
81
+ export type SkippedPipelineRemovals = {
82
+ readonly pipeline: string;
83
+ readonly removals: readonly ProjectPlanChange[];
84
+ };
77
85
 
78
86
  export type ApplyProjectResult = {
79
87
  readonly action: "changed" | "unchanged";
80
88
  readonly state: TolokaState;
81
89
  readonly changes: readonly ProjectPlanChange[];
90
+ readonly skipped: readonly SkippedPipelineRemovals[];
91
+ readonly remainingChanges: readonly ProjectPlanChange[] | undefined;
92
+ readonly converged: boolean;
82
93
  readonly writes: number;
83
94
  readonly output: string;
84
95
  };
@@ -207,6 +218,31 @@ const withCanonicalExpertListConditions = (node: unknown): unknown =>
207
218
  }
208
219
  : node;
209
220
 
221
+ const withoutEmptyRelations = (entity: unknown): unknown => {
222
+ if (!isPlainObject(entity) || !Array.isArray(entity.relations) || entity.relations.length > 0)
223
+ return entity;
224
+ const { relations: _relations, ...rest } = entity;
225
+ return rest;
226
+ };
227
+
228
+ const withoutEmptyEntityRelations = (node: unknown): unknown => {
229
+ if (!isPlainObject(node) || !isPlainObject(node.settings)) return node;
230
+ const { entities } = node.settings;
231
+ if (!isPlainObject(entities)) return node;
232
+ return {
233
+ ...node,
234
+ settings: {
235
+ ...node.settings,
236
+ entities: Object.fromEntries(
237
+ Object.entries(entities).map(([direction, list]) => [
238
+ direction,
239
+ Array.isArray(list) ? list.map(withoutEmptyRelations) : list,
240
+ ]),
241
+ ),
242
+ },
243
+ };
244
+ };
245
+
210
246
  const withAudienceSourcingDefaults = (node: PipelineGraphV1["nodes"][number]): unknown => {
211
247
  if (node.type !== "generation" && node.type !== "quorum") return node;
212
248
 
@@ -278,6 +314,15 @@ const diffKeyed = <Item>(
278
314
  return changes;
279
315
  };
280
316
 
317
+ const layoutForNodes = (
318
+ layout: PipelineGraphV1["layout"],
319
+ nodes: PipelineGraphV1["nodes"],
320
+ ): PipelineGraphV1["layout"] => {
321
+ if (layout === undefined) return undefined;
322
+ const nodeIds = new Set(nodes.map((node) => node.id));
323
+ return Object.fromEntries(Object.entries(layout).filter(([nodeId]) => nodeIds.has(nodeId)));
324
+ };
325
+
281
326
  export function diffPipelineGraphs(
282
327
  authoredGraph: PipelineGraphV1,
283
328
  liveGraph: PipelineGraphV1,
@@ -308,8 +353,10 @@ export function diffPipelineGraphs(
308
353
  liveNodes,
309
354
  (authored, live) =>
310
355
  matchesAuthored(
311
- withCanonicalExpertListConditions(authored),
312
- withCanonicalExpertListConditions(withAudienceSourcingDefaults(live)),
356
+ withoutEmptyEntityRelations(withCanonicalExpertListConditions(authored)),
357
+ withoutEmptyEntityRelations(
358
+ withCanonicalExpertListConditions(withAudienceSourcingDefaults(live)),
359
+ ),
313
360
  ),
314
361
  (node, action) => ({
315
362
  kind: "node",
@@ -327,7 +374,8 @@ export function diffPipelineGraphs(
327
374
  label: connectionLabel(connection, action === "removed" ? liveNodes : authoredNodes),
328
375
  }),
329
376
  ),
330
- ...(valueKey(authoredGraph.layout) === valueKey(liveGraph.layout)
377
+ ...(valueKey(authoredGraph.layout) ===
378
+ valueKey(layoutForNodes(liveGraph.layout, authoredGraph.nodes))
331
379
  ? []
332
380
  : [{ kind: "layout" as const, action: "changed" as const, label: "pipeline layout" }]),
333
381
  ];
@@ -359,7 +407,9 @@ const graphWithLiveState = (
359
407
  const liveNodes = new Map(liveGraph.nodes.map((node) => [node.id, node]));
360
408
  return {
361
409
  ...authoredGraph,
362
- ...(liveGraph.layout === undefined ? {} : { layout: liveGraph.layout }),
410
+ ...(liveGraph.layout === undefined
411
+ ? {}
412
+ : { layout: layoutForNodes(liveGraph.layout, authoredGraph.nodes) }),
363
413
  nodes: authoredGraph.nodes.map((node) => {
364
414
  const live = liveNodes.get(node.id);
365
415
  switch (node.type) {
@@ -954,7 +1004,26 @@ export async function applyProject(
954
1004
  { hint: { description: "Add the changed columns under new field names, or create a new dataset for the new schema." } },
955
1005
  );
956
1006
 
957
- const ruleViolations = inspection.pipelines
1007
+ const skipped: SkippedPipelineRemovals[] =
1008
+ options.allowRemovals === true
1009
+ ? []
1010
+ : inspection.pipelines.flatMap((pipeline) => {
1011
+ const removals = pipeline.graphChanges
1012
+ .filter(
1013
+ (change) =>
1014
+ change.action === "removed" && (change.kind === "node" || change.kind === "field"),
1015
+ )
1016
+ .map((change) => ({ ...change, pipeline: pipeline.source.sourceDirectory }));
1017
+ return pipeline.pipeline === undefined || removals.length === 0
1018
+ ? []
1019
+ : [{ pipeline: pipeline.source.sourceDirectory, removals }];
1020
+ });
1021
+ const skippedDirectories = new Set(skipped.map(({ pipeline }) => pipeline));
1022
+ const writablePipelines = inspection.pipelines.filter(
1023
+ (pipeline) => !skippedDirectories.has(pipeline.source.sourceDirectory),
1024
+ );
1025
+
1026
+ const ruleViolations = writablePipelines
958
1027
  .filter((pipeline) => pipeline.pipeline === undefined || pipeline.graphChanges.length > 0)
959
1028
  .flatMap((pipeline) =>
960
1029
  platformRuleIssues(pipeline.source.definition.graph).map(
@@ -967,6 +1036,9 @@ export async function applyProject(
967
1036
  { hint: { description: "Fix the listed nodes in source; toloka check reports the same rules as warnings." } },
968
1037
  );
969
1038
 
1039
+ if (inspection.changes.length > 0)
1040
+ options.onPlan?.(["Applying this plan:", planOutput(inspection.changes, [])].join("\n"));
1041
+
970
1042
  let writes = 0;
971
1043
  const importedPipelineIds = new Map<string, string>();
972
1044
  for (const pipelineInspection of inspection.pipelines) {
@@ -1005,12 +1077,14 @@ export async function applyProject(
1005
1077
 
1006
1078
  const pipelineIds = new Map<string, string>();
1007
1079
  for (const pipelineInspection of inspection.pipelines) {
1008
- const applied = await applyPipeline(
1009
- client,
1010
- pipelineInspection,
1011
- datasetIds,
1012
- importedPipelineIds.get(pipelineInspection.source.sourceDirectory),
1013
- );
1080
+ const applied = skippedDirectories.has(pipelineInspection.source.sourceDirectory)
1081
+ ? { pipelineId: pipelineInspection.pipeline?.id ?? "", writes: 0 }
1082
+ : await applyPipeline(
1083
+ client,
1084
+ pipelineInspection,
1085
+ datasetIds,
1086
+ importedPipelineIds.get(pipelineInspection.source.sourceDirectory),
1087
+ );
1014
1088
  pipelineIds.set(pipelineInspection.source.sourceDirectory, applied.pipelineId);
1015
1089
  writes += applied.writes;
1016
1090
  }
@@ -1040,14 +1114,59 @@ export async function applyProject(
1040
1114
  await writeTolokaState(options.sourceRoot, nextState);
1041
1115
  const action = writes === 0 ? "unchanged" : "changed";
1042
1116
  const plannedChanges = inspection.changes.length;
1043
- const output =
1117
+ if (plannedChanges === 0)
1118
+ return {
1119
+ action,
1120
+ state: nextState,
1121
+ changes: [],
1122
+ skipped: [],
1123
+ remainingChanges: [],
1124
+ converged: true,
1125
+ writes,
1126
+ output: "No changes.",
1127
+ };
1128
+ const replan =
1044
1129
  writes === 0
1045
- ? "No changes."
1046
- : `Applied ${plannedChanges} planned ${plannedChanges === 1 ? "change" : "changes"} with ${writes} platform ${writes === 1 ? "write" : "writes"} to project ${inspection.projectId}.`;
1130
+ ? { changes: inspection.changes }
1131
+ : await inspectProject(client, { ...options, source: inspection.source }).then(
1132
+ ({ changes }) => ({ changes }),
1133
+ (error: unknown) => ({ error: error instanceof Error ? error.message : String(error) }),
1134
+ );
1135
+ const isHeldBack = (change: ProjectPlanChange) =>
1136
+ change.pipeline !== undefined && skippedDirectories.has(change.pipeline);
1137
+ const heldChanges = inspection.changes.filter(isHeldBack).length;
1138
+ const appliedCount = plannedChanges - heldChanges;
1139
+ const remainingChanges = "changes" in replan ? replan.changes : undefined;
1140
+ const unexpected = (remainingChanges ?? []).filter((change) => !isHeldBack(change));
1141
+ const converged = remainingChanges !== undefined && unexpected.length === 0;
1142
+ const output = [
1143
+ `Applied ${heldChanges === 0 ? "" : `${appliedCount} of `}${plannedChanges} planned ${plannedChanges === 1 ? "change" : "changes"} with ${writes} platform ${writes === 1 ? "write" : "writes"} to project ${inspection.projectId}.`,
1144
+ ...skipped.flatMap(({ pipeline, removals }) => [
1145
+ "",
1146
+ `Skipped ${pipeline}: its plan removes`,
1147
+ ...removals.map((change) => ` ${changeLine(change)}`),
1148
+ "Nothing in this pipeline was written. Once the removal is agreed, run: toloka apply --allow-removals",
1149
+ ]),
1150
+ "",
1151
+ ...(remainingChanges === undefined
1152
+ ? [
1153
+ `Warning: the changes were applied, but planning again to verify them failed: ${"error" in replan ? replan.error : ""}`,
1154
+ "Run toloka plan to check the result.",
1155
+ ]
1156
+ : unexpected.length > 0
1157
+ ? [
1158
+ "Plan after apply (not converged: the platform still differs from the source):",
1159
+ planOutput(remainingChanges, []),
1160
+ ]
1161
+ : ["Plan after apply:", planOutput(remainingChanges, [])]),
1162
+ ].join("\n");
1047
1163
  return {
1048
1164
  action,
1049
1165
  state: nextState,
1050
1166
  changes: inspection.changes,
1167
+ skipped,
1168
+ remainingChanges,
1169
+ converged,
1051
1170
  writes,
1052
1171
  output,
1053
1172
  };
package/src/importer.ts CHANGED
@@ -188,9 +188,48 @@ function indentation(depth: number): string {
188
188
  return " ".repeat(depth);
189
189
  }
190
190
 
191
+ const TEMPLATE_LITERAL_MIN_LENGTH = 200;
192
+
193
+ function templateLiteralCharacter(character: string, trailing: boolean): string {
194
+ const codePoint = character.codePointAt(0) ?? 0;
195
+ if (character === "\\") return "\\\\";
196
+ if (trailing && character === " ") return "\\x20";
197
+ if (character === "\t") return trailing ? "\\t" : character;
198
+ if (character === "\n") return character;
199
+ if (character === "\r") return "\\r";
200
+ const isLoneSurrogate = character.length === 1 && codePoint >= 0xd800 && codePoint <= 0xdfff;
201
+ const isEscaped =
202
+ codePoint < 0x20 || codePoint === 0x7f || codePoint === 0x2028 || codePoint === 0x2029;
203
+ return isEscaped || isLoneSurrogate ? `\\u${codePoint.toString(16).padStart(4, "0")}` : character;
204
+ }
205
+
206
+ function templateLiteral(value: string): string {
207
+ const characters = Array.from(value);
208
+ const trailing = characters.map(() => false);
209
+ let lineEnd = true;
210
+ for (let index = characters.length - 1; index >= 0; index -= 1) {
211
+ const character = characters[index];
212
+ if (character === "\n") lineEnd = true;
213
+ else if (character === " " || character === "\t") trailing[index] = lineEnd;
214
+ else lineEnd = false;
215
+ }
216
+ const body = characters
217
+ .map((character, index) => templateLiteralCharacter(character, trailing[index] ?? false))
218
+ .join("");
219
+ return `\`${body}\``;
220
+ }
221
+
222
+ const isTemplateLiteralSafe = (value: string) => !value.includes("`") && !value.includes("${");
223
+
191
224
  function formatSource(value: unknown, depth = 0): string {
192
225
  if (isSourceReference(value)) return value.name;
193
226
  assert(value !== undefined, "Cannot emit an undefined source value");
227
+ if (
228
+ typeof value === "string" &&
229
+ (value.includes("\n") || value.length > TEMPLATE_LITERAL_MIN_LENGTH) &&
230
+ isTemplateLiteralSafe(value)
231
+ )
232
+ return templateLiteral(value);
194
233
  if (typeof value === "number") assert(Number.isFinite(value), "Cannot emit a non-finite number");
195
234
  if (value === null || typeof value !== "object") {
196
235
  const serialized = JSON.stringify(value);
package/src/index.ts CHANGED
@@ -137,6 +137,7 @@ export {
137
137
  export type {
138
138
  ApplyProjectOptions,
139
139
  ApplyProjectResult,
140
+ SkippedPipelineRemovals,
140
141
  ImportProjectOptions,
141
142
  ImportProjectResult,
142
143
  InitProjectResult,