@deepraxis/cli 0.1.1-dev.f0ef747 → 0.2.0-dev.1046919

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/COMMANDS.md +433 -424
  2. package/README.md +39 -24
  3. package/dist/praxis.js +1103 -92
  4. package/package.json +1 -1
package/dist/praxis.js CHANGED
@@ -1973,7 +1973,7 @@ clears to null; an empty string is stored as an empty string.`
1973
1973
  resource: "agent.sessions",
1974
1974
  method: "create",
1975
1975
  summary: "Create session",
1976
- description: `Create a session: one conversation with an agent. Pass agent as an agent id or {type:"agent", id, version?}; an id alone, or an object without version, pins the agent's active_version (the version chosen with agents.versions.apply, not necessarily the newest saved one). Unlike Anthropic Managed Agents, omit environment_id to use the default environment saved in the agent version (light for a new agent), unless computer_id (explicit, or the agent's default) selects a Computer; pass an environment id for a sandbox recipe. For service agents, explicit null allocates no machine, so codemode, bash and other machine tools are unavailable. Optional model must be one of the agent's allowed models; optional thinking is {effort: low|medium|high|xhigh|max|none} or null, where null inherits the agent default and then the model default (none requires the model to allow disabling thinking). Selections are saved before initial_events run; invalid ones return 400 invalid_request_error. Unlike Anthropic Managed Agents, the only inline agent override is system ({type:"agent_with_overrides", id, system}); to change the model, tools, MCP servers or skills, save a version instead. Supports vault_ids, up to 50, owned by the current organization and not archived; credential injection is deferred to a later version. budget is {type:"limit", max_list_cost:{amount, currency:"USD"}} where amount is a positive integer string of US cents ("2000" is USD 20.00); omitted budget defaults to "2000" and null removes the limit. Up to 500 file resources can be attached. Use initial_events to send a first user.message in this request, or send messages afterwards with sessions.events.send. The returned status can still be idle before initial events run; read agent.message and the subsequent session.status_idle event to confirm completion.`,
1976
+ description: `Create a session: one conversation with an agent. Pass agent as an agent id or {type:"agent", id, version?}; an id alone, or an object without version, pins the agent's active_version (the version chosen with agents.versions.apply, not necessarily the newest saved one). Unlike Anthropic Managed Agents, omit environment_id to use the default environment saved in the agent version (light for a new agent), unless computer_id (explicit, or the agent's default) selects a Computer; pass an environment id for a sandbox recipe. For service agents, explicit null allocates no machine, so codemode, bash and other machine tools are unavailable. Optional model must be one of the agent's allowed models; optional thinking is {effort: low|medium|high|xhigh|max|none} or null, where null inherits the agent default and then the model default (none requires the model to allow disabling thinking). Selections are saved before initial_events run; invalid ones return 400 invalid_request_error. Unlike Anthropic Managed Agents, the only inline agent override is system ({type:"agent_with_overrides", id, system}); to change the model, tools, MCP servers or skills, save a version instead. Supports vault_ids, up to 50, owned by the current organization and not archived; credential injection is deferred to a later version. budget is {type:"limit", max_list_cost:{amount, currency:"USD"}} where amount is a positive decimal string of US dollars with at most 2 decimal places ("20.00" is USD 20.00); omitted budget defaults to "20.00" and null removes the limit. Up to 500 file resources can be attached. Use initial_events to send a first user.message in this request, or send messages afterwards with sessions.events.send. The returned status can still be idle before initial events run; read agent.message and the subsequent session.status_idle event to confirm completion.`,
1977
1977
  http: "POST",
1978
1978
  path: "/agent/v1/sessions",
1979
1979
  streaming: "no",
@@ -2277,7 +2277,7 @@ Own-face extension. No request body is required. Uses the same stop implementati
2277
2277
  summary: "Compact Session (Extension)",
2278
2278
  description: `Request session context compaction and retrieve an operation receipt.
2279
2279
 
2280
- Available only on /agent/v1. The body may be omitted or {}. Optional instructions must be a string and is forwarded unchanged. Idempotency-Key is forwarded unchanged; a UUID is generated when absent. Returns { type: session_compaction, id, status, reason? }, where id is the operation ID. queued/running return 202; skipped/succeeded/failed return 200. Non-string instructions return 400 invalid_request_error. Missing or inaccessible managed sessions return 404 not_found_error.`,
2280
+ Available only on /agent/v1. The body may be omitted or {}. Optional instructions must be a string and is forwarded unchanged. Idempotency-Key is forwarded unchanged; a UUID is generated when absent. Returns { type: session_compaction, id, status, reason? }, where id is the operation ID. queued/running return 202; skipped/succeeded/failed/cancelled return 200. Non-string instructions return 400 invalid_request_error. Missing or inaccessible managed sessions return 404 not_found_error.`,
2281
2281
  http: "POST",
2282
2282
  path: "/agent/v1/sessions/{session_id}/compact",
2283
2283
  streaming: "no",
@@ -2333,7 +2333,7 @@ Available only on /agent/v1. Returns { type: session_compaction, id, status, rea
2333
2333
  summary: "List Session Compactions (Extension)",
2334
2334
  description: `Read session compaction history and summaries.
2335
2335
 
2336
- Available only on /agent/v1. Returns { data: [...] }. Each entry contains type, id, event_id, trigger, status, model, compacted_message_count, input_tokens_before, input_tokens_after, summary, error and created_at, as recorded by the service. Missing or inaccessible managed sessions return 404 not_found_error.`,
2336
+ Available only on /agent/v1. Returns { data: [...], active }. active is the queued or running compaction ({ type: session_compaction, id, status, trigger: manual|auto }), or null when none; manual work takes precedence. Each data entry contains type, id, event_id, trigger, status, model, compacted_message_count, input_tokens_before, input_tokens_after, summary, error and created_at, as recorded by the service. Missing or inaccessible managed sessions return 404 not_found_error.`,
2337
2337
  http: "GET",
2338
2338
  path: "/agent/v1/sessions/{session_id}/compactions",
2339
2339
  streaming: "no",
