@plaiful/cli 0.16.1 → 0.16.3

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 (4) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +184 -179
  3. package/package.json +22 -21
  4. package/src/train.js +264 -260
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Plaiful, Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,179 +1,184 @@
1
- # The Plaiful CLI
2
-
3
- > `plaiful` is how your team, or your coding agent, works on your Plaiful product from your game's repo. **Part 1**
4
- > is for the people on your team. **Part 2** is for your coding agent: every command.
5
-
6
- ## Part 1: for your team
7
-
8
- ### What it is
9
-
10
- - A command-line tool for your Plaiful product: you type commands in a terminal, in your game's repo.
11
- - It loads your data into Plaiful, reads back what Plaiful has, and reads the platform docs.
12
- - It signs in as your CMS account, so it can only see and change your own products.
13
- - It needs no AWS access.
14
- - It works in your development environment. Staging and production get your content when you promote.
15
-
16
- ### Install it and sign in
17
-
18
- You need Node 18 or later.
19
-
20
- ```sh
21
- npm install -g @plaiful/cli
22
- plaiful login
23
- ```
24
-
25
- - `plaiful login` opens the CMS. Check the code matches, and approve. The sign-in lasts 12 hours.
26
- - You need to be on Plaiful's allowlist, and own your product or have it shared with you.
27
-
28
- ### What you'll use it for
29
-
30
- | To | Run |
31
- |---|---|
32
- | Get your game's repo | `plaiful clone <product>`, or `plaiful init <product>` in a repo you already have |
33
- | Get your product's settings | `plaiful docs pull` |
34
- | Read the docs | `plaiful docs`, `plaiful docs search <words>` |
35
- | Load your world into Plaiful | `plaiful seed world`, then `plaiful seed world --apply` (and `lore`, `map`, `personas`) |
36
- | See what Plaiful has | `plaiful status`, `plaiful quests`, `plaiful lore`, `plaiful world`, `plaiful assets` |
37
- | Get a cinematic script for a world event | `plaiful events script write <eventId> --wait`, then `plaiful events script export <eventId> --fountain` |
38
- | Animate characters: a set of sprite sheets (idle, attacks, hurt, poses, a walk sheet) per record | `plaiful animation sets`, then `plaiful animation run <set> <agent> --all` |
39
- | Make or change an art style, and its reference images | `plaiful styles save` (a dry run), then `--apply`; `plaiful styles images add <id> <images>` |
40
- | Publish your OVID declaration | `plaiful ovid check`, then `plaiful ovid publish` |
41
- | Tell HERMES your studio's strategy | `plaiful hermes strategy check`, then `plaiful hermes strategy publish` (your studio's admins) |
42
- | Run your studio's team | `plaiful studio show`, `plaiful studio invite <email> --role artist`, `plaiful studio remove <email>` (your studio's admins) |
43
- | Deploy and run worker agents | `plaiful agents deploy`, `plaiful agents run <name>` |
44
-
45
- Every load starts as a dry run: it shows what would change, and changes nothing until you add `--apply`.
46
-
47
- ### Keys for coding agents and CI
48
-
49
- - A coding agent working on its own, or a CI job, can use a key instead of a sign-in.
50
- - Your product's owner makes one in the CMS: **DevOps → Deployment → your product → CLI keys**.
51
- - A key works on one product, for the jobs you pick, and stops the moment you revoke it.
52
- - Keep it out of your repo.
53
-
54
- ## Part 2: for your coding agent
55
-
56
- Every command runs as the signed-in CMS account (or a product API key that account issued), on that account's
57
- products, in **dev**.
58
-
59
- ### Commands
60
-
61
- ```sh
62
- plaiful login # opens the CMS: check the code matches, approve. 12 hours.
63
- plaiful clone my-game # clone the game repo, write .env.development, docs pull, npm install, open Zed
64
- plaiful init my-game # (a repo you already have) writes .plaiful.json (commit it; no secrets) and makes the resources/ folders
65
- plaiful docs # the platform docs, live (docs read <doc>, docs search <words>, docs changes)
66
- plaiful docs pull # your client-config.md into docs/plaiful/ (--copies: local copies of the docs too)
67
- plaiful mcp # the docs as MCP tools for your coding assistant: claude mcp add plaiful -- plaiful mcp
68
- plaiful env # rewrite .env.development from the dev client config (keeps your own lines)
69
- plaiful ovid check # checks docs/plaiful/my-game-ovid-declaration.json
70
- plaiful ovid publish # checks it again and publishes it; OVID reads it within ~5 minutes
71
- plaiful ovid show # what OVID has now
72
- plaiful seed world # dry run: what resources/world/my-game/*.json make, and what changes in dev
73
- plaiful seed world --apply # write it (then lore, then map); --reset also puts the clock, reveals and NPC bindings back
74
- plaiful seed personas # THESPIS personas and situations from resources/personas/my-game/ (same dry run / --apply)
75
- plaiful status # what OVID and THESPIS have in dev: counts per store, the clock, the declaration
76
- plaiful assets # per agent: records, and how many have art made / pending / failed / none yet
77
- plaiful assets crew-portrait --state failed # one agent's records: state, why a render failed, where the files are
78
- plaiful assets battlefield --json # also: any step that failed ({step}_step_error), and a part's source_crop and depth_min / depth_max
79
- plaiful assets regenerate battlefield --state step_failed --steps depth # re-run a step (or, without --steps, re-render: a new picture)
80
- plaiful assets regenerate building --state no_model --model # a 3D model from each record's picture (a 2d+3d Art Style; Regenerate → 3D model)
81
- plaiful quests # the quests OVID wrote: steps, and what each pays (--track, --series); quests show <id>
82
- plaiful lore # the lore sets (lore show <setId>: a set's snippets)
83
- plaiful world # the world's states and events in story order, and the clock
84
- plaiful events script write y1-s2-m1-the-object-ev-the-recovery --wait # OVID writes the event's cinematic (a draft)
85
- plaiful events script get y1-s2-m1-the-object-ev-the-recovery # the screenplay page, the versions, Soter's flags
86
- plaiful events script export y1-s2-m1-the-object-ev-the-recovery --vo --out recovery-vo.csv # the voice-over sheet
87
- plaiful events script approve y1-s2-m1-the-object-ev-the-recovery 2 # the version the game gets (--retire withdraws it)
88
- plaiful events storyboard draw y1-s2-m1-the-object-ev-the-recovery --style ink-wash --wait # a frame per shot
89
- plaiful events storyboard get y1-s2-m1-the-object-ev-the-recovery --out boards/ # the frames, saved as PNGs
90
- plaiful events edit y1-s2-m1-the-object-ev-the-recovery --title "The Recovery" # or --description, --order, --directives f.json
91
- plaiful events delete <eventId> # and quests delete <questId>; --force for official canon
92
- plaiful lore add the-sundered-wake --narrative "…" # lore reveal|hide <snippetId>, lore remove <setId>
93
- plaiful world set kessel_well false --reason "raided" # world truth|faction|var add new ones
94
- plaiful canon event <eventId> official
95
- plaiful animation sets # the animation sets you can use (sets show <id>: its states)
96
- plaiful animation sets save # save your own sets from resources/animation/my-game/*.json (sets delete <id>)
97
- plaiful animation run creature crew-portrait --all # a set on an agent's records: one sprite sheet per state
98
- plaiful styles # the art styles you can use: Plaiful's shared ones (read-only) and yours
99
- plaiful styles show style-default --out resources/styles/my-game/my-ink.json # start from one (change its id)
100
- plaiful styles save # dry run: what resources/styles/my-game/*.json would create or change (--apply saves)
101
- plaiful styles images add my-ink ref1.png ref2.jpg # reference images for one of yours (images remove <id> <key>)
102
- plaiful agents # your product's SmartBuilder agents in dev (agents show <name>: one agent's config)
103
- plaiful agents deploy # deploy or redeploy every config in resources/agents/my-game/ (or name the files)
104
- plaiful agents run crew-portrait role=medic # make one record (placeholder values as key=value)
105
- plaiful agents batch crew-portrait --count 20 # start a batch (or a batch body file) → a job id
106
- plaiful agents status crew-portrait <jobId> # a batch's progress
107
- plaiful records import crew-portrait # dry run: records you wrote (resources/records/my-game/crew-portrait.json)
108
- # into the agent's table; --apply writes them, --no-render skips the art
109
- plaiful lists # the product's SSM lists
110
- plaiful lists set shop_type tavern blacksmith healer # write one (lists get shop_type reads it)
111
- plaiful midas check # check docs/plaiful/my-game-midas-declaration.json (publish: plaiful midas publish; show)
112
- plaiful midas health # MIDAS's analysis, per kind (balance: what's flagged; proposals; assess: run it now)
113
- plaiful midas wallet <uid> # a player's balances and history (wallet "platform"); midas ledger check <file>: a report's dry run
114
- plaiful midas pricing # what each quest pays, in your reward kinds (MIDAS); delivered in the quest's rewards
115
- plaiful midas pricing set scrap --base 20 --per-effort 10 # price a kind (unset <kind>, weight <step> <n>, apply [file])
116
- plaiful hermes strategy check # check docs/plaiful/hermes-strategy.json (publish: your studio's admins; no word: what HERMES has)
117
- plaiful studio list # your studios, and your role in each
118
- plaiful studio show # your studio's people and products (admins also see invites, seats and the presets)
119
- plaiful studio invite sam@example.com --role artist --products my-game # prints the invite link to send them
120
- plaiful studio invite lee@example.com --role admin # an admin: every area, every product
121
- plaiful studio invites # pending and expired invites (resend <inviteId>: a new link; cancel <inviteId>)
122
- plaiful studio set sam@example.com --role analyst --area art=edit # change someone; what you leave out stays as it is
123
- plaiful studio remove sam@example.com # asks first (--yes skips that); the product API keys they issued stop working
124
- plaiful studio audit --limit 20 # who changed what in the studio, newest first (--before <id> for older)
125
- plaiful upload ovid-map-biomes-tiles.json ovid-map-kingdoms-tiles.json ovid-map-colors.json # map tiles → map-data/
126
- plaiful whoami # who you are (or which key), and your products
127
- plaiful logout
128
- ```
129
-
130
- `plaiful help` lists every command and option.
131
-
132
- ### Notes
133
-
134
- - `--json` on any command prints the platform's answer as JSON (for agents). Exit codes: `0` done, `1` the platform
135
- said no (invalid, not allowed, not signed in), `2` the command itself was wrong.
136
- - Everything works in **dev**. Staging and prod get your content through Plaiful's promotion.
137
- - `docs pull` keeps `client-config.md` (your keys) out of git with `docs/plaiful/.gitignore`, and prints the
138
- `git rm --cached` line if it was committed before.
139
- - `clone` needs access to the repo on GitHub (git signed in: `gh auth login` or Git Credential Manager), and
140
- `npm install` needs npm access to the `@plaiful` packages. It writes `.env.development` only when the repo has the
141
- web template's `.env.development.example`.
142
- - `lists set` writes a StringList in your product's namespace. It won't touch a key (SecureString), a setting (a plain
143
- String), or `access/*` (who may play).
144
- - The sign-in is kept in `~/.plaiful/credentials`, never in the repo. `PLAIFUL_API_URL` or `--api` points at another API.
145
- - You need to be on the Plaiful allowlist, and own or be shared the product (Plaiful staff: every product).
146
- - `studio` commands act on your studio, not one product: every member can `show` it; only its admins invite, change,
147
- remove and read the `audit`. They need a sign-in (`plaiful login`), never a product key. In more than one studio,
148
- name it with `--studio <id or name>`. Roles: `admin`, or a preset (`producer`, `developer`, `narrative-designer`,
149
- `artist`, `game-designer`, `analyst`, `viewer`); `--area <area>=view|edit|manage|none` adjusts one area;
150
- `--products a,b` limits a member to some of the studio's products (default: all).
151
- - Plaiful doesn't email invites yet: `studio invite` and `studio resend` print the link, and you send it. It works
152
- for 7 days, for the invited email only.
153
- - From a PlaifulCMS checkout instead of npm: `npm install -g <path to PlaifulCMS>/packages/plaiful-cli`. The package
154
- is public on npmjs.com; it holds no secrets, and everything it does needs a CMS sign-in or a key.
155
-
156
- ### Keys for agents and CI
157
-
158
- A product's owner issues keys in the CMS: Product deployment → the product → **CLI keys**. A key is shown once; set
159
- it as `PLAIFUL_TOKEN` in CI or the agent's environment (never in the repo) and the CLI uses it instead of a sign-in:
160
-
161
- ```sh
162
- PLAIFUL_TOKEN=plf_k_… plaiful seed world --apply
163
- ```
164
-
165
- A key acts as the owner who issued it, on that one product, in dev, for the scopes picked (`docs`, `status`, `seed`,
166
- `ovid:publish`, `lists`, `upload`). Revoking it in the CMS stops it at once; so does its issuer losing the product. The
167
- same screen shows the product's activity: everything the CLI and its keys did.
168
-
169
- ### For Plaiful staff
170
-
171
- - **Design:** `docs/system/product/PARTNER_API_AND_CLI.md`.
172
- - **Publishing a new version:** bump `version` in `package.json`, then `npm publish` from this folder, signed in to
173
- npm as a member of the `plaiful` org.
174
- - **Tests:** the end-to-end tests run this CLI against the partner API handler:
175
- `lambda/functions/partner-api/__tests__/partner-api.test.js`.
176
- - **The model registry (`plaiful models`, staff only):** publish release cards with their files, push training data,
177
- and run GPU training on Google Cloud (`models train`, with your own `gcloud` sign-in). Guide:
178
- `docs/design/model-registry.md`; card format: `docs/design/model-card.md`. Tests:
179
- `lambda/functions/partner-api/__tests__/models.test.js` and `models-cli.test.js`.
1
+ # The Plaiful CLI
2
+
3
+ > `plaiful` is how your team, or your coding agent, works on your Plaiful product from your game's repo. **Part 1**
4
+ > is for the people on your team. **Part 2** is for your coding agent: every command.
5
+
6
+ ## Part 1: for your team
7
+
8
+ ### What it is
9
+
10
+ - A command-line tool for your Plaiful product: you type commands in a terminal, in your game's repo.
11
+ - It loads your data into Plaiful, reads back what Plaiful has, and reads the platform docs.
12
+ - It signs in as your CMS account, so it can only see and change your own products.
13
+ - It needs no AWS access.
14
+ - It works in your development environment. Staging and production get your content when you promote.
15
+
16
+ ### Install it and sign in
17
+
18
+ You need Node 18 or later.
19
+
20
+ ```sh
21
+ npm install -g @plaiful/cli
22
+ plaiful login
23
+ ```
24
+
25
+ - `plaiful login` opens the CMS. Check the code matches, and approve. The sign-in lasts 12 hours.
26
+ - You need to be on Plaiful's allowlist, and own your product or have it shared with you.
27
+
28
+ ### What you'll use it for
29
+
30
+ | To | Run |
31
+ |---|---|
32
+ | Get your game's repo | `plaiful clone <product>`, or `plaiful init <product>` in a repo you already have |
33
+ | Get your product's settings | `plaiful docs pull` |
34
+ | Read the docs | `plaiful docs`, `plaiful docs search <words>` |
35
+ | Load your world into Plaiful | `plaiful seed world`, then `plaiful seed world --apply` (and `lore`, `map`, `personas`) |
36
+ | See what Plaiful has | `plaiful status`, `plaiful quests`, `plaiful lore`, `plaiful world`, `plaiful assets` |
37
+ | Get a cinematic script for a world event | `plaiful events script write <eventId> --wait`, then `plaiful events script export <eventId> --fountain` |
38
+ | Animate characters: a set of sprite sheets (idle, attacks, hurt, poses, a walk sheet) per record | `plaiful animation sets`, then `plaiful animation run <set> <agent> --all` |
39
+ | Make or change an art style, and its reference images | `plaiful styles save` (a dry run), then `--apply`; `plaiful styles images add <id> <images>` |
40
+ | Publish your OVID declaration | `plaiful ovid check`, then `plaiful ovid publish` |
41
+ | Tell HERMES your studio's strategy | `plaiful hermes strategy check`, then `plaiful hermes strategy publish` (your studio's admins) |
42
+ | Run your studio's team | `plaiful studio show`, `plaiful studio invite <email> --role artist`, `plaiful studio remove <email>` (your studio's admins) |
43
+ | Deploy and run worker agents | `plaiful agents deploy`, `plaiful agents run <name>` |
44
+
45
+ Every load starts as a dry run: it shows what would change, and changes nothing until you add `--apply`.
46
+
47
+ ### Keys for coding agents and CI
48
+
49
+ - A coding agent working on its own, or a CI job, can use a key instead of a sign-in.
50
+ - Your product's owner makes one in the CMS: **DevOps → Deployment → your product → CLI keys**.
51
+ - A key works on one product, for the jobs you pick, and stops the moment you revoke it.
52
+ - Keep it out of your repo.
53
+
54
+ ## Part 2: for your coding agent
55
+
56
+ Every command runs as the signed-in CMS account (or a product API key that account issued), on that account's
57
+ products, in **dev**.
58
+
59
+ ### Commands
60
+
61
+ ```sh
62
+ plaiful login # opens the CMS: check the code matches, approve. 12 hours.
63
+ plaiful clone my-game # clone the game repo, write .env.development, docs pull, npm install, open Zed
64
+ plaiful init my-game # (a repo you already have) writes .plaiful.json (commit it; no secrets) and makes the resources/ folders
65
+ plaiful docs # the platform docs, live (docs read <doc>, docs search <words>, docs changes)
66
+ plaiful docs pull # your client-config.md into docs/plaiful/ (--copies: local copies of the docs too)
67
+ plaiful mcp # the docs as MCP tools for your coding assistant: claude mcp add plaiful -- plaiful mcp
68
+ plaiful env # rewrite .env.development from the dev client config (keeps your own lines)
69
+ plaiful ovid check # checks docs/plaiful/my-game-ovid-declaration.json
70
+ plaiful ovid publish # checks it again and publishes it; OVID reads it within ~5 minutes
71
+ plaiful ovid show # what OVID has now
72
+ plaiful seed world # dry run: what resources/world/my-game/*.json make, and what changes in dev
73
+ plaiful seed world --apply # write it (then lore, then map); --reset also puts the clock, reveals and NPC bindings back
74
+ plaiful seed personas # THESPIS personas and situations from resources/personas/my-game/ (same dry run / --apply)
75
+ plaiful status # what OVID and THESPIS have in dev: counts per store, the clock, the declaration
76
+ plaiful assets # per agent: records, and how many have art made / pending / failed / none yet
77
+ plaiful assets crew-portrait --state failed # one agent's records: state, why a render failed, where the files are
78
+ plaiful assets battlefield --json # also: any step that failed ({step}_step_error), and a part's source_crop and depth_min / depth_max
79
+ plaiful assets regenerate battlefield --state step_failed --steps depth # re-run a step (or, without --steps, re-render: a new picture)
80
+ plaiful assets regenerate building --state no_model --model # a 3D model from each record's picture (a 2d+3d Art Style; Regenerate → 3D model)
81
+ plaiful quests # the quests OVID wrote: steps, and what each pays (--track, --series); quests show <id>
82
+ plaiful lore # the lore sets (lore show <setId>: a set's snippets)
83
+ plaiful world # the world's states and events in story order, and the clock
84
+ plaiful events script write y1-s2-m1-the-object-ev-the-recovery --wait # OVID writes the event's cinematic (a draft)
85
+ plaiful events script get y1-s2-m1-the-object-ev-the-recovery # the screenplay page, the versions, Soter's flags
86
+ plaiful events script export y1-s2-m1-the-object-ev-the-recovery --vo --out recovery-vo.csv # the voice-over sheet
87
+ plaiful events script approve y1-s2-m1-the-object-ev-the-recovery 2 # the version the game gets (--retire withdraws it)
88
+ plaiful events storyboard draw y1-s2-m1-the-object-ev-the-recovery --style ink-wash --wait # a frame per shot
89
+ plaiful events storyboard get y1-s2-m1-the-object-ev-the-recovery --out boards/ # the frames, saved as PNGs
90
+ plaiful events edit y1-s2-m1-the-object-ev-the-recovery --title "The Recovery" # or --description, --order, --directives f.json
91
+ plaiful events delete <eventId> # and quests delete <questId>; --force for official canon
92
+ plaiful lore add the-sundered-wake --narrative "…" # lore reveal|hide <snippetId>, lore remove <setId>
93
+ plaiful world set kessel_well false --reason "raided" # world truth|faction|var add new ones
94
+ plaiful canon event <eventId> official
95
+ plaiful animation sets # the animation sets you can use (sets show <id>: its states)
96
+ plaiful animation sets save # save your own sets from resources/animation/my-game/*.json (sets delete <id>)
97
+ plaiful animation run creature crew-portrait --all # a set on an agent's records: one sprite sheet per state
98
+ plaiful styles # the art styles you can use: Plaiful's shared ones (read-only) and yours
99
+ plaiful styles show style-default --out resources/styles/my-game/my-ink.json # start from one (change its id)
100
+ plaiful styles save # dry run: what resources/styles/my-game/*.json would create or change (--apply saves)
101
+ plaiful styles images add my-ink ref1.png ref2.jpg # reference images for one of yours (images remove <id> <key>)
102
+ plaiful agents # your product's SmartBuilder agents in dev (agents show <name>: one agent's config)
103
+ plaiful agents deploy # deploy or redeploy every config in resources/agents/my-game/ (or name the files)
104
+ plaiful agents run crew-portrait role=medic # make one record (placeholder values as key=value)
105
+ plaiful agents batch crew-portrait --count 20 # start a batch (or a batch body file) → a job id
106
+ plaiful agents status crew-portrait <jobId> # a batch's progress
107
+ plaiful records import crew-portrait # dry run: records you wrote (resources/records/my-game/crew-portrait.json)
108
+ # into the agent's table; --apply writes them, --no-render skips the art
109
+ plaiful lists # the product's SSM lists
110
+ plaiful lists set shop_type tavern blacksmith healer # write one (lists get shop_type reads it)
111
+ plaiful midas check # check docs/plaiful/my-game-midas-declaration.json (publish: plaiful midas publish; show)
112
+ plaiful midas health # MIDAS's analysis, per kind (balance: what's flagged; proposals; assess: run it now)
113
+ plaiful midas wallet <uid> # a player's balances and history (wallet "platform"); midas ledger check <file>: a report's dry run
114
+ plaiful midas pricing # what each quest pays, in your reward kinds (MIDAS); delivered in the quest's rewards
115
+ plaiful midas pricing set scrap --base 20 --per-effort 10 # price a kind (unset <kind>, weight <step> <n>, apply [file])
116
+ plaiful hermes strategy check # check docs/plaiful/hermes-strategy.json (publish: your studio's admins; no word: what HERMES has)
117
+ plaiful studio list # your studios, and your role in each
118
+ plaiful studio show # your studio's people and products (admins also see invites, seats and the presets)
119
+ plaiful studio invite sam@example.com --role artist --products my-game # prints the invite link to send them
120
+ plaiful studio invite lee@example.com --role admin # an admin: every area, every product
121
+ plaiful studio invites # pending and expired invites (resend <inviteId>: a new link; cancel <inviteId>)
122
+ plaiful studio set sam@example.com --role analyst --area art=edit # change someone; what you leave out stays as it is
123
+ plaiful studio remove sam@example.com # asks first (--yes skips that); the product API keys they issued stop working
124
+ plaiful studio audit --limit 20 # who changed what in the studio, newest first (--before <id> for older)
125
+ plaiful upload ovid-map-biomes-tiles.json ovid-map-kingdoms-tiles.json ovid-map-colors.json # map tiles → map-data/
126
+ plaiful whoami # who you are (or which key), and your products
127
+ plaiful logout
128
+ ```
129
+
130
+ `plaiful help` lists every command and option.
131
+
132
+ ### Notes
133
+
134
+ - `--json` on any command prints the platform's answer as JSON (for agents). Exit codes: `0` done, `1` the platform
135
+ said no (invalid, not allowed, not signed in), `2` the command itself was wrong.
136
+ - Everything works in **dev**. Staging and prod get your content through Plaiful's promotion.
137
+ - `docs pull` keeps `client-config.md` (your keys) out of git with `docs/plaiful/.gitignore`, and prints the
138
+ `git rm --cached` line if it was committed before.
139
+ - `clone` needs access to the repo on GitHub (git signed in: `gh auth login` or Git Credential Manager), and
140
+ `npm install` needs npm access to the `@plaiful` packages. It writes `.env.development` only when the repo has the
141
+ web template's `.env.development.example`.
142
+ - `lists set` writes a StringList in your product's namespace. It won't touch a key (SecureString), a setting (a plain
143
+ String), or `access/*` (who may play).
144
+ - The sign-in is kept in `~/.plaiful/credentials`, never in the repo. `PLAIFUL_API_URL` or `--api` points at another API.
145
+ - You need to be on the Plaiful allowlist, and own or be shared the product (Plaiful staff: every product).
146
+ - `studio` commands act on your studio, not one product: every member can `show` it; only its admins invite, change,
147
+ remove and read the `audit`. They need a sign-in (`plaiful login`), never a product key. In more than one studio,
148
+ name it with `--studio <id or name>`. Roles: `admin`, or a preset (`producer`, `developer`, `narrative-designer`,
149
+ `artist`, `game-designer`, `analyst`, `viewer`); `--area <area>=view|edit|manage|none` adjusts one area;
150
+ `--products a,b` limits a member to some of the studio's products (default: all).
151
+ - Plaiful doesn't email invites yet: `studio invite` and `studio resend` print the link, and you send it. It works
152
+ for 7 days, for the invited email only.
153
+ - From a PlaifulCMS checkout instead of npm: `npm install -g <path to PlaifulCMS>/packages/plaiful-cli`. The package
154
+ is public on npmjs.com; it holds no secrets, and everything it does needs a CMS sign-in or a key.
155
+
156
+ ### Keys for agents and CI
157
+
158
+ A product's owner issues keys in the CMS: Product deployment → the product → **CLI keys**. A key is shown once; set
159
+ it as `PLAIFUL_TOKEN` in CI or the agent's environment (never in the repo) and the CLI uses it instead of a sign-in:
160
+
161
+ ```sh
162
+ PLAIFUL_TOKEN=plf_k_… plaiful seed world --apply
163
+ ```
164
+
165
+ A key acts as the owner who issued it, on that one product, in dev, for the scopes picked (`docs`, `status`, `seed`,
166
+ `ovid:publish`, `lists`, `upload`). Revoking it in the CMS stops it at once; so does its issuer losing the product. The
167
+ same screen shows the product's activity: everything the CLI and its keys did.
168
+
169
+ ### For Plaiful staff
170
+
171
+ - **Design:** `docs/system/product/PARTNER_API_AND_CLI.md`.
172
+ - **Publishing a new version:** bump `version` in `package.json`, then `npm publish` from this folder, signed in to
173
+ npm as a member of the `plaiful` org.
174
+ - **Tests:** the end-to-end tests run this CLI against the partner API handler:
175
+ `lambda/functions/partner-api/__tests__/partner-api.test.js`.
176
+ - **The model registry (`plaiful models`, staff only):** publish release cards with their files, push training data,
177
+ and run GPU training on Google Cloud (`models train`, with your own `gcloud` sign-in). Guide:
178
+ `docs/design/model-registry.md`; card format: `docs/design/model-card.md`. Tests:
179
+ `lambda/functions/partner-api/__tests__/models.test.js` and `models-cli.test.js`.
180
+
181
+ ## Licence
182
+
183
+ Apache License 2.0: see [LICENSE](LICENSE). Versions up to 0.16.2 were published without a licence. The licence
184
+ covers this CLI only, not the Plaiful name or logo, and not the Plaiful platform it talks to.
package/package.json CHANGED
@@ -1,21 +1,22 @@
1
- {
2
- "name": "@plaiful/cli",
3
- "version": "0.16.1",
4
- "description": "The Plaiful CLI: work on your Plaiful product from your game repo, with no AWS access",
5
- "bin": {
6
- "plaiful": "bin/plaiful.js"
7
- },
8
- "files": [
9
- "bin",
10
- "src",
11
- "README.md"
12
- ],
13
- "engines": {
14
- "node": ">=18"
15
- },
16
- "license": "UNLICENSED",
17
- "publishConfig": {
18
- "registry": "https://registry.npmjs.org/",
19
- "access": "public"
20
- }
21
- }
1
+ {
2
+ "name": "@plaiful/cli",
3
+ "version": "0.16.3",
4
+ "description": "The Plaiful CLI: work on your Plaiful product from your game repo, with no AWS access",
5
+ "bin": {
6
+ "plaiful": "bin/plaiful.js"
7
+ },
8
+ "files": [
9
+ "bin",
10
+ "src",
11
+ "README.md",
12
+ "LICENSE"
13
+ ],
14
+ "engines": {
15
+ "node": ">=18"
16
+ },
17
+ "license": "Apache-2.0",
18
+ "publishConfig": {
19
+ "registry": "https://registry.npmjs.org/",
20
+ "access": "public"
21
+ }
22
+ }
package/src/train.js CHANGED
@@ -1,260 +1,264 @@
1
- 'use strict';
2
-
3
- /**
4
- * `plaiful models train …`: run a training job on a Google Cloud GPU (Vertex AI custom training) instead of the
5
- * developer's own machine, so the GPU time draws on Plaiful's Google Cloud credits (PlaifulCMS
6
- * docs/design/model-registry.md §5). Plaiful staff only for now, and it runs on this machine's `gcloud` sign-in: the
7
- * platform holds no Google credentials.
8
- *
9
- * A job: the code folder and the data folders are copied to the project's bucket (data is cached across jobs), Vertex
10
- * AI runs the entry command on one GPU with the bucket mounted at /gcs/<bucket>, the job writes to {out}, and
11
- * `train fetch` brings the output home, ready to card and `plaiful models publish`.
12
- *
13
- * Settings, from flags, else .plaiful.json "training": { project, region, bucket, image }, else PLAIFUL_GCP_* env.
14
- */
15
-
16
- const fs = require('fs');
17
- const os = require('os');
18
- const path = require('path');
19
-
20
- /** One GPU per job, by name: the machine Vertex AI pairs with it. */
21
- const GPUS = {
22
- l4: { machineType: 'g2-standard-8', acceleratorType: 'NVIDIA_L4' },
23
- t4: { machineType: 'n1-standard-8', acceleratorType: 'NVIDIA_TESLA_T4' },
24
- a100: { machineType: 'a2-highgpu-1g', acceleratorType: 'NVIDIA_TESLA_A100' },
25
- };
26
- // Google's prebuilt PyTorch training image. Check it against Google's current list on the first run (model-registry.md §5).
27
- const DEFAULT_IMAGE = 'us-docker.pkg.dev/vertex-ai/training/pytorch-gpu.2-1.py310:latest';
28
- const DEFAULT_REGION = 'us-central1';
29
- const DEFAULT_HOURS = 12;
30
- const CODE_EXCLUDE = '(^|/)(\\.git|node_modules|__pycache__|\\.venv|venv)(/|$)';
31
-
32
- const jobsFile = () => path.join(process.env.PLAIFUL_HOME || path.join(os.homedir(), '.plaiful'), 'train-jobs.json');
33
- function readJobs() { try { return JSON.parse(fs.readFileSync(jobsFile(), 'utf8')); } catch { return []; } }
34
- function writeJobs(jobs) { fs.mkdirSync(path.dirname(jobsFile()), { recursive: true }); fs.writeFileSync(jobsFile(), `${JSON.stringify(jobs, null, 2)}\n`); }
35
-
36
- /** A name gcloud and the bucket accept: lowercase letters, digits and dashes. */
37
- const slug = (s) => String(s).toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40);
38
- const stamp = (d = new Date()) => d.toISOString().replace(/[-:]/g, '').replace(/\..*/, '').replace('T', '-').toLowerCase();
39
-
40
- /** The job's settings → { project, region, bucket, image } (bucket without gs://). */
41
- function settings(flags, repoConfig) {
42
- const t = (repoConfig && repoConfig.training) || {};
43
- const s = {
44
- project: flags.project || t.project || process.env.PLAIFUL_GCP_PROJECT,
45
- region: flags.region || t.region || process.env.PLAIFUL_GCP_REGION || DEFAULT_REGION,
46
- bucket: String(flags.bucket || t.bucket || process.env.PLAIFUL_GCP_BUCKET || '').replace(/^gs:\/\//, '').replace(/\/+$/, ''),
47
- image: flags.image || t.image || DEFAULT_IMAGE,
48
- };
49
- return s;
50
- }
51
-
52
- /** The shell script the container runs: copy the code out of the bucket, install, run the entry. */
53
- function jobScript({ bucket, id, entry }) {
54
- const root = `/gcs/${bucket}`;
55
- const cmd = entry.replace(/\{data\}/g, `${root}/data`).replace(/\{out\}/g, `${root}/jobs/${id}/out`);
56
- return [
57
- 'set -euo pipefail',
58
- `mkdir -p /tmp/code && cp -r ${root}/jobs/${id}/code/. /tmp/code/`,
59
- 'cd /tmp/code',
60
- 'if [ -f requirements.txt ]; then pip install -q -r requirements.txt; fi',
61
- 'mkdir -p "$PLAIFUL_OUT"',
62
- 'nvidia-smi --query-gpu=name,memory.total --format=csv || true',
63
- cmd,
64
- ].join('\n');
65
- }
66
-
67
- /** The Vertex AI CustomJobSpec (gcloud ai custom-jobs create --config). */
68
- function jobSpec({ bucket, id, entry, gpu, machine, image, hours, task }) {
69
- const g = GPUS[gpu];
70
- const root = `/gcs/${bucket}`;
71
- return {
72
- workerPoolSpecs: [{
73
- machineSpec: { machineType: machine || g.machineType, acceleratorType: g.acceleratorType, acceleratorCount: 1 },
74
- replicaCount: 1,
75
- diskSpec: { bootDiskType: 'pd-ssd', bootDiskSizeGb: 100 },
76
- containerSpec: {
77
- imageUri: image,
78
- command: ['bash', '-c'],
79
- args: [jobScript({ bucket, id, entry })],
80
- env: [
81
- { name: 'PLAIFUL_JOB', value: id },
82
- { name: 'PLAIFUL_TASK', value: task },
83
- { name: 'PLAIFUL_DATA', value: `${root}/data` },
84
- { name: 'PLAIFUL_OUT', value: `${root}/jobs/${id}/out` },
85
- ],
86
- },
87
- }],
88
- scheduling: { timeout: `${Math.round(hours * 3600)}s` },
89
- };
90
- }
91
-
92
- function makeTrain({ UsageError, ApiError, repo, models }) {
93
- /** Run gcloud, capturing its output. → stdout; throws on failure with gcloud's own message. */
94
- function gcloud(ctx, args, { json = false, inherit = false } = {}) {
95
- const argv = [...args, ...(json ? ['--format=json'] : [])];
96
- if (inherit) {
97
- const r = ctx.io.exec('gcloud', argv, { inherit: true });
98
- if (r.status !== 0) throw new ApiError(0, { code: 'gcloud', error: `gcloud ${args.slice(0, 3).join(' ')} failed (exit ${r.status})` });
99
- return '';
100
- }
101
- const r = ctx.io.exec('gcloud', argv);
102
- if (r.status !== 0) {
103
- const msg = String(r.stderr || r.stdout || '').trim().split('\n').filter((l) => /ERROR|error/.test(l)).slice(-2).join(' ') || `exit ${r.status}`;
104
- throw new ApiError(0, { code: 'gcloud', error: `gcloud ${args.slice(0, 3).join(' ')} failed: ${msg}${/auth|login|credential/i.test(msg) ? ' (run `gcloud auth login`)' : ''}` });
105
- }
106
- return json ? JSON.parse(r.stdout || 'null') : r.stdout;
107
- }
108
-
109
- function need(s) {
110
- if (!s.project) throw new UsageError('which Google Cloud project? --project, or "training": { "project": … } in .plaiful.json');
111
- if (!s.bucket) throw new UsageError('which bucket for job files? --bucket, or "training": { "bucket": … } in .plaiful.json (in the job\'s region)');
112
- }
113
-
114
- /** `plaiful models train check`: is this machine and project ready to run a job? */
115
- async function check(ctx) {
116
- const r = repo(ctx, { required: false });
117
- const s = settings(ctx.flags, r.found && r.found.config);
118
- const lines = [];
119
- const ok = (good, text) => { lines.push(`${good ? '✓' : '✗'} ${text}`); return good; };
120
- let fine = true;
121
- const ver = ctx.io.exec('gcloud', ['--version']);
122
- fine = ok(ver.status === 0, ver.status === 0 ? `gcloud: ${String(ver.stdout).split('\n')[0]}` : 'gcloud isn\'t installed (https://cloud.google.com/sdk)') && fine;
123
- if (ver.status === 0) {
124
- const acct = ctx.io.exec('gcloud', ['auth', 'print-access-token', '--quiet']);
125
- fine = ok(acct.status === 0, acct.status === 0 ? 'signed in to Google Cloud' : 'not signed in: run `gcloud auth login`') && fine;
126
- fine = ok(!!s.project, s.project ? `project: ${s.project}` : 'no project set (--project or .plaiful.json training.project)') && fine;
127
- fine = ok(!!s.bucket, s.bucket ? `bucket: gs://${s.bucket} (region ${s.region})` : 'no bucket set (--bucket or .plaiful.json training.bucket)') && fine;
128
- if (acct.status === 0 && s.project) {
129
- const api = ctx.io.exec('gcloud', ['services', 'list', '--enabled', `--project=${s.project}`, '--filter=config.name=aiplatform.googleapis.com', '--format=value(config.name)']);
130
- fine = ok(api.status === 0 && /aiplatform/.test(api.stdout), api.status === 0 && /aiplatform/.test(api.stdout) ? 'Vertex AI API enabled' : `Vertex AI API not enabled: gcloud services enable aiplatform.googleapis.com --project=${s.project}`) && fine;
131
- if (s.bucket) {
132
- const b = ctx.io.exec('gcloud', ['storage', 'buckets', 'describe', `gs://${s.bucket}`, `--project=${s.project}`, '--format=value(location)']);
133
- fine = ok(b.status === 0, b.status === 0 ? `bucket found (${String(b.stdout).trim().toLowerCase()})` : `bucket gs://${s.bucket} not found: gcloud storage buckets create gs://${s.bucket} --project=${s.project} --location=${s.region} --uniform-bucket-level-access`) && fine;
134
- }
135
- }
136
- }
137
- lines.push(` image: ${s.image}`);
138
- lines.push(' GPU quota (Vertex AI custom training, per region) is in the console: IAM & Admin → Quotas, "custom model training"');
139
- ctx.out(lines.join('\n'), { success: fine, settings: s });
140
- return fine ? 0 : 1;
141
- }
142
-
143
- /** `plaiful models train submit <task> --code <dir> --entry "<command>" [--data a,b] [--snapshot task/snap] [--gpu l4]` */
144
- async function submit(ctx, [task]) {
145
- if (!task) throw new UsageError('plaiful models train submit <task> --code <folder> --entry "python train.py --data {data} --out {out}" [--data <folders>] [--gpu l4|t4|a100] [--hours 12]');
146
- const r = repo(ctx, { required: false });
147
- const s = settings(ctx.flags, r.found && r.found.config);
148
- need(s);
149
- const gpu = String(ctx.flags.gpu || 'l4').toLowerCase();
150
- if (!GPUS[gpu]) throw new UsageError(`--gpu must be ${Object.keys(GPUS).join(', ')}`);
151
- const hours = ctx.flags.hours ? Number(ctx.flags.hours) : DEFAULT_HOURS;
152
- if (!(hours > 0 && hours <= 72)) throw new UsageError('--hours must be between 0 and 72 (the job is stopped after it)');
153
- if (!ctx.flags.code || !ctx.flags.entry) throw new UsageError('--code <folder> and --entry "<command>" are required ({data} and {out} are filled in)');
154
- const code = path.resolve(ctx.io.cwd(), ctx.flags.code);
155
- if (!fs.existsSync(code) || !fs.statSync(code).isDirectory()) throw new UsageError(`${code} isn't a folder`);
156
- const id = `${slug(ctx.flags.name || task)}-${stamp()}`;
157
-
158
- // Data: local folders, and registry snapshots pulled to a local cache first. Each lands in gs://<bucket>/data/<name>/.
159
- const data = [];
160
- for (const d of String(ctx.flags.data || '').split(',').map((x) => x.trim()).filter(Boolean)) {
161
- const abs = path.resolve(ctx.io.cwd(), d);
162
- if (!fs.existsSync(abs) || !fs.statSync(abs).isDirectory()) throw new UsageError(`--data ${abs} isn't a folder`);
163
- data.push({ local: abs, name: slug(path.basename(abs)) || 'data' });
164
- }
165
- for (const snap of String(ctx.flags.snapshot || '').split(',').map((x) => x.trim()).filter(Boolean)) {
166
- const [st, sid] = snap.split('/');
167
- if (!st || !sid) throw new UsageError('--snapshot is <task>/<snapshot>, e.g. voice.radio/voicedata-cast');
168
- const cache = path.join(process.env.PLAIFUL_HOME || path.join(os.homedir(), '.plaiful'), 'cache', 'datasets', st, sid);
169
- await models.dataPull({ ...ctx, flags: { ...ctx.flags, out: cache } }, [st, sid]);
170
- data.push({ local: cache, name: `${slug(st)}-${slug(sid)}` });
171
- }
172
-
173
- ctx.io.stderr.write(`Copying the code to gs://${s.bucket}/jobs/${id}/code …\n`);
174
- gcloud(ctx, ['storage', 'rsync', code, `gs://${s.bucket}/jobs/${id}/code`, '--recursive', `--exclude=${CODE_EXCLUDE}`, `--project=${s.project}`], { inherit: true });
175
- for (const d of data) {
176
- ctx.io.stderr.write(`Syncing ${d.local} → gs://${s.bucket}/data/${d.name} (only what changed) …\n`);
177
- gcloud(ctx, ['storage', 'rsync', d.local, `gs://${s.bucket}/data/${d.name}`, '--recursive', `--project=${s.project}`], { inherit: true });
178
- }
179
-
180
- // gcloud reads the config as YAML, and JSON is YAML.
181
- const spec = jobSpec({ bucket: s.bucket, id, entry: ctx.flags.entry, gpu, machine: ctx.flags.machine, image: s.image, hours, task });
182
- const cfg = path.join(os.tmpdir(), `plaiful-job-${id}.json`);
183
- fs.writeFileSync(cfg, JSON.stringify(spec, null, 2));
184
- let job;
185
- try {
186
- job = gcloud(ctx, ['ai', 'custom-jobs', 'create', `--project=${s.project}`, `--region=${s.region}`, `--display-name=${id}`, `--config=${cfg}`,
187
- `--labels=plaiful-job=${id},plaiful-task=${slug(task)},plaiful-gpu=${gpu}`], { json: true });
188
- } finally { try { fs.unlinkSync(cfg); } catch { /* temp file */ } }
189
- const record = { id, name: job && job.name, task, gpu, machine: spec.workerPoolSpecs[0].machineSpec.machineType, hours, project: s.project, region: s.region, bucket: s.bucket, data: data.map((d) => d.name), submitted_at: new Date().toISOString() };
190
- writeJobs([...readJobs(), record]);
191
- ctx.out([
192
- `Submitted ${id} on one ${gpu.toUpperCase()} (${record.machine}), stopped after ${hours} h at most.`,
193
- ` output: gs://${s.bucket}/jobs/${id}/out`,
194
- ` plaiful models train status ${id} · plaiful models train logs ${id} · plaiful models train fetch ${id}`,
195
- ].join('\n'), { success: true, job: record });
196
- return 0;
197
- }
198
-
199
- function findJob(id) {
200
- const jobs = readJobs();
201
- const j = id ? jobs.find((x) => x.id === id) : jobs[jobs.length - 1];
202
- if (!j) throw new UsageError(id ? `no job ${id} submitted from this machine (plaiful models train list)` : 'no jobs submitted from this machine yet');
203
- return j;
204
- }
205
-
206
- /** Vertex AI's view of a job → { state, started, ended, gpu_hours, error } */
207
- function describe(ctx, j) {
208
- const d = gcloud(ctx, ['ai', 'custom-jobs', 'describe', j.name, `--region=${j.region}`, `--project=${j.project}`], { json: true });
209
- const start = d.startTime ? Date.parse(d.startTime) : null;
210
- const end = d.endTime ? Date.parse(d.endTime) : (start ? Date.now() : null);
211
- return { state: String(d.state || '').replace(/^JOB_STATE_/, '').toLowerCase(), created: d.createTime, started: d.startTime || null, ended: d.endTime || null, gpu_hours: start ? Math.round(((end - start) / 3.6e6) * 100) / 100 : 0, error: d.error && d.error.message };
212
- }
213
-
214
- async function status(ctx, [id]) {
215
- const j = findJob(id);
216
- const d = describe(ctx, j);
217
- ctx.out([
218
- `${j.id}: ${d.state} (${j.gpu.toUpperCase()}, ${j.task})`,
219
- ` submitted ${j.submitted_at}${d.started ? `, started ${d.started}` : ', waiting for a GPU'}${d.ended ? `, ended ${d.ended}` : ''}`,
220
- ` GPU time so far: ${d.gpu_hours} h (billed to ${j.project}; Billing → Reports, label plaiful-job=${j.id})`,
221
- ...(d.error ? [` error: ${d.error}`] : []),
222
- ].join('\n'), { success: true, job: j, ...d });
223
- return 0;
224
- }
225
-
226
- async function list(ctx) {
227
- const jobs = readJobs();
228
- if (!jobs.length) { ctx.out('No training jobs submitted from this machine yet.', { success: true, jobs: [] }); return 0; }
229
- const rows = jobs.slice(-20).map((j) => { let d = {}; try { d = describe(ctx, j); } catch (e) { d = { state: `unknown (${e.message})` }; } return { ...j, ...d }; });
230
- ctx.out(rows.map((j) => `${j.id} ${j.state} ${j.gpu} ${j.gpu_hours != null ? `${j.gpu_hours} GPU-h` : ''} ${j.task}`).join('\n'), { success: true, jobs: rows });
231
- return 0;
232
- }
233
-
234
- async function logs(ctx, [id]) {
235
- const j = findJob(id);
236
- gcloud(ctx, ['ai', 'custom-jobs', 'stream-logs', j.name, `--region=${j.region}`, `--project=${j.project}`], { inherit: true });
237
- return 0;
238
- }
239
-
240
- async function fetch(ctx, [id]) {
241
- const j = findJob(id);
242
- const out = path.resolve(ctx.io.cwd(), ctx.flags.out || path.join('model-runs', j.id));
243
- fs.mkdirSync(out, { recursive: true });
244
- gcloud(ctx, ['storage', 'rsync', `gs://${j.bucket}/jobs/${j.id}/out`, out, '--recursive', `--project=${j.project}`], { inherit: true });
245
- ctx.out(`${j.id}'s output is in ${out}. Card it, then plaiful models publish <card.json>.`, { success: true, out });
246
- return 0;
247
- }
248
-
249
- async function cancel(ctx, [id]) {
250
- const j = findJob(id);
251
- if (!id) throw new UsageError('cancel which job? plaiful models train cancel <job>');
252
- gcloud(ctx, ['ai', 'custom-jobs', 'cancel', j.name, `--region=${j.region}`, `--project=${j.project}`]);
253
- ctx.out(`Asked Vertex AI to cancel ${j.id}.`, { success: true });
254
- return 0;
255
- }
256
-
257
- return { check, submit, status, list, logs, fetch, cancel };
258
- }
259
-
260
- module.exports = { makeTrain, jobSpec, jobScript, settings, GPUS, DEFAULT_IMAGE, slug };
1
+ 'use strict';
2
+
3
+ /**
4
+ * `plaiful models train …`: run a training job on a Google Cloud GPU (Vertex AI custom training) instead of the
5
+ * developer's own machine, so the GPU time draws on Plaiful's Google Cloud credits (PlaifulCMS
6
+ * docs/design/model-registry.md §5). Plaiful staff only for now, and it runs on this machine's `gcloud` sign-in: the
7
+ * platform holds no Google credentials.
8
+ *
9
+ * A job: the code folder and the data folders are copied to the project's bucket (data is cached across jobs), Vertex
10
+ * AI runs the entry command on one GPU with the bucket mounted at /gcs/<bucket>, the job writes to {out}, and
11
+ * `train fetch` brings the output home, ready to card and `plaiful models publish`.
12
+ *
13
+ * Settings, from flags, else .plaiful.json "training": { project, region, bucket, image }, else PLAIFUL_GCP_* env.
14
+ */
15
+
16
+ const fs = require('fs');
17
+ const os = require('os');
18
+ const path = require('path');
19
+
20
+ /** One GPU per job, by name: the machine Vertex AI pairs with it. */
21
+ const GPUS = {
22
+ l4: { machineType: 'g2-standard-8', acceleratorType: 'NVIDIA_L4' },
23
+ t4: { machineType: 'n1-standard-8', acceleratorType: 'NVIDIA_TESLA_T4' },
24
+ a100: { machineType: 'a2-highgpu-1g', acceleratorType: 'NVIDIA_TESLA_A100' },
25
+ };
26
+ // Google's newest prebuilt PyTorch training image. The 2.1 image is deprecated, and Vertex AI failed every job on it
27
+ // with only "Internal error" (2026-11-16).
28
+ const DEFAULT_IMAGE = 'us-docker.pkg.dev/vertex-ai/training/pytorch-gpu.2-4.py310:latest';
29
+ const DEFAULT_REGION = 'us-central1';
30
+ const DEFAULT_HOURS = 12;
31
+ const CODE_EXCLUDE = '(^|/)(\\.git|node_modules|__pycache__|\\.venv|venv)(/|$)';
32
+
33
+ const jobsFile = () => path.join(process.env.PLAIFUL_HOME || path.join(os.homedir(), '.plaiful'), 'train-jobs.json');
34
+ function readJobs() { try { return JSON.parse(fs.readFileSync(jobsFile(), 'utf8')); } catch { return []; } }
35
+ function writeJobs(jobs) { fs.mkdirSync(path.dirname(jobsFile()), { recursive: true }); fs.writeFileSync(jobsFile(), `${JSON.stringify(jobs, null, 2)}\n`); }
36
+
37
+ /** A name gcloud and the bucket accept: lowercase letters, digits and dashes. */
38
+ const slug = (s) => String(s).toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40);
39
+ const stamp = (d = new Date()) => d.toISOString().replace(/[-:]/g, '').replace(/\..*/, '').replace('T', '-').toLowerCase();
40
+
41
+ /** The job's settings → { project, region, bucket, image } (bucket without gs://). */
42
+ function settings(flags, repoConfig) {
43
+ const t = (repoConfig && repoConfig.training) || {};
44
+ const s = {
45
+ project: flags.project || t.project || process.env.PLAIFUL_GCP_PROJECT,
46
+ region: flags.region || t.region || process.env.PLAIFUL_GCP_REGION || DEFAULT_REGION,
47
+ bucket: String(flags.bucket || t.bucket || process.env.PLAIFUL_GCP_BUCKET || '').replace(/^gs:\/\//, '').replace(/\/+$/, ''),
48
+ image: flags.image || t.image || DEFAULT_IMAGE,
49
+ };
50
+ return s;
51
+ }
52
+
53
+ /** The shell script the container runs: copy the code out of the bucket, install, run the entry. */
54
+ function jobScript({ bucket, id, entry }) {
55
+ const root = `/gcs/${bucket}`;
56
+ const cmd = entry.replace(/\{data\}/g, `${root}/data`).replace(/\{out\}/g, `${root}/jobs/${id}/out`);
57
+ return [
58
+ 'set -euo pipefail',
59
+ `mkdir -p /tmp/code && cp -r ${root}/jobs/${id}/code/. /tmp/code/`,
60
+ 'cd /tmp/code',
61
+ 'if [ -f requirements.txt ]; then pip install -q -r requirements.txt; fi',
62
+ 'mkdir -p "$PLAIFUL_OUT"',
63
+ 'nvidia-smi --query-gpu=name,memory.total --format=csv || true',
64
+ cmd,
65
+ ].join('\n');
66
+ }
67
+
68
+ /** The Vertex AI CustomJobSpec (gcloud ai custom-jobs create --config). */
69
+ function jobSpec({ bucket, id, entry, gpu, machine, image, hours, task }) {
70
+ const g = GPUS[gpu];
71
+ const root = `/gcs/${bucket}`;
72
+ return {
73
+ workerPoolSpecs: [{
74
+ machineSpec: { machineType: machine || g.machineType, acceleratorType: g.acceleratorType, acceleratorCount: 1 },
75
+ replicaCount: 1,
76
+ diskSpec: { bootDiskType: 'pd-ssd', bootDiskSizeGb: 100 },
77
+ containerSpec: {
78
+ imageUri: image,
79
+ command: ['bash', '-c'],
80
+ args: [jobScript({ bucket, id, entry })],
81
+ env: [
82
+ { name: 'PLAIFUL_JOB', value: id },
83
+ { name: 'PLAIFUL_TASK', value: task },
84
+ { name: 'PLAIFUL_DATA', value: `${root}/data` },
85
+ { name: 'PLAIFUL_OUT', value: `${root}/jobs/${id}/out` },
86
+ ],
87
+ },
88
+ }],
89
+ scheduling: { timeout: `${Math.round(hours * 3600)}s` },
90
+ };
91
+ }
92
+
93
+ function makeTrain({ UsageError, ApiError, repo, models }) {
94
+ /** Run gcloud, capturing its output. → stdout; throws on failure with gcloud's own message. */
95
+ function gcloud(ctx, args, { json = false, inherit = false } = {}) {
96
+ const argv = [...args, ...(json ? ['--format=json'] : [])];
97
+ if (inherit) {
98
+ const r = ctx.io.exec('gcloud', argv, { inherit: true });
99
+ if (r.status !== 0) throw new ApiError(0, { code: 'gcloud', error: `gcloud ${args.slice(0, 3).join(' ')} failed (exit ${r.status})` });
100
+ return '';
101
+ }
102
+ const r = ctx.io.exec('gcloud', argv);
103
+ if (r.status !== 0) {
104
+ const msg = String(r.stderr || r.stdout || '').trim().split('\n').filter((l) => /ERROR|error/.test(l)).slice(-2).join(' ') || `exit ${r.status}`;
105
+ throw new ApiError(0, { code: 'gcloud', error: `gcloud ${args.slice(0, 3).join(' ')} failed: ${msg}${/auth|login|credential/i.test(msg) ? ' (run `gcloud auth login`)' : ''}` });
106
+ }
107
+ return json ? JSON.parse(r.stdout || 'null') : r.stdout;
108
+ }
109
+
110
+ function need(s) {
111
+ if (!s.project) throw new UsageError('which Google Cloud project? --project, or "training": { "project": … } in .plaiful.json');
112
+ if (!s.bucket) throw new UsageError('which bucket for job files? --bucket, or "training": { "bucket": … } in .plaiful.json (in the job\'s region)');
113
+ }
114
+
115
+ /** `plaiful models train check`: is this machine and project ready to run a job? */
116
+ async function check(ctx) {
117
+ const r = repo(ctx, { required: false });
118
+ const s = settings(ctx.flags, r.found && r.found.config);
119
+ const lines = [];
120
+ const ok = (good, text) => { lines.push(`${good ? '✓' : '✗'} ${text}`); return good; };
121
+ let fine = true;
122
+ const ver = ctx.io.exec('gcloud', ['--version']);
123
+ fine = ok(ver.status === 0, ver.status === 0 ? `gcloud: ${String(ver.stdout).split('\n')[0]}` : 'gcloud isn\'t installed (https://cloud.google.com/sdk)') && fine;
124
+ if (ver.status === 0) {
125
+ const acct = ctx.io.exec('gcloud', ['auth', 'print-access-token', '--quiet']);
126
+ fine = ok(acct.status === 0, acct.status === 0 ? 'signed in to Google Cloud' : 'not signed in: run `gcloud auth login`') && fine;
127
+ fine = ok(!!s.project, s.project ? `project: ${s.project}` : 'no project set (--project or .plaiful.json training.project)') && fine;
128
+ fine = ok(!!s.bucket, s.bucket ? `bucket: gs://${s.bucket} (region ${s.region})` : 'no bucket set (--bucket or .plaiful.json training.bucket)') && fine;
129
+ if (acct.status === 0 && s.project) {
130
+ const api = ctx.io.exec('gcloud', ['services', 'list', '--enabled', `--project=${s.project}`, '--filter=config.name=aiplatform.googleapis.com', '--format=value(config.name)']);
131
+ fine = ok(api.status === 0 && /aiplatform/.test(api.stdout), api.status === 0 && /aiplatform/.test(api.stdout) ? 'Vertex AI API enabled' : `Vertex AI API not enabled: gcloud services enable aiplatform.googleapis.com --project=${s.project}`) && fine;
132
+ if (s.bucket) {
133
+ const b = ctx.io.exec('gcloud', ['storage', 'buckets', 'describe', `gs://${s.bucket}`, `--project=${s.project}`, '--format=value(location)']);
134
+ fine = ok(b.status === 0, b.status === 0 ? `bucket found (${String(b.stdout).trim().toLowerCase()})` : `bucket gs://${s.bucket} not found: gcloud storage buckets create gs://${s.bucket} --project=${s.project} --location=${s.region} --uniform-bucket-level-access`) && fine;
135
+ }
136
+ }
137
+ }
138
+ lines.push(` image: ${s.image}`);
139
+ lines.push(' GPU quota (Vertex AI custom training, per region) is in the console: IAM & Admin → Quotas, "custom model training"');
140
+ ctx.out(lines.join('\n'), { success: fine, settings: s });
141
+ return fine ? 0 : 1;
142
+ }
143
+
144
+ /** `plaiful models train submit <task> --code <dir> --entry "<command>" [--data a,b] [--snapshot task/snap] [--gpu l4]` */
145
+ async function submit(ctx, [task]) {
146
+ if (!task) throw new UsageError('plaiful models train submit <task> --code <folder> --entry "python train.py --data {data} --out {out}" [--data <folders>] [--gpu l4|t4|a100] [--hours 12]');
147
+ const r = repo(ctx, { required: false });
148
+ const s = settings(ctx.flags, r.found && r.found.config);
149
+ need(s);
150
+ const gpu = String(ctx.flags.gpu || 'l4').toLowerCase();
151
+ if (!GPUS[gpu]) throw new UsageError(`--gpu must be ${Object.keys(GPUS).join(', ')}`);
152
+ const hours = ctx.flags.hours ? Number(ctx.flags.hours) : DEFAULT_HOURS;
153
+ if (!(hours > 0 && hours <= 72)) throw new UsageError('--hours must be between 0 and 72 (the job is stopped after it)');
154
+ if (!ctx.flags.code || !ctx.flags.entry) throw new UsageError('--code <folder> and --entry "<command>" are required ({data} and {out} are filled in)');
155
+ const code = path.resolve(ctx.io.cwd(), ctx.flags.code);
156
+ if (!fs.existsSync(code) || !fs.statSync(code).isDirectory()) throw new UsageError(`${code} isn't a folder`);
157
+ const id = `${slug(ctx.flags.name || task)}-${stamp()}`;
158
+
159
+ // Data: local folders, and registry snapshots pulled to a local cache first. Each lands in gs://<bucket>/data/<name>/.
160
+ const data = [];
161
+ for (const d of String(ctx.flags.data || '').split(',').map((x) => x.trim()).filter(Boolean)) {
162
+ const abs = path.resolve(ctx.io.cwd(), d);
163
+ if (!fs.existsSync(abs) || !fs.statSync(abs).isDirectory()) throw new UsageError(`--data ${abs} isn't a folder`);
164
+ data.push({ local: abs, name: slug(path.basename(abs)) || 'data' });
165
+ }
166
+ for (const snap of String(ctx.flags.snapshot || '').split(',').map((x) => x.trim()).filter(Boolean)) {
167
+ const [st, sid] = snap.split('/');
168
+ if (!st || !sid) throw new UsageError('--snapshot is <task>/<snapshot>, e.g. voice.radio/voicedata-cast');
169
+ const cache = path.join(process.env.PLAIFUL_HOME || path.join(os.homedir(), '.plaiful'), 'cache', 'datasets', st, sid);
170
+ await models.dataPull({ ...ctx, flags: { ...ctx.flags, out: cache } }, [st, sid]);
171
+ data.push({ local: cache, name: `${slug(st)}-${slug(sid)}` });
172
+ }
173
+
174
+ ctx.io.stderr.write(`Copying the code to gs://${s.bucket}/jobs/${id}/code …\n`);
175
+ gcloud(ctx, ['storage', 'rsync', code, `gs://${s.bucket}/jobs/${id}/code`, '--recursive', `--exclude=${CODE_EXCLUDE}`, `--project=${s.project}`], { inherit: true });
176
+ for (const d of data) {
177
+ ctx.io.stderr.write(`Syncing ${d.local} → gs://${s.bucket}/data/${d.name} (only what changed) …\n`);
178
+ gcloud(ctx, ['storage', 'rsync', d.local, `gs://${s.bucket}/data/${d.name}`, '--recursive', `--project=${s.project}`], { inherit: true });
179
+ }
180
+
181
+ // gcloud reads the config as YAML, and JSON is YAML.
182
+ const spec = jobSpec({ bucket: s.bucket, id, entry: ctx.flags.entry, gpu, machine: ctx.flags.machine, image: s.image, hours, task });
183
+ const cfg = path.join(os.tmpdir(), `plaiful-job-${id}.json`);
184
+ fs.writeFileSync(cfg, JSON.stringify(spec, null, 2));
185
+ let job;
186
+ try {
187
+ job = gcloud(ctx, ['ai', 'custom-jobs', 'create', `--project=${s.project}`, `--region=${s.region}`, `--display-name=${id}`, `--config=${cfg}`,
188
+ `--labels=plaiful-job=${id},plaiful-task=${slug(task)},plaiful-gpu=${gpu}`], { json: true });
189
+ } finally { try { fs.unlinkSync(cfg); } catch { /* temp file */ } }
190
+ const record = { id, name: job && job.name, task, gpu, machine: spec.workerPoolSpecs[0].machineSpec.machineType, hours, project: s.project, region: s.region, bucket: s.bucket, data: data.map((d) => d.name), submitted_at: new Date().toISOString() };
191
+ writeJobs([...readJobs(), record]);
192
+ ctx.out([
193
+ `Submitted ${id} on one ${gpu.toUpperCase()} (${record.machine}), stopped after ${hours} h at most.`,
194
+ ` output: gs://${s.bucket}/jobs/${id}/out`,
195
+ ` plaiful models train status ${id} · plaiful models train logs ${id} · plaiful models train fetch ${id}`,
196
+ ].join('\n'), { success: true, job: record });
197
+ return 0;
198
+ }
199
+
200
+ function findJob(id) {
201
+ const jobs = readJobs();
202
+ const j = id ? jobs.find((x) => x.id === id) : jobs[jobs.length - 1];
203
+ if (!j) throw new UsageError(id ? `no job ${id} submitted from this machine (plaiful models train list)` : 'no jobs submitted from this machine yet');
204
+ return j;
205
+ }
206
+
207
+ /** Vertex AI's view of a job → { state, started, ended, gpu_hours, error } */
208
+ function describe(ctx, j) {
209
+ const d = gcloud(ctx, ['ai', 'custom-jobs', 'describe', j.name, `--region=${j.region}`, `--project=${j.project}`], { json: true });
210
+ const state = String(d.state || '').replace(/^JOB_STATE_/, '').toLowerCase();
211
+ // Vertex AI sets startTime as soon as a job is accepted, so a job still waiting for its machine isn't GPU time yet.
212
+ const waiting = ['queued', 'pending'].includes(state);
213
+ const start = d.startTime && !waiting ? Date.parse(d.startTime) : null;
214
+ const end = d.endTime ? Date.parse(d.endTime) : (start ? Date.now() : null);
215
+ return { state, created: d.createTime, started: d.startTime || null, ended: d.endTime || null, gpu_hours: start ? Math.round(((end - start) / 3.6e6) * 100) / 100 : 0, error: d.error && d.error.message };
216
+ }
217
+
218
+ async function status(ctx, [id]) {
219
+ const j = findJob(id);
220
+ const d = describe(ctx, j);
221
+ ctx.out([
222
+ `${j.id}: ${d.state} (${j.gpu.toUpperCase()}, ${j.task})`,
223
+ ` submitted ${j.submitted_at}${d.started ? `, started ${d.started}` : ', waiting for a GPU'}${d.ended ? `, ended ${d.ended}` : ''}`,
224
+ ` GPU time so far: ${d.gpu_hours} h (billed to ${j.project}; Billing → Reports, label plaiful-job=${j.id})`,
225
+ ...(d.error ? [` error: ${d.error}`] : []),
226
+ ].join('\n'), { success: true, job: j, ...d });
227
+ return 0;
228
+ }
229
+
230
+ async function list(ctx) {
231
+ const jobs = readJobs();
232
+ if (!jobs.length) { ctx.out('No training jobs submitted from this machine yet.', { success: true, jobs: [] }); return 0; }
233
+ const rows = jobs.slice(-20).map((j) => { let d = {}; try { d = describe(ctx, j); } catch (e) { d = { state: `unknown (${e.message})` }; } return { ...j, ...d }; });
234
+ ctx.out(rows.map((j) => `${j.id} ${j.state} ${j.gpu} ${j.gpu_hours != null ? `${j.gpu_hours} GPU-h` : ''} ${j.task}`).join('\n'), { success: true, jobs: rows });
235
+ return 0;
236
+ }
237
+
238
+ async function logs(ctx, [id]) {
239
+ const j = findJob(id);
240
+ gcloud(ctx, ['ai', 'custom-jobs', 'stream-logs', j.name, `--region=${j.region}`, `--project=${j.project}`], { inherit: true });
241
+ return 0;
242
+ }
243
+
244
+ async function fetch(ctx, [id]) {
245
+ const j = findJob(id);
246
+ const out = path.resolve(ctx.io.cwd(), ctx.flags.out || path.join('model-runs', j.id));
247
+ fs.mkdirSync(out, { recursive: true });
248
+ gcloud(ctx, ['storage', 'rsync', `gs://${j.bucket}/jobs/${j.id}/out`, out, '--recursive', `--project=${j.project}`], { inherit: true });
249
+ ctx.out(`${j.id}'s output is in ${out}. Card it, then plaiful models publish <card.json>.`, { success: true, out });
250
+ return 0;
251
+ }
252
+
253
+ async function cancel(ctx, [id]) {
254
+ const j = findJob(id);
255
+ if (!id) throw new UsageError('cancel which job? plaiful models train cancel <job>');
256
+ gcloud(ctx, ['ai', 'custom-jobs', 'cancel', j.name, `--region=${j.region}`, `--project=${j.project}`]);
257
+ ctx.out(`Asked Vertex AI to cancel ${j.id}.`, { success: true });
258
+ return 0;
259
+ }
260
+
261
+ return { check, submit, status, list, logs, fetch, cancel };
262
+ }
263
+
264
+ module.exports = { makeTrain, jobSpec, jobScript, settings, GPUS, DEFAULT_IMAGE, slug };