@@ -2549,9 +2549,9 @@ Available only on /agent/v1. Use the message_id field from own-face events, not
2549
2549
  query: [
2550
2550
  {
2551
2551
  name: "limit",
2552
- type: "number",
2552
+ type: "integer",
2553
2553
  required: false,
2554
- description: "Number of items per page."
2554
+ description: "Number of resources per page, from 1 to 100; defaults to 100."
2555
2555
  },
2556
2556
  {
2557
2557
  name: "page",
@@ -3926,7 +3926,7 @@ file at the root of that directory.`
3926
3926
  resource: "automation.actions",
3927
3927
  method: "list",
3928
3928
  summary: "List actions",
3929
- description: "Discover callable Actions and their ns/name references without executing them. Combine each returned namespace and name as ns/name; Action calls use the current revision and do not accept @version or @tag. Filter by name or description; results include seven-day statistics and revision summaries without implementation source. Archived actions are excluded by default.",
3929
+ description: 'Discover callable Actions and their ns/name references without executing them. Combine each returned namespace and name as ns/name; Action calls use the current revision and do not accept @version or @tag. Filter by name or description; results include seven-day statistics and revision summaries without implementation source. Archived actions are excluded by default. List items carry no input contract: get the action and read current_revision.input_schema. Call it with call("ns/name", input) in a script or call: ns/name with with: in a workflow.',
3930
3930
  http: "GET",
3931
3931
  path: "/automation/v1/actions",
3932
3932
  streaming: "no",
@@ -4095,7 +4095,7 @@ file at the root of that directory.`
4095
4095
  resource: "automation.actions",
4096
4096
  method: "retrieve",
4097
4097
  summary: "Get an Action with its current input and output JSON Schemas",
4098
- description: 'Read the Action and its full current implementation, with input and output JSON Schemas at current_revision.input_schema and current_revision.output_schema. To read a built-in Action, use ns=praxis and name=<bare name>, for example name=ocr; invoke it in a script with call("ocr", input). The response ETag is the current revision ID for conditional updates.',
4098
+ description: 'Read the Action and its full current implementation, with input and output JSON Schemas at current_revision.input_schema and current_revision.output_schema. To read a built-in Action, use ns=praxis and name=<bare name>, for example name=ocr; invoke it in a script with call("ocr", input) or in a workflow step with call: ocr and with:. Input that breaks the contract returns INPUT_INVALID, with the fields in errors[]. The response ETag is the current revision ID for conditional updates.',
4099
4099
  http: "GET",
4100
4100
  path: "/automation/v1/actions/{ns}/{name}",
4101
4101
  streaming: "no",
@@ -4511,6 +4511,177 @@ file at the root of that directory.`
4511
4511
  fields: []
4512
4512
  }
4513
4513
  },
4514
+ {
4515
+ resource: "automation.humanTasks",
4516
+ method: "list",
4517
+ summary: "List human tasks",
4518
+ description: "List the human tasks that praxis/approval workflow steps opened, newest first. By default it returns only open tasks assigned to the caller: their approval inbox. scope=all lists every task of the organization, and status and run_id narrow the list. Use a returned id with retrieve for details and respond to decide. Read-only: listing never changes a task.",
4519
+ http: "GET",
4520
+ path: "/automation/v1/human-tasks",
4521
+ streaming: "no",
4522
+ pagination: true,
4523
+ pathParams: [],
4524
+ query: [
4525
+ {
4526
+ name: "limit",
4527
+ type: "integer",
4528
+ required: false,
4529
+ description: "Page size, 1–100, default 50."
4530
+ },
4531
+ {
4532
+ name: "cursor",
4533
+ type: "string",
4534
+ required: false,
4535
+ description: "The next_cursor of the previous page; omit for the first page."
4536
+ },
4537
+ {
4538
+ name: "status",
4539
+ type: "array",
4540
+ itemType: "string",
4541
+ enum: [
4542
+ "open",
4543
+ "completed",
4544
+ "expired",
4545
+ "cancelled"
4546
+ ],
4547
+ required: false,
4548
+ description: "Filter by status, comma-separated: open, completed, expired, cancelled. Defaults to open."
4549
+ },
4550
+ {
4551
+ name: "run_id",
4552
+ type: "string",
4553
+ required: false,
4554
+ description: "Only tasks opened by this run (run_)."
4555
+ },
4556
+ {
4557
+ name: "scope",
4558
+ type: "string",
4559
+ enum: [
4560
+ "assigned",
4561
+ "all"
4562
+ ],
4563
+ required: false,
4564
+ description: "assigned (default) lists only tasks assigned to the caller; all lists every task of the organization."
4565
+ }
4566
+ ]
4567
+ },
4568
+ {
4569
+ resource: "automation.humanTasks",
4570
+ method: "retrieve",
4571
+ summary: "Retrieve a human task",
4572
+ description: "Read one human task - title, Markdown body, context, actions, form, assignees, mode, due time, responses and outcome - so an assignee can choose an action and fill the form. Read-only; the Console approval page /automation/tasks/{id} reads the same resource.",
4573
+ http: "GET",
4574
+ path: "/automation/v1/human-tasks/{id}",
4575
+ streaming: "no",
4576
+ pagination: false,
4577
+ pathParams: [
4578
+ {
4579
+ name: "id",
4580
+ sdkName: "id",
4581
+ description: "Human task ID (htask_), from the list or the run's waits."
4582
+ }
4583
+ ],
4584
+ query: []
4585
+ },
4586
+ {
4587
+ resource: "automation.humanTasks",
4588
+ method: "cancel",
4589
+ summary: "Cancel a human task",
4590
+ description: "Cancel an open human task; only the person who started the run or an organization API key may cancel. The task becomes cancelled and the waiting workflow step raises a runtime error with code HUMAN_TASK_CANCELLED, which try/catch can catch. Open tasks are cancelled automatically when their run ends, so this call is not needed then.",
4591
+ http: "POST",
4592
+ path: "/automation/v1/human-tasks/{id}/cancel",
4593
+ streaming: "no",
4594
+ pagination: false,
4595
+ pathParams: [
4596
+ {
4597
+ name: "id",
4598
+ sdkName: "id",
4599
+ description: "Human task ID (htask_)."
4600
+ }
4601
+ ],
4602
+ query: [],
4603
+ body: {
4604
+ required: false,
4605
+ fields: [
4606
+ {
4607
+ name: "reason",
4608
+ type: "string",
4609
+ required: false,
4610
+ description: "Optional cancellation reason, at most 500 characters."
4611
+ }
4612
+ ]
4613
+ }
4614
+ },
4615
+ {
4616
+ resource: "automation.humanTasks",
4617
+ method: "delegate",
4618
+ summary: "Delegate a human task",
4619
+ description: "An assignee who has not responded hands their place to another user (to_user), replacing their entry in assignees.users in place, so sequential order is kept. The new user cannot already be an assignee, nor the initiator unless self-approval is allowed. The task must still be open.",
4620
+ http: "POST",
4621
+ path: "/automation/v1/human-tasks/{id}/delegate",
4622
+ streaming: "no",
4623
+ pagination: false,
4624
+ pathParams: [
4625
+ {
4626
+ name: "id",
4627
+ sdkName: "id",
4628
+ description: "Human task ID (htask_)."
4629
+ }
4630
+ ],
4631
+ query: [],
4632
+ body: {
4633
+ required: true,
4634
+ fields: [
4635
+ {
4636
+ name: "to_user",
4637
+ type: "string",
4638
+ required: true,
4639
+ description: "User ID taking over; cannot already be an assignee, nor the initiator unless self-approval is allowed."
4640
+ }
4641
+ ]
4642
+ }
4643
+ },
4644
+ {
4645
+ resource: "automation.humanTasks",
4646
+ method: "respond",
4647
+ summary: "Respond to a human task",
4648
+ description: "Submit an action (action_id), form values (values) and a comment as the calling user. Depending on the task's mode the response either decides it (status becomes completed, outcome is set, and the waiting workflow resumes with outcome as the step output) or is recorded while other assignees are awaited. When two assignees respond at once, exactly one decides and the other gets TASK_CLOSED. An agent may respond only if the workflow set allow_agent_decision. Send an Idempotency-Key to retry safely.",
4649
+ http: "POST",
4650
+ path: "/automation/v1/human-tasks/{id}/respond",
4651
+ streaming: "no",
4652
+ pagination: false,
4653
+ pathParams: [
4654
+ {
4655
+ name: "id",
4656
+ sdkName: "id",
4657
+ description: "Human task ID (htask_)."
4658
+ }
4659
+ ],
4660
+ query: [],
4661
+ body: {
4662
+ required: true,
4663
+ fields: [
4664
+ {
4665
+ name: "action_id",
4666
+ type: "string",
4667
+ required: true,
4668
+ description: "The chosen action ID from the task's actions, for example approve."
4669
+ },
4670
+ {
4671
+ name: "values",
4672
+ type: "object",
4673
+ required: false,
4674
+ description: "Any JSON object whose keys are strings and whose values are any JSON value."
4675
+ },
4676
+ {
4677
+ name: "comment",
4678
+ type: "string",
4679
+ required: false,
4680
+ description: "Comment of at most 4000 characters; required when the action has require_comment true."
4681
+ }
4682
+ ]
4683
+ }
4684
+ },
4514
4685
  {
4515
4686
  resource: "automation.resolve",
4516
4687
  method: "retrieve",
@@ -4691,7 +4862,7 @@ file at the root of that directory.`
4691
4862
  resource: "automation.runs",
4692
4863
  method: "create",
4693
4864
  summary: "Run a published target or execute draft source",
4694
- description: 'Execute a published script or workflow with target, or test unpublished code directly with source and language (ts for TypeScript, yaml for workflow YAML), without first saving or publishing a definition. Minimal script: `export default async ({ file_id }: { file_id: string }) => { const result = await call("ocr", { document: { type: "file", file_id } }); return result; }`; send it as source with language="ts", input={"file_id":"<uploaded file ID>"} and wait=0, using a PDF or image already uploaded to your account. To call a platform API directly in the same script, use the praxis SDK object, for example `praxis.model.ocr.create({ body: { model: "glm-ocr", document: { type: "file", file_id } } })`; Action IDs are strings passed to call(), not SDK methods such as praxis.ocr(...). praxis, call, invoke, console and codemode are module-scope bindings, not on globalThis, and need no import; invoke("namespace/name", input) starts a child run. target and source are mutually exclusive; target accepts ns/name@version, @tag or @range and defaults to latest when @ is omitted. Source/input validation precedes run creation, so a separate validate call is optional. input defaults to {} and must match the input schema and fit within 1 MiB. wait is 0–60 seconds (default 0): a terminal run returns 200, otherwise 202. Use the returned id with praxis.automation.runs.retrieve and inspect status, output and error; acceptance does not mean successful completion. For long-running, background or batch work, use wait: 0 and poll the run, or split work into child runs or a workflow; wait only controls the response wait and does not extend execution limits. Actions time out after 30 s (run-sandbox after 10 min); scripts have a 5 min wall-clock limit and a 30 s CPU limit; workflows default to 24 h and allow up to 7 days. Each run can start at most 100 child runs, with at most 20 active at once; nesting depth is limited to 10. Idempotency-Key is scoped to tenant, method and path for 24 hours, excluding wait from the fingerprint; replay returns the current run with Idempotent-Replayed: true, changed contents return 422 and an in-flight request returns 409. New non-deterministic run IDs contain 78 characters, compared with 46 for legacy random IDs; treat IDs as opaque strings. Historical and deterministic IDs remain valid; same-millisecond order is not guaranteed.',
4865
+ description: 'Execute a published script or workflow with target, or test unpublished code directly with source and language (ts for TypeScript, yaml for workflow YAML), without first saving or publishing a definition. Minimal script: `export default async ({ file_id }: { file_id: string }) => { const result = await call("ocr", { document: { type: "file", file_id } }); return result; }`; send it as source with language="ts", input={"file_id":"<uploaded file ID>"} and wait=0, using a PDF or image already uploaded to your account. To call a platform API directly in the same script, use the praxis SDK object, for example `praxis.model.ocr.create({ body: { model: "glm-ocr", document: { type: "file", file_id } } })`; Action IDs are strings passed to call(), not SDK methods such as praxis.ocr(...). praxis, call, invoke, console and codemode are module-scope bindings, not on globalThis, and need no import; invoke("namespace/name", input) starts a child run. target and source are mutually exclusive; target accepts ns/name@version, @tag or @range and defaults to latest when @ is omitted. Source/input validation precedes run creation, so a separate validate call is optional. input defaults to {} and must match the input schema and fit within 1 MiB. wait is 0–60 seconds (default 0): a terminal run returns 200, otherwise 202. Use the returned id with praxis.automation.runs.retrieve and inspect status, output and error; acceptance does not mean successful completion. For long-running, background or batch work, use wait: 0 and poll the run, or split work into child runs or a workflow; wait only controls the response wait and does not extend execution limits. Actions time out after 30 s (run-sandbox after 10 min); scripts have a 5 min wall-clock limit and a 30 s CPU limit; workflows default to 24 h and allow up to 30 days. Each run can start at most 100 child runs, with at most 20 active at once; nesting depth is limited to 10. Idempotency-Key is scoped to tenant, method and path for 24 hours, excluding wait from the fingerprint; replay returns the current run with Idempotent-Replayed: true, changed contents return 422 and an in-flight request returns 409. With language=yaml, source is a workflow YAML: the run input is . in the first step, and the shape is described in create workflow. Error details are in errors[] (pointer, detail, hint). New non-deterministic run IDs contain 78 characters, compared with 46 for legacy random IDs; treat IDs as opaque strings. Historical and deterministic IDs remain valid; same-millisecond order is not guaranteed.',
4695
4866
  http: "POST",
4696
4867
  path: "/automation/v1/runs",
4697
4868
  streaming: "no",
@@ -5183,7 +5354,7 @@ file at the root of that directory.`
5183
5354
  resource: "automation.scripts",
5184
5355
  method: "create",
5185
5356
  summary: "Create a script",
5186
- description: 'Save a TypeScript script as an editable draft for later reuse; this does not publish or start a run. Choose your own namespace without registering it first; praxis is reserved for built-in Actions. Scripts and workflows share names within the tenant; a duplicate returns NAME_TAKEN. The draft is a source string with a default-exported function, for example `export default async (input: {name: string}) => ({greeting: "Hello, " + input.name});`. Scripts provide praxis, call, invoke, console and codemode as module-scope bindings, not on globalThis, with no import needed: praxis.<domain>.<resource>.<method>(...) calls a platform API, call("ocr", input) calls a built-in Action, and invoke("namespace/name", input) starts a child run. Action IDs are strings (bare names for built-ins, namespace/name for your own Actions); praxis.ocr(...) does not exist. To test it, pass that source and language=ts to praxis.automation.runs.create without publishing. To publish later, use the returned draft.revision as expected_draft_revision.',
5357
+ description: 'Save a TypeScript script as an editable draft for later reuse; this does not publish or start a run. Choose your own namespace without registering it first; praxis is reserved for built-in Actions. Scripts and workflows share names within the tenant; a duplicate returns NAME_TAKEN. The draft is a source string with a default-exported function, for example `export default async (input: {name: string}) => ({greeting: "Hello, " + input.name});`. Scripts provide praxis, call, invoke, console and codemode as module-scope bindings, not on globalThis, with no import needed: praxis.<domain>.<resource>.<method>(...) calls a platform API, call("ocr", input) calls a built-in Action, and invoke("namespace/name", input) starts a child run. Action IDs are strings (bare names for built-ins, namespace/name for your own Actions); praxis.ocr(...) does not exist. The return value is limited to 1 MiB: write large results to a file with call("write-file", ...) and return the file ID. A call error carries errors[] (pointer, detail, hint); String(e) is only the summary. To test it, pass that source and language=ts to praxis.automation.runs.create without publishing. To publish later, use the returned draft.revision as expected_draft_revision.',
5187
5358
  http: "POST",
5188
5359
  path: "/automation/v1/scripts",
5189
5360
  streaming: "no",
@@ -6132,7 +6303,7 @@ file at the root of that directory.`
6132
6303
  resource: "automation.validate",
6133
6304
  method: "create",
6134
6305
  summary: "Validate a definition",
6135
- description: "Check source without executing it when you need diagnostics, inferred schemas or references. This is optional before praxis.automation.runs.create, which also validates source before execution. Actions, scripts and workflows are supported; results include validity without saving. Invalid source is reported with valid=false. Script/action output schemas are inferred from return types: Promise unwrapping, Record, intersections and Date. Unknown types yield an empty schema and a warning in warnings. Source diagnostics use /source or /implementation/source with 1-based line/column. For kind=action the same admission checks as action creation apply (no external imports, platform operations only as direct call(praxis/<api>.<op>, input) calls, no agent or automation calls), so source that validates is not rejected at creation.",
6306
+ description: "Check source without executing it when you need diagnostics, inferred schemas or references. This is optional before praxis.automation.runs.create, which also validates source before execution. Actions, scripts and workflows are supported; results include validity without saving. Invalid source is reported with valid=false. Script/action output schemas are inferred from return types: Promise unwrapping, Record, intersections and Date. Unknown types yield an empty schema and a warning in warnings. Source diagnostics use /source or /implementation/source with 1-based line/column. For kind=action the same admission checks as action creation apply (no external imports, platform operations only as direct call(praxis/<api>.<op>, input) calls, no agent or automation calls), so source that validates is not rejected at creation. For kind=workflow the YAML needs document (dsl, namespace, name, version) and do; each problem is one entry in errors[] (pointer, detail, hint), so read the first one. A listen outside the supported subset (to.all, inside a fork) and emit are not reported here and fail with DEFINITION_INVALID only when a run is created. Workflow syntax reference: https://deepraxis.com/docs/developers/automation/reference/workflow-syntax.",
6136
6307
  http: "POST",
6137
6308
  path: "/automation/v1/validate",
6138
6309
  streaming: "no",
@@ -6239,7 +6410,7 @@ file at the root of that directory.`
6239
6410
  resource: "automation.workflows",
6240
6411
  method: "create",
6241
6412
  summary: "Create a workflow",
6242
- description: "Save a YAML workflow as an editable draft without publishing or starting a run. Choose your own namespace without registering it first; praxis is reserved for built-in Actions. To test the draft, send its source and language=yaml to praxis.automation.runs.create. Scripts and workflows share names within the tenant; a duplicate returns NAME_TAKEN. run.workflow accepts ns/name@range or {namespace, name, version, input}; run.script uses the same reference shape as a platform extension. Object namespace, name and version are required; version accepts an exact version, dist-tag or range, locked at publication. Object input defaults to {} and supports expressions; string references retain task-level with. run.await defaults to true and returns the child output. With false, the child uses detach and the task immediately returns {run_id}; parent cancellation does not cascade. Inline script.code returns DEFINITION_INVALID with a detail asking you to save a script and reference it first. raise.error retains its type URI, status, title and detail in the run error.",
6413
+ description: 'Workflow syntax reference: https://deepraxis.com/docs/developers/automation/reference/workflow-syntax. Save a YAML workflow as an editable draft; this does not validate, publish or run it, so check it with validate (kind=workflow) first. Minimal draft: document with dsl ("1.0.3"), namespace, name and version, plus a do list of steps, for example document: {dsl: "1.0.3", namespace: demo, name: add, version: "1.0.0"} and do: [{first: {call: demo/add-one, with: {n: "${ .n }"}}}]. call: <ns/name> calls an Action directly (bare name for built-ins such as ocr) and with is the Action input; the input contract is at current_revision.input_schema in the get-action response. run: starts a saved script or child workflow. The run input is . in the first step, and expressions are jq written as a whole ${ ... } string. Limits: Action 30 s (run-sandbox 10 min), workflow 24 h by default and 30 days at most, payload 1 MiB. Test the draft by sending its source and language=yaml to praxis.automation.runs.create. Guide: /docs/developers/automation/guides/write-workflow. Error details are in the errors[] of the response (pointer, detail, hint). Choose your own namespace without registering it first; praxis is reserved for built-in Actions. Scripts and workflows share names within the tenant; a duplicate returns NAME_TAKEN. run.workflow accepts ns/name@range or {namespace, name, version, input}; run.script uses the same reference shape as a platform extension. Object namespace, name and version are required; version accepts an exact version, dist-tag or range, locked at publication. Object input defaults to {} and supports expressions; string references retain task-level with. run.await defaults to true and returns the child output. With false, the child uses detach and the task immediately returns {run_id}; parent cancellation does not cascade. Inline script.code returns DEFINITION_INVALID with a detail asking you to save a script and reference it first. raise.error retains its type URI, status, title and detail in the run error.',
6243
6414
  http: "POST",
6244
6415
  path: "/automation/v1/workflows",
6245
6416
  streaming: "no",
@@ -6309,7 +6480,7 @@ file at the root of that directory.`
6309
6480
  resource: "automation.workflows",
6310
6481
  method: "update",
6311
6482
  summary: "Update a workflow draft",
6312
- description: "Update description, labels or draft with the current draft revision in If-Match. Even metadata-only updates create a new draft revision.",
6483
+ description: "Update description, labels or draft with the current draft revision in If-Match, taken from draft.revision in the get-workflow response. Even metadata-only updates create a new draft revision. A mismatch returns 412 PRECONDITION_FAILED; read the draft again, merge and retry. The draft is not validated here, so check it with validate (kind=workflow) before publishing. Error details are in errors[]. See the workflow syntax reference at https://deepraxis.com/docs/developers/automation/reference/workflow-syntax.",
6313
6484
  http: "PATCH",
6314
6485
  path: "/automation/v1/workflows/{ns}/{name}",
6315
6486
  streaming: "no",
@@ -6547,7 +6718,7 @@ file at the root of that directory.`
6547
6718
  "publish"
6548
6719
  ],
6549
6720
  summary: "Publish a workflow version",
6550
- description: "Publish a saved definition from its draft or an ad hoc run as a reusable version for named runs or triggers, validating the definition and locking dependencies. To test unpublished code, use praxis.automation.runs.create with source and language instead. Use draft.revision from create or retrieve as expected_draft_revision. The draft must match expected_draft_revision; an ad hoc run requires from_run and expected_source_sha256. The same version and contents return the existing version; different contents return VERSION_EXISTS, prereleases require an explicit tag (not latest, URL-safe characters only, not a version or range; violations return TAG_REQUIRED or TAG_INVALID with the complete rules in hint), and invalid definitions return DEFINITION_INVALID. Stable releases automatically advance latest only above the highest existing stable version; workflows becoming latest synchronize their declared schedule. String and object run.workflow/run.script references share version resolution and dependency locking. Publishing removes +build metadata from the version number.",
6721
+ description: "Publish a saved definition from its draft or an ad hoc run as a reusable version for named runs or triggers, validating the definition and locking dependencies. To test unpublished code, use praxis.automation.runs.create with source and language instead. Use draft.revision from create or retrieve as expected_draft_revision. The draft must match expected_draft_revision; an ad hoc run requires from_run and expected_source_sha256. The same version and contents return the existing version; different contents return VERSION_EXISTS, prereleases require an explicit tag (not latest, URL-safe characters only, not a version or range; violations return TAG_REQUIRED or TAG_INVALID with the complete rules in hint), and invalid definitions return DEFINITION_INVALID. Stable releases automatically advance latest only above the highest existing stable version; workflows becoming latest synchronize their declared schedule. String and object run.workflow/run.script references share version resolution and dependency locking. Publishing removes +build metadata from the version number. For a workflow, document namespace, name and version must equal the publish target, otherwise DEFINITION_IDENTITY_MISMATCH; where a DEFINITION_INVALID failure sits is listed in errors[] (pointer, detail, hint).",
6551
6722
  http: "POST",
6552
6723
  path: "/automation/v1/workflows/{ns}/{name}/versions",
6553
6724
  streaming: "no",
@@ -8234,7 +8405,7 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
8234
8405
  resource: "file.files",
8235
8406
  method: "create",
8236
8407
  summary: "Upload file",
8237
- description: 'Upload a file to reuse in conversations or attach to a knowledge base. Unlike OpenAI Files, uploads must be nonempty and at most 100000000 bytes, and only user_data, assistants and vision purposes are accepted. Send file bytes as a multipart file part, not a filename or file ID; in the SDK use a File or Blob, for example new File(["Return within 23 days."], "policy.txt", { type: "text/plain" }). Content determines the MIME type. Supported uploads include PDF, DOCX/XLSX/PPTX, PNG/JPEG/GIF/WebP, MP3/WAV/FLAC/OGG/M4A, MP4/WebM, and UTF-8 JSON/NDJSON/CSV/Markdown/plain text; empty, unsupported, oversized files and unsupported purposes return 400. Use Uploads for larger files. The purpose vision accepts only PNG, JPEG, GIF and WebP, while conversation images require user_data. The returned ID belongs to your tenant; upload alone does not ingest the file into Knowledge. Knowledge attachment has a lower limit of 100000000 bytes. Optionally set expires_after[anchor]=created_at with expires_after[seconds] (3600–2592000), or praxis[expires_in_seconds] (3600–7776000), never both. Without expiry, the file persists until deleted.',
8408
+ description: 'Upload a file to reuse in conversations or attach to a knowledge base. Unlike OpenAI Files, uploads must be nonempty and at most 100000000 bytes, and only user_data and vision purposes are accepted. Send file bytes as a multipart file part, not a filename or file ID; in the SDK use a File or Blob, for example new File(["Return within 23 days."], "policy.txt", { type: "text/plain" }). Content determines the MIME type. Supported uploads include PDF, DOCX/XLSX/PPTX, PNG/JPEG/GIF/WebP, MP3/WAV/FLAC/OGG/M4A, MP4/WebM, and UTF-8 JSON/NDJSON/CSV/Markdown/plain text; empty, unsupported, oversized files and unsupported purposes return 400. Use Uploads for larger files. The purpose vision accepts only PNG, JPEG, GIF and WebP, while conversation images require user_data. The returned ID belongs to your tenant; upload alone does not ingest the file into Knowledge. Knowledge attachment has a lower limit of 100000000 bytes. Optionally set expires_after[anchor]=created_at with expires_after[seconds] (3600–7776000). Without expiry, the file persists until deleted.',
8238
8409
  http: "POST",
8239
8410
  path: "/file/v1/files",
8240
8411
  streaming: "no",
@@ -8256,23 +8427,16 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
8256
8427
  type: "string",
8257
8428
  enum: [
8258
8429
  "user_data",
8259
- "assistants",
8260
8430
  "vision"
8261
8431
  ],
8262
8432
  required: true,
8263
- description: "Purpose label stored with the file: user_data, assistants or vision. The vision purpose accepts only PNG, JPEG, GIF and WebP images. Conversation image references require user_data."
8433
+ description: "Purpose label stored with the file: user_data or vision. The vision purpose accepts only PNG, JPEG, GIF and WebP images. Conversation image references require user_data."
8264
8434
  },
8265
8435
  {
8266
8436
  name: "expires_after",
8267
8437
  type: "object",
8268
8438
  required: false,
8269
8439
  description: "Optional expiry relative to created_at. Files without an expiry persist until deleted."
8270
- },
8271
- {
8272
- name: "praxis",
8273
- type: "object",
8274
- required: false,
8275
- description: "Own-face extensions. Use at most one expiry setting."
8276
8440
  }
8277
8441
  ]
8278
8442
  }
@@ -8335,7 +8499,7 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
8335
8499
  resource: "file.uploads",
8336
8500
  method: "create",
8337
8501
  summary: "Create an upload",
8338
- description: "Start a multipart upload for a file larger than the 100000000-byte direct-upload limit. Supply the exact byte length, filename, MIME type and purpose. Unlike OpenAI, uploads accept at most 2 GiB (2147483648 bytes) and only user_data, assistants and vision purposes. Add parts of at most 64000000 bytes and complete within one hour. Optional part_size enables fixed-size, retryable parts. expires_after applies to the resulting file (3600–7776000 seconds on this own face); without it the file persists until deleted.",
8502
+ description: "Start a multipart upload for a file larger than the 100000000-byte direct-upload limit. Supply the exact byte length, filename, MIME type and purpose. Unlike OpenAI, uploads accept at most 2 GiB (2147483648 bytes) and only user_data and vision purposes. Add parts of at most 64000000 bytes and complete within one hour. Optional part_size enables fixed-size, retryable parts. expires_after applies to the resulting file (3600–7776000 seconds on this own face); without it the file persists until deleted.",
8339
8503
  http: "POST",
8340
8504
  path: "/file/v1/uploads",
8341
8505
  streaming: "no",
@@ -8368,11 +8532,10 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
8368
8532
  type: "string",
8369
8533
  enum: [
8370
8534
  "user_data",
8371
- "assistants",
8372
8535
  "vision"
8373
8536
  ],
8374
8537
  required: true,
8375
- description: "Use user_data for conversation attachments, assistants for assistant files, or vision for PNG, JPEG, GIF and WebP images."
8538
+ description: "Use user_data for conversation attachments, or vision for PNG, JPEG, GIF and WebP images."
8376
8539
  },
8377
8540
  {
8378
8541
  name: "expires_after",
@@ -9552,7 +9715,7 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
9552
9715
  name: "overwrite",
9553
9716
  type: "boolean",
9554
9717
  required: false,
9555
- description: "Allow replacing an existing public_id, preserving its asset_id and increasing its version. False returns the existing resource without replacing it; defaults to true."
9718
+ description: "Allow replacing an existing public_id, preserving its asset_id and increasing its version. Only the latest version is deliverable; old version URLs return 404. Create a new public_id to retain old deliveries. False returns the existing resource without replacing it; defaults to true."
9556
9719
  },
9557
9720
  {
9558
9721
  name: "tags",
@@ -9610,7 +9773,8 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
9610
9773
  {
9611
9774
  name: "file_id",
9612
9775
  type: "string",
9613
- required: true
9776
+ required: true,
9777
+ description: "File ID to copy into this library; passed as the upload source instead of file bytes. This creates an independent public copy readable without authentication. Deleting the source File does not delete this asset; do not import confidential content."
9614
9778
  },
9615
9779
  {
9616
9780
  name: "public_id",
@@ -9664,7 +9828,7 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
9664
9828
  name: "overwrite",
9665
9829
  type: "boolean",
9666
9830
  required: false,
9667
- description: "Allow replacing an existing public_id, preserving its asset_id and increasing its version. False returns the existing resource without replacing it; defaults to true."
9831
+ description: "Allow replacing an existing public_id, preserving its asset_id and increasing its version. Only the latest version is deliverable; old version URLs return 404. Create a new public_id to retain old deliveries. False returns the existing resource without replacing it; defaults to true."
9668
9832
  },
9669
9833
  {
9670
9834
  name: "tags",
@@ -10181,7 +10345,7 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
10181
10345
  name: "expression",
10182
10346
  type: "string",
10183
10347
  required: false,
10184
- description: "Asset filter expression supporting field comparisons, AND, OR, NOT, parentheses and suffix wildcards. An empty expression matches all assets."
10348
+ description: 'Asset filter expression supporting field comparisons, AND, OR, NOT, parentheses and suffix wildcards. An empty expression matches all assets. For business metadata use context.sku=KETTLE-RED AND context.revision=2; request with_field: ["context"] to include context.'
10185
10349
  },
10186
10350
  {
10187
10351
  name: "sort_by",
@@ -10327,6 +10491,70 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
10327
10491
  ]
10328
10492
  }
10329
10493
  },
10494
+ {
10495
+ resource: "meta.docs",
10496
+ method: "search",
10497
+ summary: "Search platform documentation",
10498
+ description: "Find guides and references by keyword before reading them with praxis.meta.docs.retrieve. Public; no API key required. Matches documentation titles, headings and page text without case sensitivity; all query words must occur. q is required; limit defaults to 20 and accepts 1–50. lang defaults to zh or use en for English. Returns paths, page titles, canonical URLs and short matching snippets; no matches returns an empty array.",
10499
+ http: "GET",
10500
+ path: "/meta/v1/docs/search",
10501
+ streaming: "no",
10502
+ pagination: false,
10503
+ pathParams: [],
10504
+ query: [
10505
+ {
10506
+ name: "q",
10507
+ type: "string",
10508
+ required: true,
10509
+ description: "Keywords describing the syntax or guide needed, for example export or workflow."
10510
+ },
10511
+ {
10512
+ name: "limit",
10513
+ type: "integer",
10514
+ required: false,
10515
+ description: "Maximum number of matching pages returned; integer 1–50, default 20."
10516
+ },
10517
+ {
10518
+ name: "lang",
10519
+ type: "string",
10520
+ enum: [
10521
+ "zh",
10522
+ "en"
10523
+ ],
10524
+ required: false,
10525
+ description: "Documentation language: zh for Chinese (default), en for English."
10526
+ }
10527
+ ]
10528
+ },
10529
+ {
10530
+ resource: "meta.docs",
10531
+ method: "retrieve",
10532
+ summary: "Read documentation Markdown",
10533
+ description: "Read a platform guide or reference before implementing an unfamiliar capability. Public; no API key required. Take path from praxis.meta.docs.search, or use developers/automation/guides/write-workflow. Append #heading-id to path to read only that section, including its subsections. Encode the hash as %23 over HTTP; SDK callers pass it in the path string. lang defaults to zh; en selects the English page. Unknown pages or anchors return DOC_NOT_FOUND; search again for a valid path.",
10534
+ http: "GET",
10535
+ path: "/meta/v1/docs/{path}",
10536
+ streaming: "no",
10537
+ pagination: false,
10538
+ pathParams: [
10539
+ {
10540
+ name: "path",
10541
+ sdkName: "path",
10542
+ description: "Slash-separated documentation path from docs.search; optionally append #heading-id to select a section."
10543
+ }
10544
+ ],
10545
+ query: [
10546
+ {
10547
+ name: "lang",
10548
+ type: "string",
10549
+ enum: [
10550
+ "zh",
10551
+ "en"
10552
+ ],
10553
+ required: false,
10554
+ description: "Documentation language: zh for Chinese (default), en for English."
10555
+ }
10556
+ ]
10557
+ },
10330
10558
  {
10331
10559
  resource: "meta.health",
10332
10560
  method: "retrieve",
@@ -18930,6 +19158,8 @@ var fileCancelUpload = (options) => (options.client ?? client).post({
18930
19158
  var healthCheck = (options) => (options?.client ?? client).get({ url: "/meta/v1/health", ...options });
18931
19159
  var metaMethodsSearch = (options) => (options?.client ?? client).get({ url: "/meta/v1/methods", ...options });
18932
19160
  var metaMethodsRetrieve = (options) => (options.client ?? client).get({ url: "/meta/v1/methods/{name}", ...options });
19161
+ var metaDocsRetrieve = (options) => (options.client ?? client).get({ url: "/meta/v1/docs/{path}", ...options });
19162
+ var metaDocsSearch = (options) => (options.client ?? client).get({ url: "/meta/v1/docs/search", ...options });
18933
19163
  var listModels = (options) => (options?.client ?? client).get({
18934
19164
  querySerializer: { parameters: {
18935
19165
  supported_api: { array: { explode: false } },
@@ -21706,6 +21936,84 @@ var automationHooksReceive = (options) => (options.client ?? client).post({
21706
21936
  ...options.headers
21707
21937
  }
21708
21938
  });
21939
+ var automationHumanTasksList = (options) => (options?.client ?? client).get({
21940
+ querySerializer: { parameters: { status: { array: { explode: false } } } },
21941
+ security: [{
21942
+ key: "BearerAuth",
21943
+ scheme: "bearer",
21944
+ type: "http"
21945
+ }, {
21946
+ key: "ApiKeyAuth",
21947
+ name: "X-API-Key",
21948
+ type: "apiKey"
21949
+ }],
21950
+ url: "/automation/v1/human-tasks",
21951
+ ...options
21952
+ });
21953
+ var automationHumanTasksGet = (options) => (options.client ?? client).get({
21954
+ security: [{
21955
+ key: "BearerAuth",
21956
+ scheme: "bearer",
21957
+ type: "http"
21958
+ }, {
21959
+ key: "ApiKeyAuth",
21960
+ name: "X-API-Key",
21961
+ type: "apiKey"
21962
+ }],
21963
+ url: "/automation/v1/human-tasks/{id}",
21964
+ ...options
21965
+ });
21966
+ var automationHumanTasksRespond = (options) => (options.client ?? client).post({
21967
+ security: [{
21968
+ key: "BearerAuth",
21969
+ scheme: "bearer",
21970
+ type: "http"
21971
+ }, {
21972
+ key: "ApiKeyAuth",
21973
+ name: "X-API-Key",
21974
+ type: "apiKey"
21975
+ }],
21976
+ url: "/automation/v1/human-tasks/{id}/respond",
21977
+ ...options,
21978
+ headers: {
21979
+ "Content-Type": "application/json",
21980
+ ...options.headers
21981
+ }
21982
+ });
21983
+ var automationHumanTasksCancel = (options) => (options.client ?? client).post({
21984
+ security: [{
21985
+ key: "BearerAuth",
21986
+ scheme: "bearer",
21987
+ type: "http"
21988
+ }, {
21989
+ key: "ApiKeyAuth",
21990
+ name: "X-API-Key",
21991
+ type: "apiKey"
21992
+ }],
21993
+ url: "/automation/v1/human-tasks/{id}/cancel",
21994
+ ...options,
21995
+ headers: {
21996
+ "Content-Type": "application/json",
21997
+ ...options.headers
21998
+ }
21999
+ });
22000
+ var automationHumanTasksDelegate = (options) => (options.client ?? client).post({
22001
+ security: [{
22002
+ key: "BearerAuth",
22003
+ scheme: "bearer",
22004
+ type: "http"
22005
+ }, {
22006
+ key: "ApiKeyAuth",
22007
+ name: "X-API-Key",
22008
+ type: "apiKey"
22009
+ }],
22010
+ url: "/automation/v1/human-tasks/{id}/delegate",
22011
+ ...options,
22012
+ headers: {
22013
+ "Content-Type": "application/json",
22014
+ ...options.headers
22015
+ }
22016
+ });
21709
22017
  var databaseListDatabases = (options) => (options?.client ?? client).get({
21710
22018
  security: [{
21711
22019
  key: "database-bearerAuth",
@@ -24176,6 +24484,13 @@ function createAutomation(transport) {
24176
24484
  hooks: {
24177
24485
  send: bind(transport, automationHooksReceive)
24178
24486
  },
24487
+ humanTasks: {
24488
+ cancel: bind(transport, automationHumanTasksCancel),
24489
+ delegate: bind(transport, automationHumanTasksDelegate),
24490
+ list: bindPage(transport, automationHumanTasksList),
24491
+ respond: bind(transport, automationHumanTasksRespond),
24492
+ retrieve: bind(transport, automationHumanTasksGet)
24493
+ },
24179
24494
  resolve: {
24180
24495
  retrieve: bind(transport, automationResolveResolve)
24181
24496
  },
@@ -24466,6 +24781,10 @@ function createMedia(transport) {
24466
24781
  }
24467
24782
  function createMeta(transport) {
24468
24783
  return {
24784
+ docs: {
24785
+ retrieve: bind(transport, metaDocsRetrieve),
24786
+ search: bind(transport, metaDocsSearch)
24787
+ },
24469
24788
  health: {
24470
24789
  retrieve: bind(transport, healthCheck)
24471
24790
  },
@@ -24957,7 +25276,7 @@ function assertKnownOptions(options) {
24957
25276
  class Transport {
24958
25277
  config;
24959
25278
  constructor(options) {
24960
- this.config = { timeoutMs: 60000, maxRetries: 2, fetch: globalThis.fetch, ...options };
25279
+ this.config = { timeoutMs: 600000, maxRetries: 2, fetch: globalThis.fetch, ...options };
24961
25280
  this.validate(this.config.timeoutMs, this.config.maxRetries);
24962
25281
  }
24963
25282
  validate(timeout, retries) {
@@ -25061,7 +25380,7 @@ async function publish(client2, input) {
25061
25380
  const timeout = input.timeout_ms ?? 120000;
25062
25381
  if (!Number.isFinite(timeout) || timeout < 0)
25063
25382
  throw new RangeError("timeout_ms must be non-negative and finite");
25064
- const contentType = [
25383
+ const moduleTypes = [
25065
25384
  "application/javascript+module",
25066
25385
  "text/javascript",
25067
25386
  "application/javascript",
@@ -25070,9 +25389,30 @@ async function publish(client2, input) {
25070
25389
  "application/wasm",
25071
25390
  "application/octet-stream",
25072
25391
  "application/x-python"
25073
- ].find((type) => type === (input.main?.content_type ?? "application/javascript+module"));
25074
- if (!contentType)
25075
- throw new PraxisError({ code: "INVALID_PARAMS", message: `Unsupported module content_type: ${input.main?.content_type}` });
25392
+ ];
25393
+ const moduleType = (type) => {
25394
+ const found = moduleTypes.find((candidate) => candidate === (type ?? "application/javascript+module"));
25395
+ if (!found)
25396
+ throw new PraxisError({ code: "INVALID_PARAMS", message: `Unsupported module content_type: ${type}` });
25397
+ return found;
25398
+ };
25399
+ if (input.main && input.modules)
25400
+ throw new PraxisError({ code: "INVALID_PARAMS", message: "Pass either main or modules, not both" });
25401
+ if (input.main_module !== undefined && !input.modules)
25402
+ throw new PraxisError({ code: "INVALID_PARAMS", message: "main_module requires modules; with main the entry is main.name" });
25403
+ if (input.modules && input.modules.length === 0)
25404
+ throw new PraxisError({ code: "INVALID_PARAMS", message: "modules must not be empty" });
25405
+ const entryModules = input.main ? [{ name: input.main.name, content_type: moduleType(input.main.content_type), content_base64: base64(new TextEncoder().encode(input.main.content)) }] : input.modules?.map((module) => ({
25406
+ name: module.name,
25407
+ content_type: moduleType(module.content_type),
25408
+ content_base64: base64(typeof module.content === "string" ? new TextEncoder().encode(module.content) : module.content)
25409
+ }));
25410
+ if (new Set(entryModules?.map((module) => module.name)).size !== (entryModules?.length ?? 0))
25411
+ throw new PraxisError({ code: "INVALID_PARAMS", message: "Duplicate module name" });
25412
+ const mainModule = input.main ? input.main.name : input.modules ? input.main_module ?? input.modules[0].name : undefined;
25413
+ if (input.modules && !input.modules.some((module) => module.name === mainModule)) {
25414
+ throw new PraxisError({ code: "INVALID_PARAMS", message: `main_module ${mainModule} is not among modules` });
25415
+ }
25076
25416
  const files = Object.entries(input.files);
25077
25417
  if (files.length > 1e5)
25078
25418
  throw new PraxisError({ code: "LIMIT_EXCEEDED", message: "At most 100000 asset paths can be published" });
@@ -25125,7 +25465,7 @@ async function publish(client2, input) {
25125
25465
  const removed = Object.keys(previous).filter((key) => !Object.hasOwn(manifest, key));
25126
25466
  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(manifest))));
25127
25467
  const manifestHash = Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
25128
- const staticOnly = !["main", "bindings", "compatibility_date", "compatibility_flags", "assets_config"].some((key) => Object.hasOwn(input, key));
25468
+ const staticOnly = !["main", "modules", "main_module", "bindings", "compatibility_date", "compatibility_flags", "assets_config"].some((key) => Object.hasOwn(input, key));
25129
25469
  const unchanged = staticOnly && !!currentVersion && manifestHash === currentVersion.praxis.assets_manifest?.manifest_hash;
25130
25470
  const hashes = new Set(Object.values(manifest).map((entry) => entry.hash));
25131
25471
  const currentResult = {
@@ -25181,11 +25521,7 @@ async function publish(client2, input) {
25181
25521
  assets: versionAssets,
25182
25522
  ...input.compatibility_flags ? { compatibility_flags: input.compatibility_flags } : {},
25183
25523
  ...input.bindings ? { bindings: input.bindings } : {},
25184
- ...input.main ? { main_module: input.main.name, modules: [{
25185
- name: input.main.name,
25186
- content_type: contentType,
25187
- content_base64: base64(new TextEncoder().encode(input.main.content))
25188
- }] } : {}
25524
+ ...entryModules ? { main_module: mainModule, modules: entryModules } : {}
25189
25525
  } });
25190
25526
  let deployment = result.deployment;
25191
25527
  if (!deployment)
@@ -25316,7 +25652,7 @@ function decideTabReuse(targetUrl, tabs) {
25316
25652
  if (best === undefined || rank < best.rank || rank === best.rank && (tab.active || !best.tab.active))
25317
25653
  best = { tab, rank };
25318
25654
  }
25319
- return best?.tab;
25655
+ return best?.tab ?? tabs.find((tab) => isBlankTab(tab.url));
25320
25656
  }
25321
25657
  function buildConnectUrl(parts) {
25322
25658
  const url = new URL("/browser/v1/connect", parts.api);
@@ -25334,6 +25670,16 @@ function pickAgentContext(contexts, agentId) {
25334
25670
  return [...own].sort((x, y) => (x.createdAt ?? "").localeCompare(y.createdAt ?? "") || x.id.localeCompare(y.id))[0];
25335
25671
  }
25336
25672
  var agentContextName = (agentId) => `agent-${agentId}`.replace(/[^A-Za-z0-9._:-]/g, "-").slice(0, 128);
25673
+ function isBlankTab(value) {
25674
+ if (value === "" || value === "about:blank")
25675
+ return true;
25676
+ try {
25677
+ const url = new URL(value);
25678
+ return (url.protocol === "https:" || url.protocol === "http:") && url.pathname === "/start" && (url.hostname.startsWith("console-") || url.hostname === "console.deepraxis.com");
25679
+ } catch {
25680
+ return false;
25681
+ }
25682
+ }
25337
25683
 
25338
25684
  // ../../packages/sdk/typescript/src/helpers/browser-connect.ts
25339
25685
  var PLAYWRIGHT_CORE_VERSION = "1.63.0";
@@ -25532,6 +25878,116 @@ class Praxis {
25532
25878
  }
25533
25879
  }
25534
25880
  }
25881
+ // ../../packages/sdk/typescript/src/helpers/application-build.ts
25882
+ var UNSUPPORTED_BINDING_KEYS = [
25883
+ "services",
25884
+ "queues",
25885
+ "durable_objects",
25886
+ "ai",
25887
+ "analytics_engine_datasets",
25888
+ "vectorize",
25889
+ "hyperdrive",
25890
+ "browser",
25891
+ "send_email",
25892
+ "mtls_certificates",
25893
+ "dispatch_namespaces",
25894
+ "unsafe",
25895
+ "version_metadata",
25896
+ "images",
25897
+ "workflows",
25898
+ "pipelines",
25899
+ "secrets_store_secrets",
25900
+ "ratelimits",
25901
+ "vpc_services",
25902
+ "media",
25903
+ "tail_consumers",
25904
+ "worker_loaders"
25905
+ ];
25906
+ var isPresent = (value) => {
25907
+ if (value === undefined || value === null)
25908
+ return false;
25909
+ if (Array.isArray(value))
25910
+ return value.some(isPresent);
25911
+ if (typeof value === "object")
25912
+ return Object.values(value).some(isPresent);
25913
+ return true;
25914
+ };
25915
+ function ignoreMatcher(line) {
25916
+ let pattern = line.trim();
25917
+ if (!pattern || pattern.startsWith("#") || pattern.startsWith("!"))
25918
+ return null;
25919
+ const anchored = pattern.startsWith("/") || pattern.slice(0, -1).includes("/");
25920
+ pattern = pattern.replace(/^\//, "").replace(/\/$/, "");
25921
+ const source = pattern.split("**").map((part) => part.split("*").map((piece) => piece.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join("[^/]*")).join(".*");
25922
+ const regex = new RegExp(`^${source}$`);
25923
+ return (path) => {
25924
+ const segments = path.split("/");
25925
+ for (let end = 1;end <= segments.length; end++) {
25926
+ if (anchored ? regex.test(segments.slice(0, end).join("/")) : regex.test(segments[end - 1]))
25927
+ return true;
25928
+ }
25929
+ return false;
25930
+ };
25931
+ }
25932
+ function bindingsFrom(wrangler) {
25933
+ const bindings = [];
25934
+ const fromList = (key, type) => {
25935
+ const list = wrangler[key];
25936
+ if (!isPresent(list))
25937
+ return;
25938
+ if (!Array.isArray(list))
25939
+ throw new PraxisError({ code: "INVALID_PARAMS", message: `wrangler.json ${key} must be an array` });
25940
+ for (const entry of list) {
25941
+ if (typeof entry?.binding !== "string")
25942
+ throw new PraxisError({ code: "INVALID_PARAMS", message: `wrangler.json ${key} entry has no binding name` });
25943
+ bindings.push({ type, name: entry.binding });
25944
+ }
25945
+ };
25946
+ fromList("d1_databases", "d1");
25947
+ fromList("kv_namespaces", "kv_namespace");
25948
+ fromList("r2_buckets", "r2_bucket");
25949
+ for (const [name, value] of Object.entries(wrangler.vars ?? {})) {
25950
+ bindings.push(typeof value === "string" ? { type: "plain_text", name, text: value } : { type: "json", name, json: value });
25951
+ }
25952
+ if (typeof wrangler.assets?.binding === "string")
25953
+ bindings.push({ type: "assets", name: wrangler.assets.binding });
25954
+ return bindings;
25955
+ }
25956
+ function publishInputFromBuild(build, name) {
25957
+ const wrangler = build.wranglerJson;
25958
+ if (!wrangler || typeof wrangler !== "object" || Array.isArray(wrangler)) {
25959
+ throw new PraxisError({ code: "INVALID_PARAMS", message: "wranglerJson must be the parsed dist/server/wrangler.json object" });
25960
+ }
25961
+ const offending = UNSUPPORTED_BINDING_KEYS.filter((key) => isPresent(wrangler[key]));
25962
+ if (offending.length) {
25963
+ throw new PraxisError({ code: "UNSUPPORTED", message: `wrangler.json declares bindings the platform does not support: ${offending.join(", ")}` });
25964
+ }
25965
+ const modules = Object.entries(build.serverFiles).filter(([path]) => path.endsWith(".js")).map(([path, content]) => ({ name: path, content, content_type: "application/javascript+module" }));
25966
+ if (typeof wrangler.main !== "string")
25967
+ throw new PraxisError({ code: "INVALID_PARAMS", message: "wrangler.json has no main entry" });
25968
+ if (!modules.some((module) => module.name === wrangler.main)) {
25969
+ throw new PraxisError({ code: "INVALID_PARAMS", message: `wrangler.json main ${wrangler.main} is not a .js file under dist/server` });
25970
+ }
25971
+ const ignored = new TextDecoder().decode(build.clientFiles[".assetsignore"] ?? new Uint8Array).split(/\r?\n/).map(ignoreMatcher).filter((matcher) => matcher !== null);
25972
+ const files = {};
25973
+ for (const [path, content] of Object.entries(build.clientFiles)) {
25974
+ if (path === ".assetsignore" || ignored.some((matches) => matches(path)))
25975
+ continue;
25976
+ files[`/${path}`] = content;
25977
+ }
25978
+ const { binding: _binding, directory: _directory, ...assetsConfig } = wrangler.assets ?? {};
25979
+ const bindings = bindingsFrom(wrangler);
25980
+ return {
25981
+ name,
25982
+ files,
25983
+ modules,
25984
+ main_module: wrangler.main,
25985
+ ...typeof wrangler.compatibility_date === "string" ? { compatibility_date: wrangler.compatibility_date } : {},
25986
+ ...Array.isArray(wrangler.compatibility_flags) ? { compatibility_flags: wrangler.compatibility_flags } : {},
25987
+ ...bindings.length ? { bindings } : {},
25988
+ ...Object.keys(assetsConfig).length ? { assets_config: assetsConfig } : {}
25989
+ };
25990
+ }
25535
25991
  // src/core/command-overrides.ts
25536
25992
  var commandOverrides = {
25537
25993
  "agent.deployments.run.create": { words: ["agent", "deployment", "run"], reason: "The terminal path is an action; expose its verb without a redundant create." },
@@ -25592,6 +26048,15 @@ function commandWords(resource, method) {
25592
26048
  const verb = kebab(method.replace(/^retrieve(?=[A-Z]|$)/, "get"));
25593
26049
  return [domain, ...resources, verb];
25594
26050
  }
26051
+ var API_WORD = "api";
26052
+ var HTTP_METHOD = /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/;
26053
+ var domainOf = (command) => command.words[1];
26054
+ function movedTo(commands, words) {
26055
+ if (!words.length || words[0] === API_WORD)
26056
+ return;
26057
+ const moved = [API_WORD, ...words];
26058
+ return commands.some((c) => moved.every((w, i) => c.words[i] === w)) ? `praxis ${moved.join(" ")}` : undefined;
26059
+ }
25595
26060
  function commandTree(operations2) {
25596
26061
  const commands = [];
25597
26062
  const seen = new Set;
@@ -25607,7 +26072,7 @@ function commandTree(operations2) {
25607
26072
  if (["login", "logout", "whoami", "org", "api", "skill"].includes(words[0]))
25608
26073
  throw new Error(`Reserved command: ${key}`);
25609
26074
  seen.add(key);
25610
- commands.push({ words, op, ...method !== op.method ? { alias: method } : {} });
26075
+ commands.push({ words: [API_WORD, ...words], op, ...method !== op.method ? { alias: method } : {} });
25611
26076
  }
25612
26077
  }
25613
26078
  for (const key of Object.keys(commandOverrides))
@@ -25903,29 +26368,112 @@ function help(commands, prefix, command) {
25903
26368
  `);
25904
26369
  }
25905
26370
  const matching = commands.filter((c) => prefix.every((w, i) => c.words[i] === w));
26371
+ const global = [
26372
+ "Global options:",
26373
+ ...globalOptions.map((s) => ` ${describeOption(s)}`),
26374
+ " -h is an alias of --help",
26375
+ "PRAXIS_ENV=develop|production (default: develop); no --env option.",
26376
+ ""
26377
+ ];
26378
+ const sample = matching.find((c) => c.words.at(-1) === "list") ?? matching[0];
26379
+ if (!prefix.length) {
26380
+ const nouns = [...new Set(workflows.map((w) => w.words[0]))];
26381
+ const summaries = new Map(workflows.map((w) => [w.words[0], w.words.length === 1 ? w.summary : undefined]));
26382
+ const width = Math.max(...nouns.map((n) => n.length));
26383
+ return [
26384
+ "praxis <command> [options]",
26385
+ "",
26386
+ "Workflows:",
26387
+ ...nouns.map((n) => ` ${n.padEnd(width)} ${summaries.get(n) ?? workflows.filter((w) => w.words[0] === n).map((w) => w.words[1]).join(", ")}`),
26388
+ "",
26389
+ "API:",
26390
+ ` praxis ${API_WORD} <domain> <resource> <action> [options] one command per API operation`,
26391
+ ` praxis ${API_WORD} <METHOD> <path> [--data JSON|@file|-] raw request`,
26392
+ ` Domains: ${domains(commands).join(", ")}`,
26393
+ "",
26394
+ ...global,
26395
+ "Examples:",
26396
+ ` ${sample ? example(sample) : "praxis --help"}`
26397
+ ].join(`
26398
+ `);
26399
+ }
25906
26400
  const children = [...new Set(matching.map((c) => c.words[prefix.length]).filter(Boolean))].sort();
25907
- if (!prefix.length)
25908
- children.unshift("login", "logout", "whoami", "org", "api", "skill");
26401
+ const raw = prefix.length === 1 && prefix[0] === API_WORD;
25909
26402
  return [
25910
26403
  `praxis${prefix.length ? " " + prefix.join(" ") : ""} <command> [options]`,
25911
26404
  "",
26405
+ ...raw ? ["Domains:"] : [],
25912
26406
  ...children.map((s) => ` ${s}`),
25913
26407
  "",
25914
- "Global options:",
25915
- ...globalOptions.map((s) => ` ${describeOption(s)}`),
26408
+ ...raw ? ["Raw request:", ` praxis ${API_WORD} <METHOD> <path> [--data JSON|@file|-]`, ""] : [],
26409
+ ...global,
26410
+ "Examples:",
26411
+ ...raw ? [` praxis ${API_WORD} GET /model/v1/models`] : [],
26412
+ ` ${sample ? example(sample) : "praxis --help"}`
26413
+ ].join(`
26414
+ `);
26415
+ }
26416
+ function domains(commands) {
26417
+ return [...new Set(commands.map((c) => c.words[1]))].sort();
26418
+ }
26419
+ var workflows = [
26420
+ { words: ["login"], usage: "login", summary: "Sign in with a browser device code." },
26421
+ { words: ["logout"], usage: "logout", summary: "Remove the saved login from the keychain and fallback file." },
26422
+ { words: ["whoami"], usage: "whoami", summary: "Show the signed-in identity and credential storage location." },
26423
+ { words: ["org", "list"], usage: "org list", summary: "List organizations available to the login." },
26424
+ { words: ["org", "switch"], usage: "org switch <organization_id>", summary: "Switch the login organization." },
26425
+ { words: ["app", "create"], usage: "app create <name> [--dir <path>] [--template <dir>] [--no-install]", summary: "Create an application project from the standard template and install its dependencies.", example: "praxis app create my-app" },
26426
+ { words: ["app", "deploy"], usage: "app deploy [--dir <path>] [--no-build]", summary: "Build the project, publish it, create declared secrets, run the health check and print the URL.", example: "praxis app deploy --dir ./my-app" },
26427
+ { words: ["app", "rollback"], usage: "app rollback [--dir <path>] [--to <version_id>]", summary: "Deploy the previous version again (or --to a given version) and wait until it is active.", example: "praxis app rollback --to <version_id>" },
26428
+ { words: ["skill"], usage: "skill [--install <dir>]", summary: "Print the AI skill, or write <dir>/praxis-cli/SKILL.md." }
26429
+ ];
26430
+ var workflowNouns = [...new Set(workflows.filter((w) => w.words.length > 1).map((w) => w.words[0]))];
26431
+ function nounHelp(noun) {
26432
+ const mine = workflows.filter((w) => w.words[0] === noun);
26433
+ const width = Math.max(...mine.map((w) => w.usage.length));
26434
+ return [...mine.map((w) => ` praxis ${w.usage.padEnd(width)} ${w.summary}`), "", `Run \`praxis ${noun} <command> --help\` for a command's options.`, "", "Examples:", ...mine.map((w) => ` ${w.example ?? `praxis ${w.usage}`}`)].join(`
26435
+ `);
26436
+ }
26437
+ function workflowHelp(workflow, options) {
26438
+ return [
26439
+ `praxis ${workflow.usage}`,
26440
+ workflow.summary,
26441
+ "",
26442
+ "Options:",
26443
+ ...[...options, ...globalOptions].map((s) => ` ${describeOption(s)}`),
25916
26444
  " -h is an alias of --help",
25917
26445
  "PRAXIS_ENV=develop|production (default: develop); no --env option.",
25918
26446
  "",
25919
26447
  "Examples:",
25920
- ` ${matching[0] ? example(matching.find((c) => c.words.at(-1) === "list") ?? matching[0]) : "praxis --help"}`
26448
+ ` ${workflow.example ?? `praxis ${workflow.usage}`}`
25921
26449
  ].join(`
25922
26450
  `);
25923
26451
  }
25924
26452
 
25925
26453
  // src/config/env.ts
25926
26454
  var DEFAULT_ENV = "develop";
26455
+ function validateApiUrl(value) {
26456
+ const fail = () => {
26457
+ throw new UsageError("PRAXIS_API_URL must be an https URL on deepraxis.com", "Use https://api.deepraxis.com or https://api-develop.deepraxis.com; credentials are never sent to other hosts.");
26458
+ };
26459
+ let u;
26460
+ try {
26461
+ u = new URL(value);
26462
+ } catch {
26463
+ return fail();
26464
+ }
26465
+ if (u.protocol !== "https:" || u.username || u.password || u.search || u.hash)
26466
+ fail();
26467
+ if (!(u.hostname === "api.deepraxis.com" || u.hostname.endsWith(".deepraxis.com")))
26468
+ fail();
26469
+ return value.replace(/\/+$/, "");
26470
+ }
26471
+ function inferEnvFromApiUrl(value) {
26472
+ return new URL(value).hostname.includes("-develop.") ? "develop" : "production";
26473
+ }
25927
26474
  function environment(vars = process.env) {
25928
- const env = vars.PRAXIS_ENV ?? DEFAULT_ENV;
26475
+ const apiOverride = vars.PRAXIS_API_URL ? validateApiUrl(vars.PRAXIS_API_URL) : undefined;
26476
+ const env = vars.PRAXIS_ENV ?? (apiOverride ? inferEnvFromApiUrl(apiOverride) : DEFAULT_ENV);
25929
26477
  if (env !== "develop" && env !== "production")
25930
26478
  throw new UsageError("PRAXIS_ENV must be develop or production", "Set PRAXIS_ENV=develop or PRAXIS_ENV=production.");
25931
26479
  const suffix = env === "develop" ? "-develop" : "";
@@ -25936,10 +26484,10 @@ function environment(vars = process.env) {
25936
26484
  throw new Error;
25937
26485
  return value.replace(/\/+$/, "");
25938
26486
  } catch {
25939
- throw new UsageError("Invalid PRAXIS endpoint URL", "Set PRAXIS_API_URL / PRAXIS_ACCOUNT_URL / PRAXIS_GATEWAY_URL to HTTP(S) host URLs.");
26487
+ throw new UsageError("Invalid PRAXIS endpoint URL", "Set PRAXIS_ACCOUNT_URL / PRAXIS_GATEWAY_URL to HTTP(S) host URLs.");
25940
26488
  }
25941
26489
  };
25942
- return { env, apiUrl: url(vars.PRAXIS_API_URL ?? `https://api${suffix}.deepraxis.com`), accountUrl: url(vars.PRAXIS_ACCOUNT_URL ?? `https://account${suffix}.deepraxis.com`), gatewayUrl: url(vars.PRAXIS_GATEWAY_URL ?? `https://gateway${suffix}.deepraxis.com`) };
26490
+ return { env, apiUrl: apiOverride ?? `https://api${suffix}.deepraxis.com`, accountUrl: url(vars.PRAXIS_ACCOUNT_URL ?? `https://account${suffix}.deepraxis.com`), gatewayUrl: url(vars.PRAXIS_GATEWAY_URL ?? `https://gateway${suffix}.deepraxis.com`) };
25943
26491
  }
25944
26492
 
25945
26493
  // src/auth/token-store.ts
@@ -26169,6 +26717,9 @@ async function withLock(lockPath, run) {
26169
26717
  }
26170
26718
 
26171
26719
  // src/auth/credentials.ts
26720
+ function credentialSource(vars) {
26721
+ return vars.PRAXIS_API_KEY ? "api-key" : vars.PRAXIS_API_TOKEN ? "machine-token" : "login";
26722
+ }
26172
26723
  async function identityRpc(config, fetchImpl, method, params, token) {
26173
26724
  const response = await fetchImpl(`${config.gatewayUrl}/rpc/practice-identity`, {
26174
26725
  method: "POST",
@@ -26197,16 +26748,22 @@ function jwtFetch(fetchImpl, token) {
26197
26748
  function credentials(config, vars, ports) {
26198
26749
  const path = ports.path ?? tokenPath(config.env);
26199
26750
  const store = ports.store ?? createTokenStore(config.env, path, ports.secretStore);
26751
+ const source = credentialSource(vars);
26200
26752
  const apiKey = vars.PRAXIS_API_KEY;
26753
+ const machineToken = source === "machine-token" ? vars.PRAXIS_API_TOKEN : undefined;
26201
26754
  const remember = ports.remember ?? (() => {});
26202
26755
  if (apiKey)
26203
26756
  remember(apiKey);
26757
+ if (machineToken)
26758
+ remember(machineToken);
26204
26759
  let cached;
26205
26760
  let cachedOrg;
26206
26761
  let pending;
26207
26762
  const requireLogin = () => {
26208
26763
  if (apiKey)
26209
26764
  throw new UsageError("The API Key determines the organization; listing or switching login organizations is unavailable.", "Unset PRAXIS_API_KEY and run `praxis login`, then retry the org command.");
26765
+ if (machineToken)
26766
+ throw new UsageError("The machine token determines the organization; listing or switching login organizations is unavailable.", "Unset PRAXIS_API_TOKEN and run `praxis login`, then retry the org command.");
26210
26767
  };
26211
26768
  async function exchange(organizationId) {
26212
26769
  const stored = await store.load();
@@ -26231,6 +26788,11 @@ function credentials(config, vars, ports) {
26231
26788
  throw new UsageError("--org cannot override an API Key organization", "Remove --org or unset PRAXIS_API_KEY and run `praxis login`.");
26232
26789
  return { source: "api-key", token: apiKey };
26233
26790
  }
26791
+ if (machineToken) {
26792
+ if (org)
26793
+ throw new UsageError("--org cannot override a machine token organization", "Remove --org or unset PRAXIS_API_TOKEN and run `praxis login`.");
26794
+ return { source: "machine-token", token: machineToken };
26795
+ }
26234
26796
  const stored = await store.load();
26235
26797
  const selected = org ?? stored?.organization_id;
26236
26798
  const opaqueFresh = stored !== null && stored.expires_at - 30000 > ports.now();
@@ -26250,11 +26812,12 @@ function credentials(config, vars, ports) {
26250
26812
  }
26251
26813
  }
26252
26814
  return {
26815
+ source,
26253
26816
  get,
26254
26817
  requireLogin,
26255
26818
  async client(org) {
26256
26819
  const c = await get(org);
26257
- return new Praxis({ apiKey: c.token, baseUrl: config.apiUrl, fetch: c.source === "login" ? jwtFetch(ports.fetch, c.token) : ports.fetch });
26820
+ return new Praxis({ apiKey: c.token, baseUrl: config.apiUrl, fetch: c.source === "api-key" ? ports.fetch : jwtFetch(ports.fetch, c.token) });
26258
26821
  },
26259
26822
  async rpc(method, params = {}, org) {
26260
26823
  const c = await get(org);
@@ -26287,7 +26850,7 @@ function commandSummary(command) {
26287
26850
  const chars = [...description];
26288
26851
  return chars.length > 120 ? chars.slice(0, 119).join("") + "…" : description;
26289
26852
  }
26290
- const words = [...command.words];
26853
+ const words = command.words.slice(1);
26291
26854
  const verb = (words.pop() ?? "use").replace(/-/g, " ");
26292
26855
  if (verb === "list" && words.length && !words.at(-1).endsWith("s"))
26293
26856
  words[words.length - 1] += "s";
@@ -26305,29 +26868,25 @@ function skillDocument(commands) {
26305
26868
  "## General rules",
26306
26869
  "",
26307
26870
  "- Select the environment only with `PRAXIS_ENV`; there is no `--env` option. The dev package defaults to develop.",
26308
- "- Authenticate with `PRAXIS_API_KEY` or `praxis login`. API keys determine the organization; login sessions can use `--org <organization_id>`.",
26871
+ "- Authenticate with `PRAXIS_API_KEY`, `PRAXIS_API_TOKEN` (a machine token, sent in the Authorization header; computers have it set) or `praxis login`, in that order. Login saves the session even when an environment credential takes precedence; unset the named variable in its warning to use the saved login. API keys and machine tokens determine the organization; login sessions can use `--org <organization_id>`. `PRAXIS_API_URL` overrides the API base and must be an https deepraxis.com URL.",
26309
26872
  "- AI mode is enabled automatically in supported agent environments. Use `--format agent` to select it explicitly.",
26310
26873
  "- Use `--json` for the complete JSON response without presentation truncation. Successful JSON output goes to stdout; errors go to stderr.",
26311
26874
  "- Supply bodies with `--data JSON`, `--data @file.json`, or `--data -` for stdin. Scalar field options override matching JSON fields. Structured fields require `--data`.",
26312
26875
  "- Deletion requires `--yes` in AI mode. Confirm the intended resource before using it.",
26313
26876
  "- Use `--limit N` to limit a server page for SDK-paginated commands. Other lists apply it only to displayed rows; `--param-limit` still sends the API parameter when available. `--all` follows supported pagination and cannot be combined with `--limit`.",
26314
- "- Error JSON has an `error` object: `code` identifies the failure, `message` describes it, `hint` suggests recovery, `env` identifies the environment, `command` identifies the command, `status` is the HTTP status, and `request_id` correlates diagnostics. Unavailable fields are null. Exit codes: 0 success, 1 runtime/API error, 2 usage error.",
26877
+ "- Error JSON has an `error` object: `code` identifies the failure, `message` describes it, `hint` suggests recovery, `env` identifies the environment, `command` identifies the command, `status` is the HTTP status, and `request_id` correlates diagnostics. Authentication failures also include `credential_source` (api-key, machine-token, or login); follow the source-specific hint. Unavailable fields are null. Exit codes: 0 success, 1 runtime/API error, 2 usage error.",
26315
26878
  "- Append `--help` to a command for its optional parameters. Required scalar body options below can also be supplied as fields in `--data`.",
26879
+ "- Two layers: top-level commands (`login`, `org`, `skill`, …) are workflows and session commands; every API operation is under `praxis api <domain> …`. `praxis api <METHOD> <path>` sends a raw request (the method is uppercase).",
26316
26880
  "",
26317
26881
  "## Account and CLI",
26318
26882
  "",
26319
- "praxis login — Sign in with a browser device code.",
26320
- "praxis logout — Remove the saved login from the keychain and fallback file.",
26321
- "praxis whoami — Show the signed-in identity and credential storage location.",
26322
- "praxis org list — List organizations available to the login.",
26323
- "praxis org switch <organization_id> — Switch the login organization.",
26324
- "praxis api <METHOD> <path> — Call an API path directly. (--data for a request body)",
26325
- "praxis skill — Print this skill; use --install <dir> to write <dir>/praxis-cli/SKILL.md."
26883
+ ...workflows.map((w) => `praxis ${w.usage} — ${w.summary.replace("Print the AI skill, or write", "Print this skill; use --install <dir> to write")}`),
26884
+ "praxis api <METHOD> <path> — Call an API path directly. (--data for a request body)"
26326
26885
  ];
26327
26886
  let domain;
26328
26887
  for (const command of commands) {
26329
- if (command.words[0] !== domain) {
26330
- domain = command.words[0];
26888
+ if (domainOf(command) !== domain) {
26889
+ domain = domainOf(command);
26331
26890
  lines.push("", `## ${domain}`, "");
26332
26891
  }
26333
26892
  const target = targetParam(command.op);
@@ -26446,7 +27005,12 @@ Enter code: ${code.user_code}` });
26446
27005
  const location = await (ports.store ?? createTokenStore(config.env, path)).save(toStored(flow.tokens, ports.now()));
26447
27006
  if (location !== "keychain")
26448
27007
  ports.emit({ kind: "message", channel: "stderr", text: "stored in a file (no system keychain available)" });
27008
+ const shadowedBy = ports.source === "api-key" ? "PRAXIS_API_KEY" : ports.source === "machine-token" ? "PRAXIS_API_TOKEN" : undefined;
26449
27009
  ports.emit({ kind: "message", text: `Logged in (${config.env}).` });
27010
+ if (shadowedBy)
27011
+ ports.emit({ kind: "message", channel: "stderr", text: `Note: ${shadowedBy} is set and takes precedence over this login. Unset it (unset ${shadowedBy}) to use the login.` });
27012
+ if (ports.json)
27013
+ ports.emit({ kind: "object", data: { env: config.env, ...shadowedBy ? { shadowed_by: shadowedBy } : {} } });
26450
27014
  }
26451
27015
  async function whoami(auth, env, org) {
26452
27016
  const credential = await auth.get(org);
@@ -26458,7 +27022,7 @@ async function whoami(auth, env, org) {
26458
27022
  source: credential.source,
26459
27023
  ...credential.storedIn ? { "stored in": credential.storedIn } : {},
26460
27024
  expires_at: credential.expiresAt ? new Date(credential.expiresAt).toISOString() : null,
26461
- ...credential.source === "api-key" ? { note: "The API key determines the organization." } : {}
27025
+ ...credential.source === "api-key" ? { note: "The API key determines the organization." } : credential.source === "machine-token" ? { note: "The machine token determines the organization." } : {}
26462
27026
  };
26463
27027
  }
26464
27028
 
@@ -26507,6 +27071,365 @@ async function api(config, auth, method, path, body, fetchImpl, emit, org) {
26507
27071
  emit({ kind: "object", data: result });
26508
27072
  }
26509
27073
 
27074
+ // src/commands/app.ts
27075
+ import { cpSync, existsSync as existsSync2, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, readFileSync as readFileSync2, renameSync, rmSync as rmSync2, statSync as statSync2, writeFileSync as writeFileSync2 } from "node:fs";
27076
+ import { tmpdir } from "node:os";
27077
+ import { dirname, join as join3, resolve } from "node:path";
27078
+
27079
+ // src/app/pure.ts
27080
+ import { createHash } from "node:crypto";
27081
+ var WORKER_NAME = /^(?!(?:www|api|admin|app|canary|canary-probe|status|docs|console)$)(?!.*--)[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/;
27082
+ function validateAppName(name) {
27083
+ if (!WORKER_NAME.test(name))
27084
+ throw new UsageError(`Invalid app name: ${name}`, "Use 3-40 lowercase letters, digits and single hyphens, starting and ending with a letter or digit; www, api, admin, app, canary, canary-probe, status, docs and console are reserved.");
27085
+ return name;
27086
+ }
27087
+ function stringEnd(text, i) {
27088
+ let j = i + 1;
27089
+ while (j < text.length && text[j] !== '"')
27090
+ j += text[j] === "\\" ? 2 : 1;
27091
+ return j;
27092
+ }
27093
+ function parseJsonc(text) {
27094
+ let out = "";
27095
+ for (let i = 0;i < text.length; i++) {
27096
+ const c = text[i];
27097
+ if (c === '"') {
27098
+ const j = stringEnd(text, i);
27099
+ out += text.slice(i, j + 1);
27100
+ i = j;
27101
+ continue;
27102
+ }
27103
+ if (c === "/" && text[i + 1] === "/") {
27104
+ while (i < text.length && text[i] !== `
27105
+ `)
27106
+ i++;
27107
+ out += `
27108
+ `;
27109
+ continue;
27110
+ }
27111
+ if (c === "/" && text[i + 1] === "*") {
27112
+ const end = text.indexOf("*/", i + 2);
27113
+ if (end < 0)
27114
+ throw new SyntaxError("Unterminated block comment");
27115
+ i = end + 1;
27116
+ out += " ";
27117
+ continue;
27118
+ }
27119
+ out += c;
27120
+ }
27121
+ let result = "";
27122
+ for (let i = 0;i < out.length; i++) {
27123
+ const c = out[i];
27124
+ if (c === '"') {
27125
+ const j = stringEnd(out, i);
27126
+ result += out.slice(i, j + 1);
27127
+ i = j;
27128
+ continue;
27129
+ }
27130
+ if (c === "," && /^\s*[}\]]/.test(out.slice(i + 1)))
27131
+ continue;
27132
+ result += c;
27133
+ }
27134
+ return JSON.parse(result);
27135
+ }
27136
+ function parseProject(value) {
27137
+ const fail = (m) => {
27138
+ throw new UsageError(m, 'praxis.jsonc needs {"kind":"application","name":"<app-name>"}; `praxis app create` writes it.');
27139
+ };
27140
+ if (!value || typeof value !== "object" || Array.isArray(value))
27141
+ return fail("praxis.jsonc must be an object");
27142
+ const v = value;
27143
+ if (v.kind !== "application")
27144
+ fail('praxis.jsonc kind must be "application"');
27145
+ if (typeof v.name !== "string" || !v.name)
27146
+ fail("praxis.jsonc has no name");
27147
+ const name = validateAppName(v.name);
27148
+ const secrets = {};
27149
+ if (v.secrets !== undefined) {
27150
+ if (!v.secrets || typeof v.secrets !== "object" || Array.isArray(v.secrets))
27151
+ fail("praxis.jsonc secrets must be an object");
27152
+ for (const [key, how] of Object.entries(v.secrets)) {
27153
+ if (!/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(key))
27154
+ fail(`Invalid secret name: ${key}`);
27155
+ if (how !== "generate")
27156
+ fail(`Secret ${key}: only "generate" is supported`);
27157
+ secrets[key] = "generate";
27158
+ }
27159
+ }
27160
+ if (v.healthcheck !== undefined && (typeof v.healthcheck !== "string" || !v.healthcheck.startsWith("/") || v.healthcheck.startsWith("//")))
27161
+ fail("praxis.jsonc healthcheck must be a path starting with /");
27162
+ return { name, secrets, ...typeof v.healthcheck === "string" ? { healthcheck: v.healthcheck } : {} };
27163
+ }
27164
+ function planSecrets(existing, declared, generate) {
27165
+ const have = new Set(existing);
27166
+ const bindings = [...have].map((name) => ({ type: "secret_text", name }));
27167
+ const created = [];
27168
+ for (const name of Object.keys(declared))
27169
+ if (!have.has(name)) {
27170
+ bindings.push({ type: "secret_text", name, text: generate() });
27171
+ created.push(name);
27172
+ }
27173
+ return { bindings, created };
27174
+ }
27175
+ function chooseRollbackTarget(deployments, currentVersionId) {
27176
+ for (const d of deployments) {
27177
+ const id = d.versions[0]?.version_id;
27178
+ if (id && id !== currentVersionId)
27179
+ return id;
27180
+ }
27181
+ return;
27182
+ }
27183
+ function verifyIntegrity(bytes, dist) {
27184
+ if (dist.integrity) {
27185
+ return dist.integrity.split(/\s+/).some((entry) => {
27186
+ const at = entry.indexOf("-");
27187
+ return entry.slice(0, at) === "sha512" && createHash("sha512").update(bytes).digest("base64") === entry.slice(at + 1);
27188
+ });
27189
+ }
27190
+ if (dist.shasum)
27191
+ return createHash("sha1").update(bytes).digest("hex") === dist.shasum;
27192
+ return false;
27193
+ }
27194
+ var templateTag = (env) => env === "develop" ? "dev" : "latest";
27195
+ function randomSecret(bytes = 32) {
27196
+ return Buffer.from(crypto.getRandomValues(new Uint8Array(bytes))).toString("base64url");
27197
+ }
27198
+ function decideBuildOutput(mode) {
27199
+ return mode === "human" ? "stream" : "capture";
27200
+ }
27201
+ function tailLines(text, count3) {
27202
+ return text.replace(/\s+$/, "").split(`
27203
+ `).slice(-count3).join(`
27204
+ `);
27205
+ }
27206
+ function nextSteps(dir, bunAvailable) {
27207
+ return [`cd ${dir}`, bunAvailable ? "bun run dev" : "npm run dev", "praxis app deploy"];
27208
+ }
27209
+
27210
+ // src/commands/app.ts
27211
+ var REGISTRY = "https://registry.npmjs.org/@deepraxis%2fapp-template";
27212
+ async function downloadTemplate(env, into, ports) {
27213
+ const meta = await ports.fetch(REGISTRY, { headers: { accept: "application/vnd.npm.install-v1+json" }, signal: AbortSignal.timeout(30000) });
27214
+ if (!meta.ok)
27215
+ throw new PraxisError({ code: "TEMPLATE_UNAVAILABLE", message: `Could not read the template package from the npm registry (${meta.status})` });
27216
+ const doc = await meta.json();
27217
+ const tag = templateTag(env), version = doc["dist-tags"]?.[tag];
27218
+ const dist = version ? doc.versions?.[version]?.dist : undefined;
27219
+ if (!version || !dist?.tarball)
27220
+ throw new PraxisError({ code: "TEMPLATE_UNAVAILABLE", message: `@deepraxis/app-template has no "${tag}" release` });
27221
+ const tarball = new URL(dist.tarball);
27222
+ if (tarball.protocol !== "https:")
27223
+ throw new PraxisError({ code: "TEMPLATE_UNAVAILABLE", message: "Template tarball is not served over https" });
27224
+ const res = await ports.fetch(tarball, { signal: AbortSignal.timeout(60000) });
27225
+ if (!res.ok)
27226
+ throw new PraxisError({ code: "TEMPLATE_UNAVAILABLE", message: `Template download failed (${res.status})` });
27227
+ const bytes = new Uint8Array(await res.arrayBuffer());
27228
+ if (!verifyIntegrity(bytes, dist))
27229
+ throw new PraxisError({ code: "TEMPLATE_INTEGRITY", message: `Template ${version} failed its integrity check; nothing was extracted` });
27230
+ const work = mkdtempSync(join3(tmpdir(), "praxis-template-"));
27231
+ try {
27232
+ writeFileSync2(join3(work, "template.tgz"), bytes);
27233
+ const code = await ports.spawn("tar", ["-xzf", "template.tgz", "package/template"], { cwd: work });
27234
+ if (code !== 0 || !existsSync2(join3(work, "package", "template")))
27235
+ throw new PraxisError({ code: "TEMPLATE_UNAVAILABLE", message: "Could not extract package/template from the template tarball" });
27236
+ cpSync(join3(work, "package", "template"), into, { recursive: true });
27237
+ } finally {
27238
+ rmSync2(work, { recursive: true, force: true });
27239
+ }
27240
+ return { version };
27241
+ }
27242
+ async function appCreate(args, env, ports) {
27243
+ const name = validateAppName(args.name);
27244
+ const dir = resolve(ports.cwd, args.dir ?? name);
27245
+ if (existsSync2(dir) && (!statSync2(dir).isDirectory() || readdirSync(dir).length))
27246
+ throw new UsageError(`${dir} already exists and is not empty`, "Pick another name or --dir.");
27247
+ mkdirSync2(dir, { recursive: true });
27248
+ let version = "local";
27249
+ try {
27250
+ if (args.template) {
27251
+ const source = resolve(ports.cwd, args.template);
27252
+ if (!existsSync2(source) || !statSync2(source).isDirectory())
27253
+ throw new UsageError(`--template ${source} is not a directory`);
27254
+ cpSync(source, dir, { recursive: true });
27255
+ } else
27256
+ version = (await downloadTemplate(env, dir, ports)).version;
27257
+ if (existsSync2(join3(dir, "_gitignore")))
27258
+ renameSync(join3(dir, "_gitignore"), join3(dir, ".gitignore"));
27259
+ const jsonc = join3(dir, "praxis.jsonc");
27260
+ if (existsSync2(jsonc))
27261
+ writeFileSync2(jsonc, readFileSync2(jsonc, "utf8").replaceAll("<app-name>", name));
27262
+ const pkg = join3(dir, "package.json");
27263
+ if (existsSync2(pkg))
27264
+ writeFileSync2(pkg, JSON.stringify({ ...JSON.parse(readFileSync2(pkg, "utf8")), name }, null, 2) + `
27265
+ `);
27266
+ } catch (error) {
27267
+ rmSync2(dir, { recursive: true, force: true });
27268
+ throw error;
27269
+ }
27270
+ if (args.install) {
27271
+ const pm = ports.has("bun") ? "bun" : "npm";
27272
+ const code = await ports.spawn(pm, ["install"], { cwd: dir });
27273
+ if (code !== 0)
27274
+ throw new PraxisError({ code: "INSTALL_FAILED", message: `${pm} install failed (exit ${code}); the project was created in ${dir}. Run it again there.` });
27275
+ }
27276
+ const next_steps = nextSteps(dir, ports.has("bun"));
27277
+ ports.human(`Created ${dir}
27278
+
27279
+ Next steps:
27280
+ ${next_steps.map((step) => ` ${step}`).join(`
27281
+ `)}`);
27282
+ ports.emit({ kind: "object", data: { dir, name, template_version: version, next_steps } });
27283
+ }
27284
+ function findProjectDir(dir, cwd) {
27285
+ if (dir) {
27286
+ const d = resolve(cwd, dir);
27287
+ if (!existsSync2(join3(d, "praxis.jsonc")))
27288
+ throw new UsageError(`No praxis.jsonc in ${d}`, "Run inside a project made by `praxis app create`, or pass --dir.");
27289
+ return d;
27290
+ }
27291
+ for (let d = resolve(cwd);; d = dirname(d)) {
27292
+ if (existsSync2(join3(d, "praxis.jsonc")))
27293
+ return d;
27294
+ if (dirname(d) === d)
27295
+ throw new UsageError("No praxis.jsonc found in this directory or its parents", "Run inside a project made by `praxis app create`, or pass --dir.");
27296
+ }
27297
+ }
27298
+ function loadProject(dir) {
27299
+ let value;
27300
+ try {
27301
+ value = parseJsonc(readFileSync2(join3(dir, "praxis.jsonc"), "utf8"));
27302
+ } catch (error) {
27303
+ throw new UsageError(`praxis.jsonc is not valid JSONC: ${error.message}`);
27304
+ }
27305
+ return parseProject(value);
27306
+ }
27307
+ function readTree(root) {
27308
+ const files = {};
27309
+ const walk = (rel) => {
27310
+ for (const entry of readdirSync(join3(root, rel), { withFileTypes: true })) {
27311
+ const path = rel ? `${rel}/${entry.name}` : entry.name;
27312
+ if (entry.isDirectory())
27313
+ walk(path);
27314
+ else if (entry.isFile())
27315
+ files[path] = new Uint8Array(readFileSync2(join3(root, path)));
27316
+ }
27317
+ };
27318
+ walk("");
27319
+ return files;
27320
+ }
27321
+ async function findWorker(client2, name) {
27322
+ for await (const w of await client2.application.workers.list())
27323
+ if (w.name === name)
27324
+ return w;
27325
+ return;
27326
+ }
27327
+ async function waitActive(client2, workerId, deployment, ports, timeoutMs = 120000) {
27328
+ const deadline = ports.now() + timeoutMs;
27329
+ let current = deployment;
27330
+ while (current.praxis.status !== "active") {
27331
+ if (current.praxis.status === "failed" || current.praxis.status === "cancelled")
27332
+ throw new PraxisError({ code: current.praxis.error?.code ?? "DEPLOYMENT_FAILED", message: current.praxis.error?.message ?? `Deployment ${current.id} ${current.praxis.status}` });
27333
+ if (ports.now() >= deadline)
27334
+ throw new PraxisError({ code: "DEPLOY_TIMEOUT", message: `Deployment ${current.id} did not become active within ${timeoutMs} ms; it may still be running` });
27335
+ await ports.wait(1000);
27336
+ current = await client2.application.workers.deployments.retrieve({ path: { worker_id: workerId, deployment_id: current.id } });
27337
+ }
27338
+ return current;
27339
+ }
27340
+ async function healthCheck2(url, path, ports, timeoutMs = 60000) {
27341
+ const target = url.replace(/\/+$/, "") + path;
27342
+ const deadline = ports.now() + timeoutMs;
27343
+ let last = "no response";
27344
+ for (;; ) {
27345
+ try {
27346
+ const res = await ports.fetch(target, { redirect: "manual", signal: AbortSignal.timeout(1e4) });
27347
+ if (res.status >= 200 && res.status < 300)
27348
+ return { path, status: res.status };
27349
+ last = String(res.status);
27350
+ } catch (error) {
27351
+ last = error.message;
27352
+ }
27353
+ if (ports.now() >= deadline)
27354
+ throw new PraxisError({ code: "HEALTHCHECK_FAILED", message: `Health check failed: GET ${target} answered ${last} for ${Math.round(timeoutMs / 1000)}s` });
27355
+ await ports.wait(2000);
27356
+ }
27357
+ }
27358
+ async function runBuild(pm, dir, ports) {
27359
+ if (decideBuildOutput(ports.mode) === "stream")
27360
+ return ports.spawn(pm, ["run", "build"], { cwd: dir });
27361
+ const started = ports.now();
27362
+ const { code, output } = await ports.spawnCapture(pm, ["run", "build"], { cwd: dir });
27363
+ const text = code === 0 ? `build ok in ${Math.round((ports.now() - started) / 100) / 10}s` : tailLines(output, 60);
27364
+ ports.emit({ kind: "message", channel: "stderr", text });
27365
+ return code;
27366
+ }
27367
+ async function appDeploy(args, client2, ports) {
27368
+ const dir = findProjectDir(args.dir, ports.cwd);
27369
+ const project = loadProject(dir);
27370
+ if (args.build) {
27371
+ const pm = ports.has("bun") ? "bun" : "npm";
27372
+ const code = await runBuild(pm, dir, ports);
27373
+ if (code !== 0)
27374
+ throw new PraxisError({ code: "BUILD_FAILED", message: `${pm} run build failed (exit ${code})` });
27375
+ }
27376
+ const server = join3(dir, "dist", "server"), clientDir = join3(dir, "dist", "client");
27377
+ if (!existsSync2(join3(server, "wrangler.json")) || !existsSync2(clientDir))
27378
+ throw new UsageError("No build output in dist/server and dist/client", "Run without --no-build, or build the project first.");
27379
+ const serverFiles = readTree(server);
27380
+ let input;
27381
+ try {
27382
+ input = publishInputFromBuild({ serverFiles, clientFiles: readTree(clientDir), wranglerJson: parseJsonc(new TextDecoder().decode(serverFiles["wrangler.json"])) }, project.name);
27383
+ } catch (error) {
27384
+ if (error instanceof PraxisError && error.code === "UNSUPPORTED")
27385
+ throw new PraxisError({ code: "UNSUPPORTED", message: `${error.message}. Remove those bindings from wrangler.jsonc and rebuild.` });
27386
+ throw error;
27387
+ }
27388
+ const worker = await findWorker(client2, project.name);
27389
+ const existing = worker ? (await client2.application.workers.secrets.list({ path: { worker_id: worker.id } })).map((s) => s.name) : [];
27390
+ const { bindings, created } = planSecrets(existing, project.secrets, ports.random);
27391
+ const named = new Set(bindings.map((b) => b.name));
27392
+ input = { ...input, bindings: [...(input.bindings ?? []).filter((b) => !(b.type === "secret_text" && named.has(b.name))), ...bindings], wait: true };
27393
+ const result = await client2.application.publish(input);
27394
+ let health = null;
27395
+ if (project.healthcheck)
27396
+ health = await healthCheck2(result.url, project.healthcheck, ports);
27397
+ ports.emit({ kind: "object", data: {
27398
+ url: result.url,
27399
+ worker_id: result.worker_id,
27400
+ version_id: result.version_id,
27401
+ deployment_id: result.deployment_id,
27402
+ uploaded: result.uploaded,
27403
+ reused: result.reused,
27404
+ secrets_created: created,
27405
+ health: health ? `${health.status} ${health.path}` : "not configured"
27406
+ } });
27407
+ }
27408
+ async function appRollback(args, client2, ports) {
27409
+ const project = loadProject(findProjectDir(args.dir, ports.cwd));
27410
+ const worker = await findWorker(client2, project.name);
27411
+ if (!worker)
27412
+ throw new PraxisError({ code: "NOT_FOUND", message: `No application named ${project.name}; deploy it first with \`praxis app deploy\`` });
27413
+ const deployments = [];
27414
+ for await (const d of await client2.application.workers.deployments.list({ path: { worker_id: worker.id } }))
27415
+ deployments.push(d);
27416
+ const active = deployments.find((d) => d.id === worker.praxis?.current_deployment_id) ?? deployments.find((d) => d.praxis.status === "active");
27417
+ const from = active?.versions[0]?.version_id;
27418
+ if (!from)
27419
+ throw new PraxisError({ code: "NOT_FOUND", message: `${project.name} has no active deployment` });
27420
+ const to = args.to ?? chooseRollbackTarget(deployments, from);
27421
+ if (!to)
27422
+ throw new UsageError(`${project.name} has no earlier version to roll back to`, "Deploy a second version first, or pass --to <version_id>.");
27423
+ if (to === from)
27424
+ throw new UsageError(`Version ${to} is already active`);
27425
+ const created = await client2.application.workers.deployments.create({ path: { worker_id: worker.id }, body: { strategy: "percentage", versions: [{ version_id: to, percentage: 100 }] } });
27426
+ const done = await waitActive(client2, worker.id, created, ports);
27427
+ ports.emit({ kind: "object", data: { url: worker.subdomain?.url ?? null, worker_id: worker.id, from_version: from, to_version: to, deployment_id: done.id } });
27428
+ }
27429
+
27430
+ // src/main.ts
27431
+ import { spawnSync } from "node:child_process";
27432
+
26510
27433
  // src/core/confirm.ts
26511
27434
  function destructive(method) {
26512
27435
  return /^(delete|purge|remove)(?:[A-Z-]|$)/.test(method);
@@ -26662,6 +27585,21 @@ function plain(value) {
26662
27585
  ` || c === "\r" || c === "\t" ? " " : "");
26663
27586
  }
26664
27587
 
27588
+ // src/output/list-columns.ts
27589
+ function workerStatus(item) {
27590
+ const row = record(item), status = record(row.praxis).status;
27591
+ if (typeof status !== "string")
27592
+ return item;
27593
+ return { ...row, status };
27594
+ }
27595
+ var listProjections = {
27596
+ "application.workers.list": workerStatus
27597
+ };
27598
+ function projectList(items, op) {
27599
+ const project = op ? listProjections[op] : undefined;
27600
+ return project ? items.map(project) : items;
27601
+ }
27602
+
26665
27603
  // src/output/human.ts
26666
27604
  var count3 = (n, noun) => `${n} ${noun}${n === 1 ? "" : "s"}`;
26667
27605
  function identity(result, ctx) {
@@ -26730,7 +27668,7 @@ function table(items, ctx, paint) {
26730
27668
  const text = truncate(v, sizes[i]);
26731
27669
  let styled = header ? paint.dim(text) : text;
26732
27670
  if (!header && ["status", "state"].includes(columns[i])) {
26733
- const color = /^(running|active|ready|succeeded|completed|enabled)$/i.test(v) ? paint.green : /^(pending|queued|starting|creating|paused)$/i.test(v) ? paint.yellow : /^(failed|error|cancelled|expired|disabled)$/i.test(v) ? paint.red : (s) => s;
27671
+ const color = /^(running|active|ready|succeeded|completed|enabled)$/i.test(v) ? paint.green : /^(pending|queued|starting|creating|paused)$/i.test(v) ? paint.yellow : /^(failed|error|cancelled|expired|disabled|deleted|purging|purged|suspended)$/i.test(v) ? paint.red : (s) => s;
26734
27672
  styled = color(text);
26735
27673
  }
26736
27674
  return styled + (i === row.length - 1 ? "" : " ".repeat(Math.max(0, sizes[i] - width(text))));
@@ -26790,7 +27728,7 @@ function renderHuman(result, ctx) {
26790
27728
  ` : "") };
26791
27729
  case "list":
26792
27730
  return {
26793
- stdout: result.items.length ? table(result.items, ctx, out) : out.dim(`No ${plain(resource)}${/(s|x|ch|sh)$/.test(resource) ? "es" : "s"}.`) + `
27731
+ stdout: result.items.length ? table(projectList(result.items, result.op), ctx, out) : out.dim(`No ${plain(resource)}${/(s|x|ch|sh)$/.test(resource) ? "es" : "s"}.`) + `
26794
27732
  `,
26795
27733
  stderr: err.dim(`${result.total !== undefined ? `${result.items.length} of ${result.total} items` : count3(result.items.length, "item")}${result.nextCursor ? ` · next: ${ctx.nextCommand ?? "praxis --help"}` : ""}`) + `
26796
27734
  `
@@ -26862,8 +27800,8 @@ ${usage ? `usage: ${JSON.stringify(usage)}
26862
27800
  return { stdout, stderr };
26863
27801
  }
26864
27802
  case "list": {
26865
- const columns = columnsFor(result.items);
26866
- const lines = columns.length ? ["|" + columns.map(cell).join("|") + "|", "|" + columns.map(() => "---").join("|") + "|", ...result.items.map((item) => "|" + columns.map((key) => cell(timestamp(key, record(item)[key]) ?? scalar(record(item)[key]))).join("|") + "|")] : [];
27803
+ const items = projectList(result.items, result.op), columns = columnsFor(items);
27804
+ const lines = columns.length ? ["|" + columns.map(cell).join("|") + "|", "|" + columns.map(() => "---").join("|") + "|", ...items.map((item) => "|" + columns.map((key) => cell(timestamp(key, record(item)[key]) ?? scalar(record(item)[key]))).join("|") + "|")] : [];
26867
27805
  lines.push(result.total !== undefined ? `${result.items.length} of ${result.total} rows; more: \`${ctx.moreCommand ?? "praxis --help"}\`` : `${result.items.length} rows; ${result.nextCursor ? `more: \`${ctx.nextCommand ?? "praxis --help"}\`` : "end"}`);
26868
27806
  return { stdout: lines.join(`
26869
27807
  `) + `
@@ -26874,7 +27812,7 @@ ${usage ? `usage: ${JSON.stringify(usage)}
26874
27812
 
26875
27813
  // src/output/render.ts
26876
27814
  function errorJSON(result, ctx) {
26877
- return JSON.stringify({ error: { code: result.code, message: result.message, hint: result.hint ?? null, env: result.env, command: ctx.command ?? null, status: result.status ?? null, request_id: result.request_id ?? null } }) + `
27815
+ return JSON.stringify({ error: { code: result.code, message: result.message, hint: result.hint ?? null, env: result.env, command: ctx.command ?? null, status: result.status ?? null, request_id: result.request_id ?? null, ...result.credential_source ? { credential_source: result.credential_source } : {} } }) + `
26878
27816
  `;
26879
27817
  }
26880
27818
  function render(result, ctx) {
@@ -27015,6 +27953,16 @@ var humanize = (code) => {
27015
27953
  const words = code.toLowerCase().split("_").filter(Boolean).join(" ");
27016
27954
  return words.charAt(0).toUpperCase() + words.slice(1);
27017
27955
  };
27956
+ function authHint(source) {
27957
+ switch (source) {
27958
+ case "api-key":
27959
+ return "The API key from PRAXIS_API_KEY was rejected; check or replace it, or unset it to use `praxis login`.";
27960
+ case "machine-token":
27961
+ return "The machine token from PRAXIS_API_TOKEN was rejected (it may have expired); unset it to use `praxis login`, or refresh it.";
27962
+ case "login":
27963
+ return "Run `praxis login` or set PRAXIS_API_KEY.";
27964
+ }
27965
+ }
27018
27966
  function errorInput(error, ctx) {
27019
27967
  const sdk = error instanceof PraxisError ? error : undefined;
27020
27968
  const raw = record(sdk?.raw), nested = record(raw.error);
@@ -27029,11 +27977,13 @@ function errorInput(error, ctx) {
27029
27977
  if (stripped)
27030
27978
  message = `${humanize(code)}${message ? `: ${message}` : ""}`;
27031
27979
  const status = sdk?.status, request_id = sdk?.requestId;
27980
+ const authFailure = status === 401 || ["NOT_LOGGED_IN", "UNAUTHENTICATED", "TOKEN_REVOKED", "LOGIN_FAILED"].includes(code);
27981
+ const source = ctx.credentialSource ?? "login";
27032
27982
  let hint = genericHint;
27033
27983
  if (error instanceof UsageError)
27034
27984
  hint = error.hint;
27035
- else if (status === 401 || ["NOT_LOGGED_IN", "UNAUTHENTICATED", "TOKEN_REVOKED", "LOGIN_FAILED"].includes(code))
27036
- hint = "Run `praxis login` or set PRAXIS_API_KEY.";
27985
+ else if (authFailure)
27986
+ hint = authHint(source);
27037
27987
  else if (status === 404)
27038
27988
  hint = ctx.listCommand ? `Check the id; list existing ones with \`${ctx.listCommand}\`` : "Check the id.";
27039
27989
  else if (status === 403)
@@ -27042,7 +27992,7 @@ function errorInput(error, ctx) {
27042
27992
  hint = "Rate limited; retry later.";
27043
27993
  else if (status !== undefined && status >= 500)
27044
27994
  hint = `Server error; retry later.${request_id ? ` Request id: ${request_id}.` : ""}`;
27045
- return { kind: "error", code, message, hint, env: ctx.env, ...status !== undefined ? { status } : {}, ...request_id ? { request_id } : {} };
27995
+ return { kind: "error", code, message, hint, env: ctx.env, ...authFailure ? { credential_source: source } : {}, ...status !== undefined ? { status } : {}, ...request_id ? { request_id } : {} };
27046
27996
  }
27047
27997
 
27048
27998
  // src/output/progress.ts
@@ -27072,9 +28022,9 @@ function startProgress(ctx, write = (text) => writeOutput({ stderr: text })) {
27072
28022
  }
27073
28023
 
27074
28024
  // src/main.ts
27075
- var version = "0.1.1-dev.f0ef747";
28025
+ var version = "0.2.0-dev.1046919";
27076
28026
  var commands = commandTree(operations);
27077
- var manual = [["login"], ["logout"], ["whoami"], ["org", "list"], ["org", "switch"], ["api"], ["skill"]];
28027
+ var manual = [...workflows.map((w) => w.words), [API_WORD]];
27078
28028
  function route(argv) {
27079
28029
  const words = [], args = [];
27080
28030
  for (let i = 0;i < argv.length; i++) {
@@ -27090,7 +28040,11 @@ function route(argv) {
27090
28040
  continue;
27091
28041
  }
27092
28042
  words.push(arg);
28043
+ if (words.length === 1 && words[0] === API_WORD && HTTP_METHOD.test(argv[i + 1] ?? ""))
28044
+ return { words, args: [...args, ...argv.slice(i + 1)] };
27093
28045
  const command = commands.find((c) => c.words.length === words.length && c.words.every((w, n) => w === words[n]));
28046
+ if (words.length === 1 && words[0] === API_WORD && argv[i + 1] !== undefined && !argv[i + 1].startsWith("-"))
28047
+ continue;
27094
28048
  if (command || manual.some((c) => c.length === words.length && c.every((w, n) => w === words[n])))
27095
28049
  return { words, args: [...args, ...argv.slice(i + 1)], command };
27096
28050
  }
@@ -27111,13 +28065,13 @@ var defaults = {
27111
28065
  chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
27112
28066
  return Buffer.concat(chunks).toString("utf8");
27113
28067
  },
27114
- ask: () => new Promise((resolve) => {
28068
+ ask: () => new Promise((resolve2) => {
27115
28069
  const input = createInterface({ input: process.stdin, terminal: false });
27116
28070
  input.once("line", (line) => {
27117
- resolve(/^(y|yes)$/i.test(line.trim()));
28071
+ resolve2(/^(y|yes)$/i.test(line.trim()));
27118
28072
  input.close();
27119
28073
  });
27120
- input.once("close", () => resolve(false));
28074
+ input.once("close", () => resolve2(false));
27121
28075
  }),
27122
28076
  async openBrowser(url) {
27123
28077
  try {
@@ -27125,15 +28079,35 @@ var defaults = {
27125
28079
  if (!["https:", "http:"].includes(parsed.protocol))
27126
28080
  return;
27127
28081
  const cmd = process.platform === "darwin" ? ["open", url] : process.platform === "win32" ? ["rundll32", "url.dll,FileProtocolHandler", url] : ["xdg-open", url];
27128
- await new Promise((resolve, reject) => {
28082
+ await new Promise((resolve2, reject) => {
27129
28083
  const child = spawn2(cmd[0], cmd.slice(1), { stdio: "ignore" });
27130
28084
  child.once("error", reject);
27131
- child.once("close", () => resolve());
28085
+ child.once("close", () => resolve2());
27132
28086
  });
27133
28087
  } catch {}
27134
28088
  },
27135
- wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
27136
- render
28089
+ wait: (ms) => new Promise((resolve2) => setTimeout(resolve2, ms)),
28090
+ render,
28091
+ spawn: (cmd, args, options) => new Promise((resolve2, reject) => {
28092
+ const child = spawn2(cmd, args, { cwd: options.cwd, stdio: ["ignore", 2, 2] });
28093
+ child.once("error", reject);
28094
+ child.once("close", (code) => resolve2(code ?? 1));
28095
+ }),
28096
+ spawnCapture: (cmd, args, options) => new Promise((resolve2, reject) => {
28097
+ const child = spawn2(cmd, args, { cwd: options.cwd, stdio: ["ignore", "pipe", "pipe"] });
28098
+ const chunks = [];
28099
+ child.stdout.on("data", (c) => chunks.push(c));
28100
+ child.stderr.on("data", (c) => chunks.push(c));
28101
+ child.once("error", reject);
28102
+ child.once("close", (code) => resolve2({ code: code ?? 1, output: Buffer.concat(chunks).toString("utf8") }));
28103
+ }),
28104
+ has: (bin) => spawnSync(process.platform === "win32" ? "where" : "which", [bin], { stdio: "ignore" }).status === 0,
28105
+ cwd: process.cwd()
28106
+ };
28107
+ var appOptions = {
28108
+ "app create": [{ name: "dir", type: "string", description: "Directory to create the project in (default: ./<name>)." }, { name: "template", type: "string", description: "Copy a local template directory instead of downloading the standard template." }, { name: "no-install", type: "boolean", description: "Skip installing dependencies." }],
28109
+ "app deploy": [{ name: "dir", type: "string", description: "Project directory (default: the nearest parent containing praxis.jsonc)." }, { name: "no-build", type: "boolean", description: "Publish the existing dist/ output without building." }],
28110
+ "app rollback": [{ name: "dir", type: "string", description: "Project directory (default: the nearest parent containing praxis.jsonc)." }, { name: "to", type: "string", description: "Version id to deploy (default: the previous version)." }]
27137
28111
  };
27138
28112
  async function main(argv, injected = {}) {
27139
28113
  const ports = { ...defaults, ...injected };
@@ -27141,6 +28115,8 @@ async function main(argv, injected = {}) {
27141
28115
  const write = outputSession((result, context) => ports.render(redact(result, secrets), context));
27142
28116
  if (ports.env.PRAXIS_API_KEY)
27143
28117
  secrets.push(ports.env.PRAXIS_API_KEY);
28118
+ if (ports.env.PRAXIS_API_TOKEN)
28119
+ secrets.push(ports.env.PRAXIS_API_TOKEN);
27144
28120
  let ctx = {
27145
28121
  json: false,
27146
28122
  ...decideOutputMode({ json: false, stdoutIsTTY: ports.stdoutIsTTY, env: ports.env }),
@@ -27163,7 +28139,7 @@ async function main(argv, injected = {}) {
27163
28139
  const selected = route(argv);
27164
28140
  ctx.command = commandLine(selected.words);
27165
28141
  ctx.resource = selected.words.at(-2) ?? selected.words[0];
27166
- const specs = [...globalOptions, ...selected.command ? [...operationOptions(selected.command.op), ...selected.command.op.body ? [dataOption] : []] : selected.words[0] === "api" ? [dataOption] : selected.words[0] === "skill" ? [{ name: "install", type: "string" }] : []];
28142
+ const specs = [...globalOptions, ...selected.command ? [...operationOptions(selected.command.op), ...selected.command.op.body ? [dataOption] : []] : selected.words.join(" ") === API_WORD ? [dataOption] : selected.words[0] === "skill" ? [{ name: "install", type: "string" }] : appOptions[selected.words.join(" ")] ?? []];
27167
28143
  const outputFlags = globalsOf(parseArgs(outputModeArgs(selected.args, specs), globalOptions));
27168
28144
  ctx.json = Boolean(outputFlags.json);
27169
28145
  Object.assign(ctx, decideOutputMode({ format: outputFlags.format, json: ctx.json, stdoutIsTTY: ports.stdoutIsTTY, env: ports.env }));
@@ -27177,15 +28153,22 @@ async function main(argv, injected = {}) {
27177
28153
  return 0;
27178
28154
  }
27179
28155
  if (!selected.words.length || !selected.command && !manual.some((c) => c.join(" ") === selected.words.join(" "))) {
27180
- if (selected.words.length && !commands.some((c) => selected.words.every((w, i) => c.words[i] === w)) && selected.words.join(" ") !== "org")
27181
- throw new UsageError(`Unknown command: ${selected.words.join(" ")}`);
28156
+ if (selected.words.length && !commands.some((c) => selected.words.every((w, i) => c.words[i] === w)) && !workflowNouns.includes(selected.words.join(" "))) {
28157
+ const moved = movedTo(commands, selected.words);
28158
+ throw new UsageError(`Unknown command: ${selected.words.join(" ")}`, moved ? `Generated commands moved under \`praxis api\`. Did you mean: ${moved}?` : selected.words[0] === API_WORD ? "Run `praxis api --help` to list API domains." : "Run `praxis --help`.");
28159
+ }
27182
28160
  if (parsed.positional.length)
27183
28161
  throw new UsageError("Unexpected arguments");
27184
- emit({ kind: "message", channel: "stdout", text: selected.words.join(" ") === "org" ? `praxis org list
27185
- praxis org switch <organization_id>
27186
-
27187
- Examples:
27188
- praxis org list` : help(commands, selected.words) });
28162
+ const noun = selected.words.join(" ");
28163
+ emit({ kind: "message", channel: "stdout", text: workflowNouns.includes(noun) ? nounHelp(noun) : help(commands, selected.words) });
28164
+ return 0;
28165
+ }
28166
+ if (selected.words.join(" ") === API_WORD && !parsed.positional.length && !flags.help) {
28167
+ emit({ kind: "message", channel: "stdout", text: help(commands, [API_WORD]) });
28168
+ return 0;
28169
+ }
28170
+ if (flags.help && selected.words.join(" ") === API_WORD && !parsed.positional.length) {
28171
+ emit({ kind: "message", channel: "stdout", text: help(commands, [API_WORD]) });
27189
28172
  return 0;
27190
28173
  }
27191
28174
  if (flags.help && selected.words[0] === "skill") {
@@ -27193,6 +28176,11 @@ Examples:
27193
28176
  Print the AI skill or write <dir>/praxis-cli/SKILL.md.` });
27194
28177
  return 0;
27195
28178
  }
28179
+ const workflow = workflows.find((w) => w.example && w.words.join(" ") === selected.words.join(" "));
28180
+ if (flags.help && workflow) {
28181
+ emit({ kind: "message", channel: "stdout", text: workflowHelp(workflow, appOptions[workflow.words.join(" ")] ?? []) });
28182
+ return 0;
28183
+ }
27196
28184
  if (flags.help) {
27197
28185
  emit({ kind: "message", channel: "stdout", text: selected.command ? help(commands, selected.words, selected.command) : `praxis ${selected.words.join(" ")}${selected.words[0] === "api" ? " <METHOD> <path> [--data JSON|@file|-]" : selected.words[1] === "switch" ? " <organization_id>" : ""}
27198
28186
  ${globalOptions.map((s) => "--" + s.name).join(" ")}
@@ -27229,6 +28217,7 @@ Examples:
27229
28217
  const auth = credentials(config, ports.env, { fetch: wireFetch, now: ports.now, path, store, remember: (s) => {
27230
28218
  secrets.push(s);
27231
28219
  } });
28220
+ ctx.credentialSource = auth.source;
27232
28221
  const org = flags.org;
27233
28222
  const confirm = (method) => confirmOperation(method, { yes: Boolean(flags.yes), noInput: Boolean(flags["no-input"]) || ctx.mode === "agent", stdinIsTTY: ports.stdinIsTTY, ask: async () => {
27234
28223
  stopProgress();
@@ -27286,7 +28275,7 @@ Examples:
27286
28275
  return 0;
27287
28276
  }
27288
28277
  const name = selected.words.join(" ");
27289
- const arity = name === "api" ? 2 : name === "org switch" ? 1 : 0;
28278
+ const arity = name === "api" ? 2 : name === "org switch" || name === "app create" ? 1 : 0;
27290
28279
  if (parsed.positional.length !== arity)
27291
28280
  throw new UsageError(`${name} expects ${arity} positional argument(s)`);
27292
28281
  if (!quiet)
@@ -27295,7 +28284,8 @@ Examples:
27295
28284
  case "login":
27296
28285
  if (flags["no-input"] || quiet)
27297
28286
  throw new UsageError("login requires displaying a device code", "Remove --no-input / --quiet or set PRAXIS_API_KEY for scripts.");
27298
- await login(config, path, { ...ports, store, fetch: wireFetch, emit, remember: (s) => secrets.push(s) });
28287
+ ctx.credentialSource = "login";
28288
+ await login(config, path, { ...ports, source: auth.source, json: ctx.mode === "json", store, fetch: wireFetch, emit, remember: (s) => secrets.push(s) });
27299
28289
  break;
27300
28290
  case "logout":
27301
28291
  emit({ kind: "message", text: await store.delete() ? "Logged out." : "Not logged in." });
@@ -27318,8 +28308,29 @@ Examples:
27318
28308
  case "org switch":
27319
28309
  emit({ kind: "object", data: await auth.switchOrganization(parsed.positional[0]) });
27320
28310
  break;
28311
+ case "app create": {
28312
+ const appPorts = { ...ports, mode: ctx.mode, emit, human: (text) => {
28313
+ if (ctx.mode === "human")
28314
+ emit({ kind: "message", channel: "stdout", text });
28315
+ }, random: randomSecret };
28316
+ await appCreate({ name: parsed.positional[0], dir: parsed.flags.dir?.[0], template: parsed.flags.template?.[0], install: !parsed.flags["no-install"] }, config.env, appPorts);
28317
+ break;
28318
+ }
28319
+ case "app deploy":
28320
+ case "app rollback": {
28321
+ const appPorts = { ...ports, mode: ctx.mode, emit, human: () => {}, random: randomSecret };
28322
+ const client2 = await auth.client(org);
28323
+ const dir = parsed.flags.dir?.[0];
28324
+ if (name === "app deploy")
28325
+ await appDeploy({ dir, build: !parsed.flags["no-build"] }, client2, appPorts);
28326
+ else
28327
+ await appRollback({ dir, to: parsed.flags.to?.[0] }, client2, appPorts);
28328
+ break;
28329
+ }
27321
28330
  case "api": {
27322
- const method = parsed.positional[0].toUpperCase();
28331
+ const method = parsed.positional[0];
28332
+ if (!HTTP_METHOD.test(method))
28333
+ throw new UsageError(`Unknown command: api ${method}`, "Run `praxis api --help` to list API domains; raw requests use an uppercase method, such as `praxis api GET /model/v1/models`.");
27323
28334
  await confirm(method.toLowerCase());
27324
28335
  if (!quiet) {
27325
28336
  stopProgress();