@deepraxis/cli 0.3.0-dev.da03302 → 0.3.0-dev.e226dc2

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 (3) hide show
  1. package/COMMANDS.md +8 -2
  2. package/dist/praxis.js +1158 -79
  3. package/package.json +1 -1
package/dist/praxis.js CHANGED
@@ -13984,11 +13984,15 @@ var init_flag_registry_generated = __esm(() => {
13984
13984
  FLAGS = {
13985
13985
  "agent-cognition-idle-wake": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "genius", ticket: 540, expires: "2026-11-30", system: "flagship" },
13986
13986
  "cognition-weight-driven": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "praxis-bd", ticket: 1760, expires: "2026-12-05", system: "devops" },
13987
+ crm: { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "usr_rv860m7z9h8szkgma56cd14n", ticket: 2179, expires: "2026-12-31", system: "devops" },
13987
13988
  "delivery-rules-v2": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "usr_t60d4g5z82rhbtbfrfxfbdxe", ticket: 2048, expires: "2026-11-28", system: "devops" },
13989
+ "end-users": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "usr_t60d4g5z82rhbtbfrfxfbdxe", ticket: 2312, expires: "2026-12-15", system: "devops" },
13988
13990
  "model-access-gate": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "usr_t60d4g5z82rhbtbfrfxfbdxe", ticket: 1933, expires: "2026-12-15", system: "devops" },
13989
13991
  "open-project": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "praxis-51", ticket: 1488, expires: "2026-11-25", system: "devops" },
13992
+ "requests-never-hold": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "usr_t60d4g5z82rhbtbfrfxfbdxe", ticket: 2119, expires: "2026-11-29", system: "devops" },
13990
13993
  "requests-v1": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "usr_t60d4g5z82rhbtbfrfxfbdxe", ticket: 2057, expires: "2026-11-28", system: "devops" },
13991
13994
  "router-precommit-hedge": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "usr_t60d4g5z82rhbtbfrfxfbdxe", ticket: 2052, expires: "2026-11-28", system: "devops" },
13995
+ "router-responses-hedge": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "usr_t60d4g5z82rhbtbfrfxfbdxe", ticket: 2149, expires: "2026-11-28", system: "devops" },
13992
13996
  "search-provider-routing": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "praxis-98", ticket: 716, expires: "2026-12-31", system: "devops" },
13993
13997
  "unit-live-probe": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "usr_t60d4g5z82rhbtbfrfxfbdxe", ticket: null, expires: "2026-11-19", system: "devops" }
13994
13998
  };
@@ -14015,7 +14019,7 @@ function checkFlags(files, registry, today = new Date().toISOString().slice(0, 1
14015
14019
  }
14016
14020
  const registryFile = production.find((f) => f.path.endsWith("flag-registry.generated.ts"));
14017
14021
  const registryLine = (key) => registryFile ? lineOf(registryFile.text, Math.max(0, registryFile.text.indexOf(`"${key}":`))) : 1;
14018
- const add = (file, offset, message) => issues.push({ file: file.path, line: lineOf(file.text, offset), message });
14022
+ const add = (file, offset, message2) => issues.push({ file: file.path, line: lineOf(file.text, offset), message: message2 });
14019
14023
  const referencedKeysIn = (file) => {
14020
14024
  for (const key of registered) {
14021
14025
  const literal = new RegExp(`(?:"|')${key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:"|')`);
@@ -14104,7 +14108,7 @@ async function main() {
14104
14108
  else
14105
14109
  console.log(`Feature flag registry check passed (${Object.keys(FLAGS).length} registered flags).`);
14106
14110
  }
14107
- var isTest = (path) => /(^|\/)(spec|__tests__)(\/|$)|\.(test|spec)\.[cm]?[jt]sx?$/.test(path), lineOf = (text2, offset) => text2.slice(0, offset).split(`
14111
+ var isTest = (path) => /(^|\/)(spec|__tests__)(\/|$)|\.(test|spec)\.[cm]?[jt]sx?$/.test(path), lineOf = (text3, offset) => text3.slice(0, offset).split(`
14108
14112
  `).length, isCalendarDate = (value) => /^\d{4}-\d{2}-\d{2}$/.test(value) && !Number.isNaN(new Date(`${value}T00:00:00.000Z`).valueOf()) && new Date(`${value}T00:00:00.000Z`).toISOString().slice(0, 10) === value;
14109
14113
  var init_check_flags = __esm(() => {
14110
14114
  init_flag_registry_generated();
@@ -14302,7 +14306,7 @@ async function checkRegistrySync(ports = {}) {
14302
14306
  }
14303
14307
  async function syncFlags(ports = {}) {
14304
14308
  const registry = ports.registry ?? registryUrl;
14305
- const write = ports.write ?? ((target, text2) => writeFile4(target, text2));
14309
+ const write = ports.write ?? ((target, text3) => writeFile4(target, text3));
14306
14310
  const log = ports.log ?? console.log;
14307
14311
  const error = ports.error ?? console.error;
14308
14312
  const devops = await (ports.devops ?? readDevopsFlags)();
@@ -14539,12 +14543,13 @@ async function runEngineDelegation(delegation, options) {
14539
14543
  }
14540
14544
 
14541
14545
  // src/main.ts
14542
- import { existsSync as existsSync4 } from "node:fs";
14546
+ import { existsSync as existsSync4, readFileSync as readFileSync3, unlinkSync } from "node:fs";
14543
14547
  import { mkdir as mkdir4, readFile as readFile7, readdir as readdir3, writeFile as writeFile5 } from "node:fs/promises";
14544
- import { resolve as resolve11 } from "node:path";
14548
+ import { dirname as dirname10, join as join12, resolve as resolve11 } from "node:path";
14549
+ import { homedir as homedir3 } from "node:os";
14545
14550
  import { pathToFileURL } from "node:url";
14546
14551
  import { createHash as createHash5 } from "node:crypto";
14547
- import { spawn as spawn4 } from "node:child_process";
14552
+ import { spawn as spawn5 } from "node:child_process";
14548
14553
  import { createInterface } from "node:readline";
14549
14554
 
14550
14555
  // ../../packages/sdk/typescript/src/operations.generated.ts
@@ -15599,8 +15604,8 @@ Idempotent. Access tokens revoked while the customer was blocked stay revoked; s
15599
15604
  {
15600
15605
  resource: "agent.agents.events",
15601
15606
  method: "stream",
15602
- summary: "Follow your conversation with an agent live",
15603
- description: "Follow your conversation with a personal or general agent live over Server-Sent Events: the stream of your own main session with that agent, the same stream sessions.events.stream opens, event_deltas[] previews included. {agent_id} takes the agent_… id, the eight character identity number or the handle; a service or assume agent answers 400. Closing the stream only drops your subscription and does not stop the agent; read past events with agents.events.list.",
15607
+ summary: "Follow an agent live",
15608
+ description: "Follow an agent live over Server-Sent Events. For a personal or general agent it is the stream of your own main session with that agent, the same stream sessions.events.stream opens, event_deltas[] previews included; read past events with agents.events.list. An assume agent has no main session: its body is its MCP connections, and this stream is its broadcast point, which every live connection of the agent hears at once. It carries two events, each with an SSE id: inbox.letter_delivered { letter_id, sender, sender_name, summary, thread, create_time } when a letter arrives (the letter stays unread; take it with the agent's inbox tool, the body is not in the event), and cognition.ritual_held { ritual, owner, title, engram, create_time } when a domain gives the agent a memory. Reconnect with the Last-Event-ID header to receive what you missed from a short recent buffer (about an hour); a first connection replays nothing, so read agents.inbox.letters.list for mail already waiting. {agent_id} takes the agent_… id, the eight character identity number or the handle; a service agent answers 400. Closing the stream only drops your subscription and does not stop the agent.",
15604
15609
  http: "GET",
15605
15610
  path: "/agent/v1/agents/{agent_id}/events/stream",
15606
15611
  streaming: "always",
@@ -15626,6 +15631,40 @@ Idempotent. Access tokens revoked while the customer was blocked stay revoked; s
15626
15631
  }
15627
15632
  ]
15628
15633
  },
15634
+ {
15635
+ resource: "agent.agents.inbox.letters",
15636
+ method: "list",
15637
+ summary: "List an assume agent's waiting letters",
15638
+ description: "Check whether mail waits for an assume agent without taking it: answers unread, the count of delivered letters the agent has not read, and letters, the newest unread ones (id, sender address, summary, thread, create_time; never the body). Nothing is marked read, so calling it again answers the same until the agent reads its mail with its own inbox tool (praxis_assume_inbox, action \"read\"). Use it when something outside the agent has to learn that mail arrived: the local `praxis agent events wait` reads it once on start and after every reconnect to its agent's event stream, so no letter that arrived while nothing listened is missed. {agent_id} takes the agent_… id, the eight character identity number or the handle of an assume agent in your organization; any other kind answers 400 ASSUME_AGENT_REQUIRED. To read or answer the letters, use the agent's inbox tool, not this read. Example: GET /agent/v1/agents/R1M9TQ2X/inbox/letters?unread=true&limit=5.",
15639
+ http: "GET",
15640
+ path: "/agent/v1/agents/{agent_id}/inbox/letters",
15641
+ streaming: "no",
15642
+ pagination: false,
15643
+ pathParams: [
15644
+ {
15645
+ name: "agent_id",
15646
+ sdkName: "agent_id",
15647
+ description: "The assume agent: its agent_… id, eight character identity number or handle, from agents.list or the praxis-assume MCP URL; resolved in your organization. Also accepts an 8-character identity number (0–9, A–Z); malformed, absent and foreign references return 404, and response ids always use agent_…."
15648
+ }
15649
+ ],
15650
+ query: [
15651
+ {
15652
+ name: "unread",
15653
+ type: "boolean",
15654
+ enum: [
15655
+ true
15656
+ ],
15657
+ required: false,
15658
+ description: "Only true is accepted, which is also the default; this read lists waiting (unread) letters and nothing else."
15659
+ },
15660
+ {
15661
+ name: "limit",
15662
+ type: "integer",
15663
+ required: false,
15664
+ description: "How many of the newest unread letters to return, 1 to 50 (default 20); unread always counts every waiting letter."
15665
+ }
15666
+ ]
15667
+ },
15629
15668
  {
15630
15669
  resource: "agent.agents.unarchive",
15631
15670
  method: "create",
@@ -16993,7 +17032,7 @@ delete it. Omit the field to preserve.`
16993
17032
  summary: "List Session Artifacts (Extension)",
16994
17033
  description: `List the files this session delivered; an end-customer token reads its own session.
16995
17034
 
16996
- Own-face extension. Returns { data: Artifact[] } ordered by create_time. Each artifact is one file in the session outputs directory with id, name, version, parts, source_hrefs, create_time and update_time. Delivering the same path again keeps the id and adds one to version. Files are captured seconds after the turn ends, so artifacts appear after session.status_idle; also watch the agent.artifact_delivered event. Whoever may read the session may read its artifacts; a session that is missing or not yours returns 404.`,
17035
+ Own-face extension. Returns { data: Artifact[] } ordered by create_time. Each artifact is one file in the session outputs directory, or one canvas or media asset the reply pointed at (a part with kind object carrying object_type, object_id and href; one artifact per object, pointing at it again adds no version), with id, name, version, parts, source_hrefs, create_time and update_time. Delivering the same path again keeps the id and adds one to version. Files are captured seconds after the turn ends, so artifacts appear after session.status_idle; also watch the agent.artifact_delivered event. Whoever may read the session may read its artifacts; a session that is missing or not yours returns 404.`,
16997
17036
  http: "GET",
16998
17037
  path: "/agent/v1/sessions/{session_id}/artifacts",
16999
17038
  streaming: "no",
@@ -17013,7 +17052,7 @@ Own-face extension. Returns { data: Artifact[] } ordered by create_time. Each ar
17013
17052
  summary: "Create Artifact Content URL (Extension)",
17014
17053
  description: `Mint a short-lived download address for one file of an artifact.
17015
17054
 
17016
- Own-face extension. The body is optional: part (index into the artifact parts, default 0) and ttl_seconds (60 to 300, default 300). Returns { url, expire_time }. The address works for minutes; do not store or log it. An unknown artifact or an out-of-range part returns 404 ARTIFACT_NOT_FOUND, a session that is missing or not yours returns 404, and a ttl_seconds outside 60 to 300 returns 400.`,
17055
+ Own-face extension. The body is optional: part (index into the artifact parts, default 0) and ttl_seconds (60 to 300, default 300). Returns { url, expire_time }. The address works for minutes; do not store or log it. For an object part the address serves a snapshot picture of a canvas or the own bytes of the asset; an object that no longer exists returns 404 ARTIFACT_NOT_FOUND and a failing share service returns 502. An unknown artifact or an out-of-range part returns 404 ARTIFACT_NOT_FOUND, a session that is missing or not yours returns 404, and a ttl_seconds outside 60 to 300 returns 400.`,
17017
17056
  http: "POST",
17018
17057
  path: "/agent/v1/sessions/{session_id}/artifacts/{artifact_id}/content_url",
17019
17058
  streaming: "no",
@@ -17232,7 +17271,7 @@ Praxis extension available only on /agent/v1, following Claude Agent SDK getCont
17232
17271
  resource: "agent.sessions.events",
17233
17272
  method: "list",
17234
17273
  summary: "List session events",
17235
- description: "Read the event history of a session as a page of events, oldest first by default (order=desc for newest first). Use it after sending a message to collect the reply, to find tool calls that wait for approval or client custom tool results (session.status_idle with stop_reason requires_action lists their event_ids; a request nobody answered within 24 hours is settled as unanswered and the session goes idle with stop_reason request_expired, which the /anthropic/v1 face shows as end_turn), or to audit a run; to follow a running session live use sessions.events.stream instead. Filter by types and by a created_at range on processed_at; pages hold at most 100 events (default 20) and next_page continues. A failed run emits session.error before session.status_terminated. Native history also includes user.steer, user.withdraw, system.notification, session.forked, session.goal_changed and session.goal_verification; these are not accepted by the /anthropic/v1 event-type filter. This operation addresses one session — normally a worker session an agent dispatched; to talk to a personal or general agent itself, use agents.events.list instead. In the path, session_id may also be `main` (your own main session with that agent) or a short session name, and either alias then requires agent_id with the agent_… id, the eight character identity number or the handle; only the own face /agent/v1 accepts an alias, /anthropic/v1 requires a real sesn_… id.",
17274
+ description: "Read the event history of a session as a page of events, oldest first by default (order=desc for newest first). Use it after sending a message to collect the reply, to find tool calls that wait for approval or client custom tool results (session.status_idle with stop_reason requires_action lists their event_ids; a request nobody answered within 24 hours is settled as unanswered and the session goes idle with stop_reason request_expired, which the /anthropic/v1 face shows as end_turn), or to audit a run; to follow a running session live use sessions.events.stream instead. Filter by types and by a created_at range on processed_at; pages hold at most 100 events (default 20) and next_page continues. A failed run emits session.error before session.status_terminated. Native history also includes user.steer, user.withdraw, system.notification, system.notification_suppressed (pending background notifications that hit the wake quota and started no run), system.notification_recorded, session.forked, session.goal_changed and session.goal_verification; these are not accepted by the /anthropic/v1 event-type filter. This operation addresses one session — normally a worker session an agent dispatched; to talk to a personal or general agent itself, use agents.events.list instead. In the path, session_id may also be `main` (your own main session with that agent) or a short session name, and either alias then requires agent_id with the agent_… id, the eight character identity number or the handle; only the own face /agent/v1 accepts an alias, /anthropic/v1 requires a real sesn_… id.",
17236
17275
  http: "GET",
17237
17276
  path: "/agent/v1/sessions/{session_id}/events",
17238
17277
  streaming: "no",
@@ -17391,6 +17430,26 @@ Available only on /agent/v1. Use the message_id field from own-face events, not
17391
17430
  ]
17392
17431
  }
17393
17432
  },
17433
+ {
17434
+ resource: "agent.sessions.requests",
17435
+ method: "list",
17436
+ summary: "List Session Requests (Extension)",
17437
+ description: `List the requests a session is waiting on; an end-customer token reads its own session.
17438
+
17439
+ Own-face extension. When a session stops at session.status_idle with stop_reason requires_action, read what it waits on here instead of replaying events. Returns { data: Request[] } ordered by create_time, an empty array when nothing is pending, not paginated. Each request has id (the pending tool call id), object (request), kind (question for the ask_user_question tool, approval for any other tool that waits for permission), status (pending), tool_name, input (the same input the agent.tool_use event shows), create_time and expire_time. Answer a request as before: send a user.tool_confirmation event for its id. expire_time is set only for a session with no collaboration mode while the requests-v1 release is on (create_time plus 24 hours; an expired request counts as declined), otherwise null. Answered, expired and superseded requests are not listed, and neither are pending custom tool results (user.custom_tool_result). Whoever may read the session may read its requests; a session that is missing or not yours returns 404.`,
17440
+ http: "GET",
17441
+ path: "/agent/v1/sessions/{session_id}/requests",
17442
+ streaming: "no",
17443
+ pagination: false,
17444
+ pathParams: [
17445
+ {
17446
+ name: "session_id",
17447
+ sdkName: "session_id",
17448
+ description: "Session id from session creation or listing."
17449
+ }
17450
+ ],
17451
+ query: []
17452
+ },
17394
17453
  {
17395
17454
  resource: "agent.sessions.resources",
17396
17455
  method: "list",
@@ -29914,7 +29973,7 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
29914
29973
  resource: "devops.units",
29915
29974
  method: "push",
29916
29975
  summary: "Push a unit's branch",
29917
- description: "Publish the unit's local commits to the remote for the change: the machine itself holds no git credential and cannot reach the remote, so this verb is the way work done on a unit lands. ref says what to push — branch for the change's own branch, wip for this unit's own refs/praxis/wip/<change>, or a full ref name; anything else (the default branch, another change's branch, a tag, another unit's wip ref) is refused with 400 PUSH_REF_FORBIDDEN and nothing is pushed. expectedHead is the commit you believe the remote branch is at now; DevOps checks it before signing anything, and a remote that has moved since answers 409 HEAD_MOVED with nothing pushed, so fetch first when unsure, reconcile, and send the new head. For branch the call also takes a lease on that head, so the push cannot silently overwrite work that landed in between; wip is this change's own ref and is force-pushed. On success the answer is pushedSha, the commit that landed. Commit inside the machine first, through the sandbox instance API — this verb pushes commits, it does not create them. The unit must be available with a machine and a checkout, or the call answers 409 UNIT_INVALID_STATE; a push that fails inside the machine answers 500 EXECUTION_FAILED and the machine's own words are in the unit's transitions.",
29976
+ description: "Publish the unit's local commits to the remote for the change: the machine itself holds no git credential and cannot reach the remote, so this verb is the way work done on a unit lands. ref says what to push — branch for the change's own branch, wip for this unit's own refs/praxis/wip/<change>, or a full ref name; anything else (the default branch, another change's branch, a tag, another unit's wip ref) is refused with 400 PUSH_REF_FORBIDDEN and nothing is pushed. expectedHead is the commit you believe the remote branch is at now; DevOps checks it before signing anything, and a remote that has moved since answers 409 HEAD_MOVED with nothing pushed, so fetch first when unsure, reconcile, and send the new head. For branch the call also takes a lease on that head, so the push cannot silently overwrite work that landed in between; wip is this change's own ref and is force-pushed. On success the answer is pushedSha, the commit that landed. Commit inside the machine first, through the sandbox instance API — this verb pushes commits, it does not create them. The unit must be available with a machine and a checkout, or the call answers 409 UNIT_INVALID_STATE; a push that git refuses inside the machine answers with the cause in the error message and in details.detail (the last 4000 characters of git's output, credentials redacted) and details.exitCode (git's exit code): 409 PUSH_REJECTED_BY_HOOK when a pre-push hook such as lefthook rejected it, so read the hook output, fix the content and push again, 409 PUSH_REJECTED_NON_FAST_FORWARD when the remote moved ahead, so fetch and reconcile, 409 HEAD_MOVED when the lease on expectedHead no longer holds, and 500 PUSH_FAILED for anything else. Do not retry the same push unchanged.",
29918
29977
  http: "POST",
29919
29978
  path: "/devops/v1/units/{id}:push",
29920
29979
  streaming: "no",
@@ -34928,6 +34987,7 @@ for more details.`
34928
34987
  "openai.images.generations",
34929
34988
  "openai.responses",
34930
34989
  "openai.videos",
34990
+ "praxis.media.process",
34931
34991
  "praxis.video.matting",
34932
34992
  "typesafe.systemone",
34933
34993
  "volcengine.music",
@@ -40603,6 +40663,131 @@ for more details.`
40603
40663
  ]
40604
40664
  }
40605
40665
  },
40666
+ {
40667
+ resource: "share.permissions",
40668
+ method: "list",
40669
+ summary: "List shares",
40670
+ description: "Find the shares of this organization, newest first, for example every link that exposes one file before you decide which to revoke. Filter by resource_type, resource_id and status; filters combine with AND. Continue with next_page_token as page_token until next_page_token is null. Records never include link.web_url. A credential bound to specific files must pass resource_type and resource_id of a bound file, and an unbound file answers 404.",
40671
+ http: "GET",
40672
+ path: "/share/v1/permissions",
40673
+ streaming: "no",
40674
+ pagination: false,
40675
+ pathParams: [],
40676
+ query: [
40677
+ {
40678
+ name: "resource_type",
40679
+ type: "string",
40680
+ enum: [
40681
+ "file",
40682
+ "artifact",
40683
+ "canvas",
40684
+ "media_asset"
40685
+ ],
40686
+ required: false,
40687
+ description: "Only shares of this object type; file, canvas and media_asset create today."
40688
+ },
40689
+ {
40690
+ name: "resource_id",
40691
+ type: "string",
40692
+ required: false,
40693
+ description: "Only shares of the object with this id, for example a file id from the File API or a media asset's library_id/asset_id; combine with resource_type."
40694
+ },
40695
+ {
40696
+ name: "status",
40697
+ type: "string",
40698
+ enum: [
40699
+ "active",
40700
+ "expired",
40701
+ "revoked"
40702
+ ],
40703
+ required: false,
40704
+ description: "Only shares in this state; omit to list every state."
40705
+ },
40706
+ {
40707
+ name: "page_size",
40708
+ type: "integer",
40709
+ required: false,
40710
+ description: "Maximum shares in one page, from 1 to 100; defaults to 50."
40711
+ },
40712
+ {
40713
+ name: "page_token",
40714
+ type: "string",
40715
+ required: false,
40716
+ description: "Opaque next_page_token from the preceding page with the same filters; omit on the first request."
40717
+ }
40718
+ ]
40719
+ },
40720
+ {
40721
+ resource: "share.permissions",
40722
+ method: "create",
40723
+ summary: "Create share",
40724
+ description: "Make one file readable by anyone holding a link, before sending the link to a person or embedding it. Name the object as resource {type, id}, with the file id from the File API. The response is 201 and is the only time link.web_url is returned; store it, because later reads omit it and a lost address means creating another share (the old one keeps working until you delete it). The link is anonymous and read-only. A type other than file answers 400 RESOURCE_TYPE_UNSUPPORTED, and a file that is missing or outside your organization answers 404 RESOURCE_NOT_FOUND.",
40725
+ http: "POST",
40726
+ path: "/share/v1/permissions",
40727
+ streaming: "no",
40728
+ pagination: false,
40729
+ pathParams: [],
40730
+ query: [],
40731
+ body: {
40732
+ required: true,
40733
+ fields: [
40734
+ {
40735
+ name: "resource",
40736
+ type: "object",
40737
+ required: true,
40738
+ description: "The object a share exposes, named by a type and an id."
40739
+ },
40740
+ {
40741
+ name: "expire_time",
40742
+ type: "string",
40743
+ required: false,
40744
+ description: "ISO 8601 instant after which the link answers 410; omit or null for a link that never expires, and it must be in the future."
40745
+ },
40746
+ {
40747
+ name: "prevents_download",
40748
+ type: "boolean",
40749
+ required: false,
40750
+ description: "Ask viewers to open the content without a download prompt; a limit, not a guarantee, because anyone who can read it can save it. Defaults to false."
40751
+ }
40752
+ ]
40753
+ }
40754
+ },
40755
+ {
40756
+ resource: "share.permissions",
40757
+ method: "delete",
40758
+ summary: "Delete share",
40759
+ description: "Take a link back so nobody can open it again. This revokes the share, the record stays readable with status revoked, and opening the link answers 410. Repeating the call on a revoked share is harmless and answers 204 again. Content addresses already signed when the link was opened expire on their own within five minutes. Take the id from shares.create or shares.list.",
40760
+ http: "DELETE",
40761
+ path: "/share/v1/permissions/{id}",
40762
+ streaming: "no",
40763
+ pagination: false,
40764
+ pathParams: [
40765
+ {
40766
+ name: "id",
40767
+ sdkName: "id",
40768
+ description: "Share id returned by shares.create or shares.list, in the form shr_ followed by 32 lowercase letters or digits; a link address is not accepted."
40769
+ }
40770
+ ],
40771
+ query: []
40772
+ },
40773
+ {
40774
+ resource: "share.permissions",
40775
+ method: "retrieve",
40776
+ summary: "Retrieve share",
40777
+ description: "Read one share to see whether its link is still active, when it expires, and how many times it was opened. Take the id from shares.create or shares.list. The record never includes link.web_url, because the address is shown once at creation. A share that does not exist or belongs to another organization answers 404 PERMISSION_NOT_FOUND.",
40778
+ http: "GET",
40779
+ path: "/share/v1/permissions/{id}",
40780
+ streaming: "no",
40781
+ pagination: false,
40782
+ pathParams: [
40783
+ {
40784
+ name: "id",
40785
+ sdkName: "id",
40786
+ description: "Share id returned by shares.create or shares.list, in the form shr_ followed by 32 lowercase letters or digits; a link address is not accepted."
40787
+ }
40788
+ ],
40789
+ query: []
40790
+ },
40606
40791
  {
40607
40792
  resource: "studio.codexes",
40608
40793
  method: "list",
@@ -47077,6 +47262,19 @@ var getAgentConsolidation = (options) => (options.client ?? client).get({
47077
47262
  url: "/agent/v1/agents/{agent_id}/consolidations/{consolidation_id}",
47078
47263
  ...options
47079
47264
  });
47265
+ var listAgentInboxLetters = (options) => (options.client ?? client).get({
47266
+ security: [{
47267
+ key: "BearerAuth",
47268
+ scheme: "bearer",
47269
+ type: "http"
47270
+ }, {
47271
+ key: "ApiKeyAuth",
47272
+ name: "X-API-Key",
47273
+ type: "apiKey"
47274
+ }],
47275
+ url: "/agent/v1/agents/{agent_id}/inbox/letters",
47276
+ ...options
47277
+ });
47080
47278
  var applyAgentVersion = (options) => (options.client ?? client).post({
47081
47279
  security: [{
47082
47280
  key: "BearerAuth",
@@ -47547,6 +47745,19 @@ var createSessionArtifactContentUrl = (options) => (options.client ?? client).po
47547
47745
  ...options.headers
47548
47746
  }
47549
47747
  });
47748
+ var listSessionRequests = (options) => (options.client ?? client).get({
47749
+ security: [{
47750
+ key: "BearerAuth",
47751
+ scheme: "bearer",
47752
+ type: "http"
47753
+ }, {
47754
+ key: "ApiKeyAuth",
47755
+ name: "X-API-Key",
47756
+ type: "apiKey"
47757
+ }],
47758
+ url: "/agent/v1/sessions/{session_id}/requests",
47759
+ ...options
47760
+ });
47550
47761
  var listSessionBackgroundTasks = (options) => (options.client ?? client).get({
47551
47762
  security: [{
47552
47763
  key: "BearerAuth",
@@ -55802,6 +56013,46 @@ var searchMap = (options) => (options.client ?? client).post({
55802
56013
  ...options.headers
55803
56014
  }
55804
56015
  });
56016
+ var shareListPermissions = (options) => (options?.client ?? client).get({
56017
+ security: [{
56018
+ key: "share-bearerAuth",
56019
+ scheme: "bearer",
56020
+ type: "http"
56021
+ }],
56022
+ url: "/share/v1/permissions",
56023
+ ...options
56024
+ });
56025
+ var shareCreatePermission = (options) => (options.client ?? client).post({
56026
+ security: [{
56027
+ key: "share-bearerAuth",
56028
+ scheme: "bearer",
56029
+ type: "http"
56030
+ }],
56031
+ url: "/share/v1/permissions",
56032
+ ...options,
56033
+ headers: {
56034
+ "Content-Type": "application/json",
56035
+ ...options.headers
56036
+ }
56037
+ });
56038
+ var shareDeletePermission = (options) => (options.client ?? client).delete({
56039
+ security: [{
56040
+ key: "share-bearerAuth",
56041
+ scheme: "bearer",
56042
+ type: "http"
56043
+ }],
56044
+ url: "/share/v1/permissions/{id}",
56045
+ ...options
56046
+ });
56047
+ var shareRetrievePermission = (options) => (options.client ?? client).get({
56048
+ security: [{
56049
+ key: "share-bearerAuth",
56050
+ scheme: "bearer",
56051
+ type: "http"
56052
+ }],
56053
+ url: "/share/v1/permissions/{id}",
56054
+ ...options
56055
+ });
55805
56056
  var studioGenresList = (options) => (options?.client ?? client).get({
55806
56057
  security: [{
55807
56058
  key: "BearerAuth",
@@ -57838,6 +58089,11 @@ function createAgent(transport) {
57838
58089
  send: bind(transport, sendAgentEvents),
57839
58090
  stream: bindStream(transport, streamAgentEvents)
57840
58091
  },
58092
+ inbox: {
58093
+ letters: {
58094
+ list: bind(transport, listAgentInboxLetters)
58095
+ }
58096
+ },
57841
58097
  list: bind(transport, agentsList),
57842
58098
  retrieve: bind(transport, agentsRetrieve),
57843
58099
  retrieveAppearance: bind(transport, getAgentAppearance),
@@ -57926,6 +58182,9 @@ function createAgent(transport) {
57926
58182
  },
57927
58183
  fork: bind(transport, forkSession),
57928
58184
  list: bind(transport, sessionsList),
58185
+ requests: {
58186
+ list: bind(transport, listSessionRequests)
58187
+ },
57929
58188
  resources: {
57930
58189
  create: bind(transport, sessionsResourcesAdd),
57931
58190
  delete: bind(transport, aliasOperation(sessionsResourcesDelete, { query: { session_id: "query_session_id" } })),
@@ -59087,6 +59346,16 @@ function createSearch(transport) {
59087
59346
  }
59088
59347
  };
59089
59348
  }
59349
+ function createShare(transport) {
59350
+ return {
59351
+ permissions: {
59352
+ create: bind(transport, shareCreatePermission),
59353
+ delete: bind(transport, shareDeletePermission),
59354
+ list: bind(transport, shareListPermissions),
59355
+ retrieve: bind(transport, shareRetrievePermission)
59356
+ }
59357
+ };
59358
+ }
59090
59359
  function createStudio(transport) {
59091
59360
  return {
59092
59361
  codexes: {
@@ -59357,6 +59626,7 @@ var resourceFactories = {
59357
59626
  organization: createOrganization,
59358
59627
  sandbox: createSandbox,
59359
59628
  search: createSearch,
59629
+ share: createShare,
59360
59630
  studio: createStudio,
59361
59631
  ticket: createTicket,
59362
59632
  vault: createVault
@@ -61174,7 +61444,7 @@ function help(commands, prefix, command) {
61174
61444
  ...[...operationOptions(command.op), ...bodyDataOption(command.op), ...globalOptions].map((s) => ` ${describeOption(s, s.required && fieldRequired(command.op, s, s.location ?? "query"))}`),
61175
61445
  ...command.op.body?.fields.filter((f) => !operationOptions(command.op).some((s) => s.location === "body" && s.field === f) && (f.type === "object" || f.type === "array" && !["string", "number", "integer", "boolean"].includes(f.itemType ?? ""))).map((f) => ` --data: ${f.name} (${f.type}${f.required ? ", required" : ""})`) ?? [],
61176
61446
  " -h is an alias of --help",
61177
- "PRAXIS_ENV=develop|production (default: develop); no --env option.",
61447
+ "PRAXIS_ENV=production|develop (default: production; develop must be named); no --env option.",
61178
61448
  "",
61179
61449
  "Examples:",
61180
61450
  ` ${example(command)}`
@@ -61186,7 +61456,7 @@ function help(commands, prefix, command) {
61186
61456
  "Global options:",
61187
61457
  ...globalOptions.map((s) => ` ${describeOption(s)}`),
61188
61458
  " -h is an alias of --help",
61189
- "PRAXIS_ENV=develop|production (default: develop); no --env option.",
61459
+ "PRAXIS_ENV=production|develop (default: production; develop must be named); no --env option.",
61190
61460
  ""
61191
61461
  ];
61192
61462
  const sample = matching.find((c) => c.words.at(-1) === "list") ?? matching[0];
@@ -61674,6 +61944,41 @@ var workflows = [
61674
61944
  platform: "praxis api devops project change create — the platform creates and names a Change; the CLI only lands its branch (ADR-125 §5).",
61675
61945
  docs: "https://docs.deepraxis.com/docs/cli"
61676
61946
  },
61947
+ {
61948
+ words: ["agent", "events", "wait"],
61949
+ usage: "agent events wait [--timeout <seconds>]",
61950
+ summary: "Wait until a new letter arrives for your assume agent (PRAXIS_ASSUME_AGENT, default R1M9TQ2X), print who wrote and how to read it, and exit 0. It first checks the waiting letters once, so mail that arrived while nothing waited is reported at once; then it follows the agent's event stream, reconnecting with backoff. Nothing is marked read. Run it as a background task in Claude Code: its exit wakes the idle session; read the mail with praxis_assume_inbox and start it again.",
61951
+ example: "PRAXIS_ASSUME_AGENT=R1M9TQ2X praxis agent events wait",
61952
+ network: "online"
61953
+ },
61954
+ {
61955
+ words: ["agent", "memory"],
61956
+ usage: "agent memory [--hook SessionStart|UserPromptSubmit]",
61957
+ summary: "Print your assume agent's memory as it stands now (PRAXIS_ASSUME_AGENT): who it is, its post, manager, duties and the charters it works under, drawn from its organization. With --hook it reads the Claude Code hook input on stdin and prints the hook's JSON: the whole memory at SessionStart, only what is new since that session last read it at UserPromptSubmit; it never fails the hook.",
61958
+ example: "praxis agent memory",
61959
+ network: "online"
61960
+ },
61961
+ {
61962
+ words: ["agent", "recall"],
61963
+ usage: "agent recall [--words <w,w>] [--handles <id,id>]",
61964
+ summary: "Recall from your assume agent's memory: with no flags, what else comes to mind; with words, what was filed under them; with handles, that entry and its original.",
61965
+ example: "praxis agent recall --words 章程,运维部",
61966
+ network: "online"
61967
+ },
61968
+ {
61969
+ words: ["agent", "remember"],
61970
+ usage: "agent remember --text <experience> [--about <id,id>]",
61971
+ summary: "Keep an experience in your assume agent's memory: it is consolidated in the background like a lived conversation, and recall finds it afterwards.",
61972
+ example: 'praxis agent remember --text "Sean 定了副总裁用钩子载入认知"',
61973
+ network: "online"
61974
+ },
61975
+ {
61976
+ words: ["agent", "events", "channel"],
61977
+ usage: "agent events channel",
61978
+ summary: "Run as a Claude Code channel (a stdio MCP server declaring claude/channel, no tools): pushes the waiting letters once, then every new letter and new memory of your assume agent (PRAXIS_ASSUME_AGENT, default R1M9TQ2X) into the running session. Started by the assume-agent plugin, not by hand; stdout carries MCP frames only, logs go to stderr.",
61979
+ example: "claude --dangerously-load-development-channels plugin:assume-agent@deepraxis",
61980
+ network: "online"
61981
+ },
61677
61982
  { words: ["canvas", "import"], usage: "canvas import <file.pen> [--name <name>] [--canvas <cvs_…> --yes] [--frames <id,id>] [--image-root <dir>] [--dry-run]", summary: "Import a Pencil .pen file as a canvas, uploading the images it references first.", example: 'praxis canvas import design.pen --name "Landing page"' },
61678
61983
  { words: ["skill"], usage: "skill [--install <dir>]", summary: "Print the AI skill, or write <dir>/praxis-cli/SKILL.md." },
61679
61984
  {
@@ -61743,7 +62048,7 @@ function workflowHelp(workflow, options) {
61743
62048
  "Options:",
61744
62049
  ...[...options, ...globalOptions].map((s) => ` ${describeOption(s)}`),
61745
62050
  " -h is an alias of --help",
61746
- "PRAXIS_ENV=develop|production (default: develop); no --env option.",
62051
+ "PRAXIS_ENV=production|develop (default: production; develop must be named); no --env option.",
61747
62052
  ...workflow.requires === "checkout" ? [`Requires: ${CHECKOUT_REQUIREMENT}`] : [],
61748
62053
  ...workflow.notes?.length ? ["", ...workflow.notes] : [],
61749
62054
  ...workflow.network ? ["", `Network: ${workflow.network}`] : [],
@@ -65760,6 +66065,30 @@ function bunTestRun(packagePath, code, output) {
65760
66065
  }
65761
66066
 
65762
66067
  // src/commands/devops-test.ts
66068
+ import { spawn as spawn4 } from "node:child_process";
66069
+ var CACHE_OFF_REEXEC_ENV = "PRAXIS_DEVOPS_TEST_CACHE_OFF";
66070
+ function needsCacheOffReexec(env) {
66071
+ return env.BUN_RUNTIME_TRANSPILER_CACHE_PATH !== "0" && !env[CACHE_OFF_REEXEC_ENV];
66072
+ }
66073
+ function isDevopsTestRun(words) {
66074
+ return words.join(" ") === "devops test";
66075
+ }
66076
+ function spawnInherit(cmd, args, options) {
66077
+ return new Promise((resolveCode) => {
66078
+ const child = spawn4(cmd, [...args], { cwd: options.cwd, env: options.env, stdio: "inherit" });
66079
+ child.once("error", (error) => {
66080
+ console.error(error instanceof Error ? error.message : String(error));
66081
+ resolveCode(1);
66082
+ });
66083
+ child.once("close", (code) => resolveCode(code ?? 1));
66084
+ });
66085
+ }
66086
+ function reexecWithCacheOff(options = {}) {
66087
+ return (options.spawn ?? spawnInherit)(process.execPath, options.argv ?? process.argv.slice(1), {
66088
+ cwd: options.cwd ?? process.cwd(),
66089
+ env: { ...options.env ?? process.env, BUN_RUNTIME_TRANSPILER_CACHE_PATH: "0", [CACHE_OFF_REEXEC_ENV]: "1" }
66090
+ });
66091
+ }
65763
66092
  async function devopsTest(flags, paths, ports) {
65764
66093
  const plan = planTest(flags, paths);
65765
66094
  if (plan.mode.kind === "affected")
@@ -66030,8 +66359,8 @@ async function localEngine(cwd) {
66030
66359
  })
66031
66360
  };
66032
66361
  }
66033
- async function localCheckout(cwd, spawn4) {
66034
- const git2 = (args) => spawn4("git", [...args], { cwd });
66362
+ async function localCheckout(cwd, spawn5) {
66363
+ const git2 = (args) => spawn5("git", [...args], { cwd });
66035
66364
  const required = async (args) => {
66036
66365
  const result = await git2(args);
66037
66366
  if (result.code !== 0)
@@ -66082,7 +66411,7 @@ async function localCheckout(cwd, spawn4) {
66082
66411
  await walk(packagePath);
66083
66412
  return files;
66084
66413
  },
66085
- runTests: (packagePath, files) => spawn4("nice", ["-n", "10", "bun", "test", ...files], { cwd: packagePath })
66414
+ runTests: (packagePath, files) => spawn5("nice", ["-n", "10", "bun", "test", ...files], { cwd: packagePath })
66086
66415
  };
66087
66416
  }
66088
66417
  async function withEngineStdoutOnStderr(body) {
@@ -69040,6 +69369,7 @@ var FILE_ID = /^file-/;
69040
69369
  var asRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
69041
69370
  var isImage = (node2) => node2.type === "image" && typeof node2.url === "string";
69042
69371
  var isRef = (node2) => node2.type === "ref" && typeof node2.ref === "string";
69372
+ var NODE_TYPES = new Set(Object.keys(KNOWN_PROPS));
69043
69373
  function visit2(value, nodeId, fn) {
69044
69374
  if (Array.isArray(value)) {
69045
69375
  for (const item of value)
@@ -69233,6 +69563,8 @@ var warningLine = (warning) => {
69233
69563
  return `${warning.code}: ${warning.ref} at ${warning.nodeId}`;
69234
69564
  case "FRAME_NOT_FOUND":
69235
69565
  return `${warning.code}: ${warning.id}`;
69566
+ case "IMAGE_FILE_NOT_FOUND":
69567
+ return `${warning.code}: ${warning.url} (the platform holds no such file) at ${warning.nodeId}`;
69236
69568
  default:
69237
69569
  return `${warning.code}: ${warning.url}`;
69238
69570
  }
@@ -69340,6 +69672,530 @@ async function canvasImport(args, ports) {
69340
69672
  return 0;
69341
69673
  }
69342
69674
 
69675
+ // src/commands/events-wait.ts
69676
+ var DEFAULT_AGENT = "R1M9TQ2X";
69677
+ var BASE_BACKOFF_MS = 1000;
69678
+ var MAX_BACKOFF_MS = 60000;
69679
+ var NOTICE_NAMED = 5;
69680
+ var ANNOUNCED_KEEP = 500;
69681
+ function assumeAgentOf(env) {
69682
+ return env.PRAXIS_ASSUME_AGENT?.trim() || DEFAULT_AGENT;
69683
+ }
69684
+ function sessionOf(raw) {
69685
+ if (raw === undefined)
69686
+ return null;
69687
+ const session = raw.trim();
69688
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(session))
69689
+ throw new Error("--session takes the Claude Code session id (letters, digits, - and _)");
69690
+ return session;
69691
+ }
69692
+ var keyPart = (part) => part.replace(/[^A-Za-z0-9_-]/g, "_");
69693
+ function waitKeyOf(env, agent, session) {
69694
+ return [env, agent, ...session === null ? [] : [session]].map(keyPart).join("-");
69695
+ }
69696
+ function pidOf(raw) {
69697
+ const pid = raw === null ? NaN : Number(raw.trim());
69698
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
69699
+ }
69700
+ function lockDecision(recorded, self, probe) {
69701
+ if (recorded === null || recorded === self || probe === null || !probe.alive)
69702
+ return { kind: "take" };
69703
+ if (!/events\s+wait/.test(probe.command))
69704
+ return { kind: "take" };
69705
+ if (probe.ppid === 1)
69706
+ return { kind: "replace", pid: recorded };
69707
+ return { kind: "refuse", pid: recorded };
69708
+ }
69709
+ function alreadyWaitingNotice(pid) {
69710
+ return `本会话已有 praxis agent events wait 在后台等待(pid ${pid}),不用再启动。`;
69711
+ }
69712
+ async function acquireWaitLock(ports) {
69713
+ for (let attempt = 0;attempt < 3; attempt++) {
69714
+ const recorded = pidOf(await ports.readPid());
69715
+ if (recorded === null) {
69716
+ if (await ports.createPid(String(ports.self)))
69717
+ return null;
69718
+ continue;
69719
+ }
69720
+ const decision = lockDecision(recorded, ports.self, await ports.probe(recorded));
69721
+ if (decision.kind === "refuse")
69722
+ return decision.pid;
69723
+ if (decision.kind === "replace")
69724
+ ports.terminate(decision.pid);
69725
+ await ports.replacePid(String(ports.self));
69726
+ const holder = pidOf(await ports.readPid());
69727
+ return holder === ports.self || holder === null ? null : holder;
69728
+ }
69729
+ return pidOf(await ports.readPid());
69730
+ }
69731
+ function timeoutMsOf(raw) {
69732
+ if (raw === undefined)
69733
+ return null;
69734
+ const seconds = Number(raw);
69735
+ if (!/^\d+(\.\d+)?$/.test(raw.trim()) || !Number.isFinite(seconds) || seconds <= 0)
69736
+ throw new Error("--timeout takes a positive number of seconds");
69737
+ return Math.round(seconds * 1000);
69738
+ }
69739
+ function backoffMs(failures) {
69740
+ if (failures <= 0)
69741
+ return 0;
69742
+ return Math.min(MAX_BACKOFF_MS, BASE_BACKOFF_MS * 2 ** Math.min(failures - 1, 16));
69743
+ }
69744
+ function inboxLettersUrl(apiUrl, agent) {
69745
+ return `${apiUrl}/agent/v1/agents/${encodeURIComponent(agent)}/inbox/letters?unread=true&limit=20`;
69746
+ }
69747
+ function eventsStreamUrl(apiUrl, agent) {
69748
+ return `${apiUrl}/agent/v1/agents/${encodeURIComponent(agent)}/events/stream`;
69749
+ }
69750
+ function streamHeaders(auth, lastEventId) {
69751
+ return { ...auth, Accept: "text/event-stream", ...lastEventId === null ? {} : { "Last-Event-ID": lastEventId } };
69752
+ }
69753
+ function lettersOf(body) {
69754
+ const value = body;
69755
+ if (!value || typeof value.unread !== "number" || !Array.isArray(value.letters))
69756
+ throw new Error("letters answer is not { unread, letters }");
69757
+ const letters = value.letters.filter((letter) => typeof letter === "object" && letter !== null && typeof letter.id === "string" && typeof letter.summary === "string");
69758
+ return { unread: value.unread, letters };
69759
+ }
69760
+ function feedSse(buffer, chunk) {
69761
+ const text2 = (buffer + chunk).replace(/\r\n?/g, `
69762
+ `);
69763
+ const blocks = text2.split(`
69764
+
69765
+ `);
69766
+ const rest = blocks.pop() ?? "";
69767
+ const frames = [];
69768
+ for (const block of blocks) {
69769
+ let event, id;
69770
+ const data = [];
69771
+ for (const line of block.split(`
69772
+ `)) {
69773
+ if (line === "" || line.startsWith(":"))
69774
+ continue;
69775
+ const colon = line.indexOf(":");
69776
+ const field = colon < 0 ? line : line.slice(0, colon);
69777
+ const value = colon < 0 ? "" : line.slice(colon + 1).replace(/^ /, "");
69778
+ if (field === "data")
69779
+ data.push(value);
69780
+ else if (field === "event")
69781
+ event = value;
69782
+ else if (field === "id")
69783
+ id = value;
69784
+ }
69785
+ if (data.length)
69786
+ frames.push({ ...event === undefined ? {} : { event }, ...id === undefined ? {} : { id }, data: data.join(`
69787
+ `) });
69788
+ }
69789
+ return { buffer: rest, frames };
69790
+ }
69791
+ var text2 = (value) => typeof value === "string" && value !== "";
69792
+ function wakeOf(frame) {
69793
+ let event;
69794
+ try {
69795
+ event = JSON.parse(frame.data);
69796
+ } catch {
69797
+ return null;
69798
+ }
69799
+ if (typeof event !== "object" || event === null)
69800
+ return null;
69801
+ if (event.type === "inbox.letter_delivered" && text2(event.letter_id) && typeof event.summary === "string")
69802
+ return { kind: "letter", letter: {
69803
+ id: event.letter_id,
69804
+ sender: typeof event.sender === "string" ? event.sender : "",
69805
+ ...text2(event.sender_name) ? { sender_name: event.sender_name } : {},
69806
+ summary: event.summary,
69807
+ thread: typeof event.thread === "string" ? event.thread : null,
69808
+ create_time: typeof event.create_time === "string" ? event.create_time : ""
69809
+ } };
69810
+ if (event.type === "cognition.ritual_held" && text2(event.title))
69811
+ return { kind: "ritual", ritual: {
69812
+ ritual: text2(event.ritual) ? event.ritual : "",
69813
+ owner: text2(event.owner) ? event.owner : "",
69814
+ title: event.title,
69815
+ engram: text2(event.engram) ? event.engram : ""
69816
+ } };
69817
+ return null;
69818
+ }
69819
+ function ritualNotice(ritual) {
69820
+ const origin = [ritual.owner, ritual.ritual].filter(Boolean).join(" 的仪式 ");
69821
+ return `你获得了一段新记忆:「${ritual.title}」${origin ? `(${origin}${ritual.engram ? `,${ritual.engram}` : ""})` : ""}。处理完再在后台运行 praxis agent events wait。`;
69822
+ }
69823
+ function retryableStatus(status) {
69824
+ return status >= 500 || status === 408 || status === 429;
69825
+ }
69826
+ function planNotice(page, announced) {
69827
+ const seen = new Set(announced);
69828
+ const fresh = page.letters.filter((letter) => !seen.has(letter.id));
69829
+ if (!fresh.length)
69830
+ return { announced };
69831
+ const named = fresh.slice(0, NOTICE_NAMED).map((letter) => `${letter.sender_name || letter.sender}:${letter.summary}(${letter.id})`);
69832
+ const more = fresh.length > NOTICE_NAMED ? `;另有 ${fresh.length - NOTICE_NAMED} 封` : "";
69833
+ const notice = `你有 ${fresh.length} 封新信:${named.join(";")}${more}。用 praxis_assume_inbox(action "read")读取并处理,处理完再在后台运行 praxis agent events wait。`;
69834
+ const next = [...announced, ...fresh.map((letter) => letter.id)];
69835
+ return { notice, announced: next.length > ANNOUNCED_KEEP ? next.slice(next.length - ANNOUNCED_KEEP) : next };
69836
+ }
69837
+ function waitStateOf(raw) {
69838
+ if (raw === null)
69839
+ return { announced: [], lastEventId: null };
69840
+ try {
69841
+ const value = JSON.parse(raw);
69842
+ return {
69843
+ announced: Array.isArray(value.announced) ? value.announced.filter((id) => typeof id === "string") : [],
69844
+ lastEventId: typeof value.last_event_id === "string" && /^\d+$/.test(value.last_event_id) ? value.last_event_id : null
69845
+ };
69846
+ } catch {
69847
+ return { announced: [], lastEventId: null };
69848
+ }
69849
+ }
69850
+ function waitStateText(state) {
69851
+ return JSON.stringify({ announced: state.announced, ...state.lastEventId === null ? {} : { last_event_id: state.lastEventId } });
69852
+ }
69853
+ var message = (error) => error instanceof Error ? error.message : String(error);
69854
+ async function runEventsWait(ports) {
69855
+ const stop = new AbortController;
69856
+ let timedOut = false;
69857
+ const timer = ports.timeoutMs === null ? undefined : setTimeout(() => {
69858
+ timedOut = true;
69859
+ stop.abort();
69860
+ }, ports.timeoutMs);
69861
+ const state = await ports.readState();
69862
+ let announced = state.announced;
69863
+ let lastEventId = state.lastEventId;
69864
+ const announceLetters = async (page) => {
69865
+ const planned = planNotice(page, announced);
69866
+ if (!planned.notice)
69867
+ return false;
69868
+ announced = planned.announced;
69869
+ await ports.writeState({ announced, lastEventId });
69870
+ ports.print(planned.notice);
69871
+ return true;
69872
+ };
69873
+ const announce = async () => announceLetters(await ports.fetchLetters());
69874
+ try {
69875
+ try {
69876
+ if (await announce())
69877
+ return 0;
69878
+ } catch (error) {
69879
+ ports.log(`praxis agent events wait: reading letters failed: ${message(error)}`);
69880
+ }
69881
+ ports.log(`praxis agent events wait: waiting for letters to assume agent ${ports.agent}`);
69882
+ let failures = 0;
69883
+ while (!stop.signal.aborted) {
69884
+ if (failures)
69885
+ await ports.sleep(backoffMs(failures), stop.signal);
69886
+ if (stop.signal.aborted)
69887
+ break;
69888
+ try {
69889
+ const opened = await ports.openStream(stop.signal, lastEventId);
69890
+ if (opened.status < 200 || opened.status >= 300 || !opened.chunks) {
69891
+ if (!retryableStatus(opened.status)) {
69892
+ ports.log(`praxis agent events wait: the event stream was refused (HTTP ${opened.status}${opened.reason ? `: ${opened.reason}` : ""})`);
69893
+ return 1;
69894
+ }
69895
+ throw new Error(`HTTP ${opened.status}`);
69896
+ }
69897
+ if (await announce())
69898
+ return 0;
69899
+ if (failures)
69900
+ ports.log("praxis agent events wait: event stream reconnected");
69901
+ failures = 0;
69902
+ let buffer = "";
69903
+ for await (const chunk of opened.chunks) {
69904
+ const fed = feedSse(buffer, chunk);
69905
+ buffer = fed.buffer;
69906
+ for (const frame of fed.frames) {
69907
+ const wake = wakeOf(frame);
69908
+ if (wake !== null && frame.id !== undefined)
69909
+ lastEventId = frame.id;
69910
+ if (wake?.kind === "letter" && await announceLetters({ unread: 1, letters: [wake.letter] }))
69911
+ return 0;
69912
+ if (wake?.kind === "ritual") {
69913
+ await ports.writeState({ announced, lastEventId });
69914
+ ports.print(ritualNotice(wake.ritual));
69915
+ return 0;
69916
+ }
69917
+ }
69918
+ }
69919
+ throw new Error("the event stream ended");
69920
+ } catch (error) {
69921
+ if (stop.signal.aborted)
69922
+ break;
69923
+ failures += 1;
69924
+ ports.log(`praxis agent events wait: ${message(error)} (${failures} in a row, reconnecting in ${backoffMs(failures) / 1000}s)`);
69925
+ }
69926
+ }
69927
+ if (timedOut)
69928
+ ports.print(`${(ports.timeoutMs ?? 0) / 1000} 秒内没有新信。需要继续等待时再在后台运行 praxis agent events wait。`);
69929
+ return 0;
69930
+ } finally {
69931
+ if (timer)
69932
+ clearTimeout(timer);
69933
+ stop.abort();
69934
+ }
69935
+ }
69936
+
69937
+ // src/commands/events-channel.ts
69938
+ var CHANNEL_SOURCE = "assume-agent";
69939
+ var SERVER_NAME = "assume-channel";
69940
+ var DEFAULT_PROTOCOL_VERSION = "2025-06-18";
69941
+ var BACKLOG_NAMED = 5;
69942
+ function channelInstructions(agent) {
69943
+ return [
69944
+ `Events from your Praxis assume agent ${agent} arrive as <channel source="${CHANNEL_SOURCE}" kind="letter" letter_id="…" sender="…">.`,
69945
+ 'kind="letter": a letter reached the agent. The content names the sender and the summary; read the letters with the praxis_assume_inbox tool (action "read") and handle them.',
69946
+ 'kind="ritual": the agent was given a new memory (a ritual was held); its knowledge is refreshed, nothing to reply to.',
69947
+ "The channel is one-way: answer through the praxis_assume_* tools, not back through the channel."
69948
+ ].join(`
69949
+ `);
69950
+ }
69951
+ function initializeResult(params, agent) {
69952
+ const asked = params?.protocolVersion;
69953
+ return {
69954
+ protocolVersion: typeof asked === "string" ? asked : DEFAULT_PROTOCOL_VERSION,
69955
+ capabilities: { experimental: { "claude/channel": {} } },
69956
+ serverInfo: { name: SERVER_NAME, version: "0.1.0" },
69957
+ instructions: channelInstructions(agent)
69958
+ };
69959
+ }
69960
+ function replyTo(message2, agent) {
69961
+ if (message2.id === undefined || message2.id === null || typeof message2.method !== "string")
69962
+ return null;
69963
+ const reply = (body) => ({ jsonrpc: "2.0", id: message2.id, ...body });
69964
+ switch (message2.method) {
69965
+ case "initialize":
69966
+ return reply({ result: initializeResult(message2.params, agent) });
69967
+ case "ping":
69968
+ return reply({ result: {} });
69969
+ default:
69970
+ return reply({ error: { code: -32601, message: `Method not found: ${message2.method}` } });
69971
+ }
69972
+ }
69973
+ var sender = (letter) => letter.sender_name || letter.sender;
69974
+ var readHint = 'Read it with praxis_assume_inbox (action "read").';
69975
+ var frame = (content, meta) => ({ jsonrpc: "2.0", method: "notifications/claude/channel", params: { content, meta } });
69976
+ function letterNotification(letter) {
69977
+ return frame(`${sender(letter)}: ${letter.summary}
69978
+ ${readHint}`, { kind: "letter", letter_id: letter.id, sender: letter.sender, ...letter.sender_name ? { sender_name: letter.sender_name } : {} });
69979
+ }
69980
+ function backlogNotification(letters) {
69981
+ const named = letters.slice(0, BACKLOG_NAMED).map((letter) => `${sender(letter)}: ${letter.summary} (${letter.id})`);
69982
+ const more = letters.length > BACKLOG_NAMED ? `; ${letters.length - BACKLOG_NAMED} more` : "";
69983
+ return frame(`${letters.length} unread letter(s) waiting: ${named.join("; ")}${more}
69984
+ ${readHint}`, { kind: "letter", letter_id: letters[0].id, sender: letters[0].sender, count: String(letters.length) });
69985
+ }
69986
+ function ritualNotification(ritual) {
69987
+ return frame(`New memory: "${ritual.title}"${ritual.owner ? ` (${ritual.owner}${ritual.ritual ? ` ${ritual.ritual}` : ""})` : ""}. Your knowledge is refreshed.`, { kind: "ritual", ...ritual.ritual ? { ritual: ritual.ritual } : {}, ...ritual.engram ? { engram: ritual.engram } : {} });
69988
+ }
69989
+ async function runChannel(ports) {
69990
+ const stop = new AbortController;
69991
+ const seen = new Set;
69992
+ let lastEventId = null;
69993
+ let follower = null;
69994
+ const fresh = (letters) => letters.filter((letter) => !seen.has(letter.id) && (seen.add(letter.id), true));
69995
+ const catchUp = async () => {
69996
+ const letters = fresh((await ports.fetchLetters()).letters);
69997
+ if (letters.length)
69998
+ ports.send(backlogNotification(letters));
69999
+ };
70000
+ const follow = async () => {
70001
+ let failures = 0;
70002
+ while (!stop.signal.aborted) {
70003
+ if (failures)
70004
+ await ports.sleep(backoffMs(failures), stop.signal);
70005
+ if (stop.signal.aborted)
70006
+ break;
70007
+ try {
70008
+ const opened = await ports.openStream(stop.signal, lastEventId);
70009
+ if (opened.status < 200 || opened.status >= 300 || !opened.chunks) {
70010
+ if (!retryableStatus(opened.status)) {
70011
+ ports.log(`assume-channel: the event stream was refused (HTTP ${opened.status}${opened.reason ? `: ${opened.reason}` : ""})`);
70012
+ return;
70013
+ }
70014
+ throw new Error(`HTTP ${opened.status}`);
70015
+ }
70016
+ try {
70017
+ await catchUp();
70018
+ } catch (error) {
70019
+ ports.log(`assume-channel: reading letters failed: ${error instanceof Error ? error.message : error}`);
70020
+ }
70021
+ if (failures)
70022
+ ports.log("assume-channel: event stream reconnected");
70023
+ failures = 0;
70024
+ let buffer2 = "";
70025
+ for await (const chunk of opened.chunks) {
70026
+ const fed = feedSse(buffer2, chunk);
70027
+ buffer2 = fed.buffer;
70028
+ for (const raw of fed.frames) {
70029
+ const wake = wakeOf(raw);
70030
+ if (wake === null)
70031
+ continue;
70032
+ if (raw.id !== undefined)
70033
+ lastEventId = raw.id;
70034
+ if (wake.kind === "letter") {
70035
+ if (fresh([wake.letter]).length)
70036
+ ports.send(letterNotification(wake.letter));
70037
+ } else
70038
+ ports.send(ritualNotification(wake.ritual));
70039
+ }
70040
+ }
70041
+ throw new Error("the event stream ended");
70042
+ } catch (error) {
70043
+ if (stop.signal.aborted)
70044
+ break;
70045
+ failures += 1;
70046
+ ports.log(`assume-channel: ${error instanceof Error ? error.message : error} (${failures} in a row, reconnecting in ${backoffMs(failures) / 1000}s)`);
70047
+ }
70048
+ }
70049
+ };
70050
+ let buffer = "";
70051
+ const handle = (line) => {
70052
+ if (!line.trim())
70053
+ return;
70054
+ let message2;
70055
+ try {
70056
+ message2 = JSON.parse(line);
70057
+ } catch {
70058
+ ports.log("assume-channel: ignored a line that is not JSON");
70059
+ return;
70060
+ }
70061
+ const reply = replyTo(message2, ports.agent);
70062
+ if (reply)
70063
+ ports.send(reply);
70064
+ if (message2.method === "notifications/initialized" && follower === null)
70065
+ follower = follow();
70066
+ };
70067
+ for await (const chunk of ports.input) {
70068
+ buffer += chunk;
70069
+ const lines = buffer.split(`
70070
+ `);
70071
+ buffer = lines.pop() ?? "";
70072
+ for (const line of lines)
70073
+ handle(line);
70074
+ }
70075
+ handle(buffer);
70076
+ stop.abort();
70077
+ await follower;
70078
+ return 0;
70079
+ }
70080
+
70081
+ // src/commands/agent-memory.ts
70082
+ var MEMORY_TOOL = "praxis_assume_memory";
70083
+ var RECALL_TOOL = "praxis_assume_recall";
70084
+ var REMEMBER_TOOL = "praxis_assume_remember";
70085
+ function mcpUrl(apiUrl, agent) {
70086
+ return `${apiUrl}/agent/v1/agents/${encodeURIComponent(agent)}/mcp`;
70087
+ }
70088
+ function rpcAnswerOf(body, id) {
70089
+ const candidates2 = body.trimStart().startsWith("{") ? [body] : body.split(`
70090
+ `).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim());
70091
+ for (const candidate of candidates2) {
70092
+ try {
70093
+ const parsed = JSON.parse(candidate);
70094
+ if (parsed.id === id)
70095
+ return parsed;
70096
+ } catch {}
70097
+ }
70098
+ return null;
70099
+ }
70100
+ function toolTextOf(result) {
70101
+ const value = result;
70102
+ const text3 = (value?.content ?? []).filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text).join(`
70103
+ `).trim();
70104
+ return value?.isError === true ? { ok: false, reason: text3 || "the tool refused" } : { ok: true, text: text3 };
70105
+ }
70106
+ async function callAgentTool(ports, url, name, args, signal) {
70107
+ const base = { ...await ports.headers(), "Content-Type": "application/json", Accept: "application/json, text/event-stream" };
70108
+ const post = (body, session2) => ports.fetch(url, {
70109
+ method: "POST",
70110
+ headers: { ...base, ...session2 === undefined ? {} : { "Mcp-Session-Id": session2 } },
70111
+ body: JSON.stringify(body),
70112
+ ...signal === undefined ? {} : { signal },
70113
+ redirect: "error"
70114
+ });
70115
+ const init = await post({ jsonrpc: "2.0", id: 1, method: "initialize", params: {
70116
+ protocolVersion: "2025-06-18",
70117
+ capabilities: {},
70118
+ clientInfo: { name: "praxis-cli-memory", version: "1" }
70119
+ } });
70120
+ const initBody = await init.text();
70121
+ if (!init.ok)
70122
+ throw new Error(`HTTP ${init.status} on initialize`);
70123
+ const session = init.headers.get("Mcp-Session-Id") ?? undefined;
70124
+ const initAnswer = rpcAnswerOf(initBody, 1);
70125
+ if (initAnswer?.error)
70126
+ throw new Error(initAnswer.error.message ?? "initialize failed");
70127
+ await post({ jsonrpc: "2.0", method: "notifications/initialized" }, session).then((r) => r.text()).catch(() => "");
70128
+ const call3 = await post({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name, arguments: args } }, session);
70129
+ const callBody = await call3.text();
70130
+ if (!call3.ok)
70131
+ throw new Error(`HTTP ${call3.status} on ${name}`);
70132
+ const answer = rpcAnswerOf(callBody, 2);
70133
+ if (answer === null)
70134
+ throw new Error(`no answer from ${name}`);
70135
+ if (answer.error)
70136
+ throw new Error(answer.error.message ?? `${name} failed`);
70137
+ const text3 = toolTextOf(answer.result);
70138
+ if (!text3.ok)
70139
+ throw new Error(text3.reason);
70140
+ return text3.text;
70141
+ }
70142
+ function memoryBodyOf(text3) {
70143
+ return text3.split(`
70144
+ `).filter((line) => !/^shell: acon_/.test(line.trim())).join(`
70145
+ `).trim();
70146
+ }
70147
+ function newParagraphs(memory, seen) {
70148
+ return memory.split(/\n{2,}/).map((part) => part.trim()).filter((part) => part !== "" && !seen.has(part));
70149
+ }
70150
+ var MEMORY_FRAME = (body) => `<memory source="praxis-assume" note="your memory as this agent, drawn from your organization just now; recall with praxis_assume_recall">
70151
+ ${body}
70152
+ </memory>`;
70153
+ var MEMORY_CHANGED_FRAME = (body) => `<memory_since_start source="praxis-assume" note="what came to mind since this conversation last read your memory">
70154
+ ${body}
70155
+ </memory_since_start>`;
70156
+ function hookOutput(event, context) {
70157
+ if (context === null || context.trim() === "")
70158
+ return null;
70159
+ return JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: context } });
70160
+ }
70161
+ function hookInputOf(raw) {
70162
+ try {
70163
+ const parsed = JSON.parse(raw);
70164
+ const sessionId = typeof parsed.session_id === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(parsed.session_id) ? parsed.session_id : null;
70165
+ return { sessionId, source: typeof parsed.source === "string" ? parsed.source : null };
70166
+ } catch {
70167
+ return { sessionId: null, source: null };
70168
+ }
70169
+ }
70170
+ async function runMemoryHook(event, input, ports) {
70171
+ try {
70172
+ const memory = memoryBodyOf(await callAgentTool(ports, ports.url, MEMORY_TOOL, {}, AbortSignal.timeout(ports.timeoutMs)));
70173
+ if (memory === "")
70174
+ return null;
70175
+ const all = newParagraphs(memory, new Set);
70176
+ if (event === "SessionStart") {
70177
+ if (input.sessionId !== null)
70178
+ await ports.writeSeen(input.sessionId, all).catch(() => {
70179
+ return;
70180
+ });
70181
+ return hookOutput(event, MEMORY_FRAME(memory));
70182
+ }
70183
+ const seen = input.sessionId === null ? [] : await ports.readSeen(input.sessionId).catch(() => []);
70184
+ const fresh = newParagraphs(memory, new Set(seen));
70185
+ if (fresh.length === 0)
70186
+ return null;
70187
+ if (input.sessionId !== null)
70188
+ await ports.writeSeen(input.sessionId, [...seen, ...fresh]).catch(() => {
70189
+ return;
70190
+ });
70191
+ return hookOutput(event, MEMORY_CHANGED_FRAME(fresh.join(`
70192
+
70193
+ `)));
70194
+ } catch {
70195
+ return null;
70196
+ }
70197
+ }
70198
+
69343
70199
  // src/main.ts
69344
70200
  import { spawnSync } from "node:child_process";
69345
70201
 
@@ -69457,15 +70313,15 @@ class ModelStream {
69457
70313
  finishReason = "unknown";
69458
70314
  usage;
69459
70315
  add(event) {
69460
- const data = streamData(event), message = record(data.message), response = record(data.response);
70316
+ const data = streamData(event), message2 = record(data.message), response = record(data.response);
69461
70317
  this.chunks.push(streamText(event));
69462
70318
  const choices = Array.isArray(data.choices) ? data.choices : [];
69463
- const reason2 = choices.map((c) => record(c).finish_reason).find((r) => typeof r === "string" && r) ?? record(data.delta).stop_reason ?? message.stop_reason ?? data.stop_reason ?? record(response.incomplete_details).reason ?? response.status;
70319
+ const reason2 = choices.map((c) => record(c).finish_reason).find((r) => typeof r === "string" && r) ?? record(data.delta).stop_reason ?? message2.stop_reason ?? data.stop_reason ?? record(response.incomplete_details).reason ?? response.status;
69464
70320
  if (typeof reason2 === "string" && reason2)
69465
70321
  this.finishReason = reason2;
69466
70322
  else if (["response.completed", "response.incomplete", "response.failed"].includes(String(data.type)))
69467
70323
  this.finishReason = String(data.type).slice("response.".length);
69468
- for (const usage of [message.usage, data.usage, response.usage]) {
70324
+ for (const usage of [message2.usage, data.usage, response.usage]) {
69469
70325
  if (usage !== null && typeof usage === "object" && !Array.isArray(usage))
69470
70326
  this.usage = { ...this.usage, ...record(usage) };
69471
70327
  }
@@ -69530,8 +70386,8 @@ function isSuccess(verb, ctx) {
69530
70386
  }
69531
70387
  var past = { create: "Created", update: "Updated", delete: "Deleted", remove: "Deleted", purge: "Deleted", pause: "Paused", unpause: "Unpaused", resume: "Resumed", start: "Started", stop: "Stopped", cancel: "Cancelled", enable: "Enabled", disable: "Disabled", connect: "Connected", extend: "Extended", fork: "Forked", upload: "Uploaded", run: "Started" };
69532
70388
  var deleted = (verb) => /^(delete|remove|purge)(-|$)/.test(verb);
69533
- function width(text2) {
69534
- return [...text2].reduce((sum, ch) => {
70389
+ function width(text3) {
70390
+ return [...text3].reduce((sum, ch) => {
69535
70391
  const cp = ch.codePointAt(0);
69536
70392
  return sum + (/\p{Mark}/u.test(ch) || cp === 8205 ? 0 : cp >= 4352 && (cp <= 4447 || cp >= 11904 && cp <= 42191 || cp >= 44032 && cp <= 55203 || cp >= 63744 && cp <= 64255 || cp >= 65040 && cp <= 65135 || cp >= 65281 && cp <= 65376 || cp >= 127744) ? 2 : 1);
69537
70393
  }, 0);
@@ -69539,13 +70395,13 @@ function width(text2) {
69539
70395
  function truncate(value, size) {
69540
70396
  if (width(value) <= size)
69541
70397
  return value;
69542
- let text2 = "";
70398
+ let text3 = "";
69543
70399
  for (const ch of value) {
69544
- if (width(text2 + ch) > size - 1)
70400
+ if (width(text3 + ch) > size - 1)
69545
70401
  break;
69546
- text2 += ch;
70402
+ text3 += ch;
69547
70403
  }
69548
- return text2 + "…";
70404
+ return text3 + "…";
69549
70405
  }
69550
70406
  function table(items, ctx, paint) {
69551
70407
  const columns = columnsFor(items);
@@ -69578,13 +70434,13 @@ function table(items, ctx, paint) {
69578
70434
  sizes[index]--;
69579
70435
  }
69580
70436
  const line = (row, header) => row.map((v, i) => {
69581
- const text2 = truncate(v, sizes[i]);
69582
- let styled = header ? paint.dim(text2) : text2;
70437
+ const text3 = truncate(v, sizes[i]);
70438
+ let styled = header ? paint.dim(text3) : text3;
69583
70439
  if (!header && ["status", "state"].includes(columns[i])) {
69584
70440
  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;
69585
- styled = color(text2);
70441
+ styled = color(text3);
69586
70442
  }
69587
- return styled + (i === row.length - 1 ? "" : " ".repeat(Math.max(0, sizes[i] - width(text2))));
70443
+ return styled + (i === row.length - 1 ? "" : " ".repeat(Math.max(0, sizes[i] - width(text3))));
69588
70444
  }).join(" ");
69589
70445
  return [line(headers, true), ...rows.map((row) => line(row, false))].join(`
69590
70446
  `) + `
@@ -69683,9 +70539,9 @@ function renderHuman(result, ctx) {
69683
70539
  }
69684
70540
 
69685
70541
  // src/output/agent.ts
69686
- function cell(text2) {
69687
- const chars = [...text2];
69688
- const limited = chars.length > 500 ? chars.slice(0, 500).join("") + `…[+${chars.length - 500} chars, use --json]` : text2;
70542
+ function cell(text3) {
70543
+ const chars = [...text3];
70544
+ const limited = chars.length > 500 ? chars.slice(0, 500).join("") + `…[+${chars.length - 500} chars, use --json]` : text3;
69689
70545
  return limited.replace(/\\/g, "\\\\").replace(/\|/g, "\\|").replace(/\r?\n/g, "<br>").replace(/\r/g, "<br>");
69690
70546
  }
69691
70547
  function renderAgent(result, ctx) {
@@ -69696,9 +70552,9 @@ function renderAgent(result, ctx) {
69696
70552
  if (modelStream(result.op)) {
69697
70553
  if (!result.summary)
69698
70554
  return {};
69699
- const { text: text2, finish_reason, usage } = result.summary;
69700
- return { stdout: `${text2}${text2.endsWith(`
69701
- `) || !text2 ? "" : `
70555
+ const { text: text3, finish_reason, usage } = result.summary;
70556
+ return { stdout: `${text3}${text3.endsWith(`
70557
+ `) || !text3 ? "" : `
69702
70558
  `}finish_reason: ${finish_reason}
69703
70559
  ${usage ? `usage: ${JSON.stringify(usage)}
69704
70560
  ` : ""}` };
@@ -69917,18 +70773,18 @@ function errorInput(error, ctx) {
69917
70773
  const details = candidate !== null && typeof candidate === "object" && !Array.isArray(candidate) ? candidate : undefined;
69918
70774
  const problem = serverProblem(Object.keys(nested).length ? nested : raw);
69919
70775
  const serverText = (value) => typeof value === "string" && value.trim() ? value : undefined;
69920
- let message = error instanceof Error ? error.message : "Unexpected error";
69921
- const prefix = message.match(/^([A-Z][A-Z0-9_]+):\s*/)?.[1];
70776
+ let message2 = error instanceof Error ? error.message : "Unexpected error";
70777
+ const prefix = message2.match(/^([A-Z][A-Z0-9_]+):\s*/)?.[1];
69922
70778
  const code = error instanceof UsageError ? error.code : businessCode(raw.code) ?? businessCode(nested.code) ?? businessCode(raw.error_code) ?? prefix ?? businessCode(sdk?.code) ?? (sdk?.status ? `HTTP_${sdk.status}` : sdk ? "API_ERROR" : "RUNTIME_ERROR");
69923
70779
  let stripped = false;
69924
- while (message.startsWith(`${code}:`)) {
69925
- message = message.slice(code.length + 1).trimStart();
70780
+ while (message2.startsWith(`${code}:`)) {
70781
+ message2 = message2.slice(code.length + 1).trimStart();
69926
70782
  stripped = true;
69927
70783
  }
69928
70784
  if (stripped)
69929
- message = `${humanize(code)}${message ? `: ${message}` : ""}`;
70785
+ message2 = `${humanize(code)}${message2 ? `: ${message2}` : ""}`;
69930
70786
  const status = sdk?.status, request_id = sdk?.requestId;
69931
- message = serverText(problem?.detail) ?? serverText(problem?.title) ?? message;
70787
+ message2 = serverText(problem?.detail) ?? serverText(problem?.title) ?? message2;
69932
70788
  const authFailure = status === 401 || ["NOT_LOGGED_IN", "UNAUTHENTICATED", "TOKEN_REVOKED", "LOGIN_FAILED", "MANAGED_LOGIN_EXPIRED"].includes(code);
69933
70789
  const source = ctx.credentialSource ?? "login";
69934
70790
  let hint3 = genericHint;
@@ -69946,19 +70802,19 @@ function errorInput(error, ctx) {
69946
70802
  hint3 = "Rate limited; retry later.";
69947
70803
  else if (status !== undefined && status >= 500)
69948
70804
  hint3 = `Server error; retry later.${request_id ? ` Request id: ${request_id}.` : ""}`;
69949
- return { kind: "error", code, message, hint: hint3, ...details !== undefined ? { details } : {}, ...problem !== undefined ? { problem } : {}, env: ctx.env, ...authFailure ? { credential_source: source } : {}, ...status !== undefined ? { status } : {}, ...request_id ? { request_id } : {} };
70805
+ return { kind: "error", code, message: message2, hint: hint3, ...details !== undefined ? { details } : {}, ...problem !== undefined ? { problem } : {}, env: ctx.env, ...authFailure ? { credential_source: source } : {}, ...status !== undefined ? { status } : {}, ...request_id ? { request_id } : {} };
69950
70806
  }
69951
70807
 
69952
70808
  // src/output/progress.ts
69953
- function startProgress(ctx, write = (text2) => writeOutput({ stderr: text2 })) {
70809
+ function startProgress(ctx, write = (text3) => writeOutput({ stderr: text3 })) {
69954
70810
  if (ctx.mode !== "human" || !ctx.stderrIsTTY)
69955
70811
  return () => {};
69956
70812
  let interval;
69957
- let shown = false, frame = 0;
70813
+ let shown = false, frame2 = 0;
69958
70814
  const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
69959
70815
  const tick = () => {
69960
70816
  shown = true;
69961
- write(`\r${frames[frame++ % frames.length]} Loading…`);
70817
+ write(`\r${frames[frame2++ % frames.length]} Loading…`);
69962
70818
  };
69963
70819
  const timer = setTimeout(() => {
69964
70820
  tick();
@@ -69976,7 +70832,7 @@ function startProgress(ctx, write = (text2) => writeOutput({ stderr: text2 })) {
69976
70832
  }
69977
70833
 
69978
70834
  // src/main.ts
69979
- var version = "0.3.0-dev.da03302";
70835
+ var version = "0.3.0-dev.e226dc2";
69980
70836
  var commands = commandTree(operations);
69981
70837
  var manual = [...workflows.map((w) => w.words), [API_WORD]];
69982
70838
  function route(argv) {
@@ -70058,7 +70914,7 @@ var defaults = {
70058
70914
  return;
70059
70915
  const cmd = process.platform === "darwin" ? ["open", url] : process.platform === "win32" ? ["rundll32", "url.dll,FileProtocolHandler", url] : ["xdg-open", url];
70060
70916
  await new Promise((resolve12, reject) => {
70061
- const child = spawn4(cmd[0], cmd.slice(1), { stdio: "ignore" });
70917
+ const child = spawn5(cmd[0], cmd.slice(1), { stdio: "ignore" });
70062
70918
  child.once("error", reject);
70063
70919
  child.once("close", () => resolve12());
70064
70920
  });
@@ -70067,12 +70923,12 @@ var defaults = {
70067
70923
  wait: (ms) => new Promise((resolve12) => setTimeout(resolve12, ms)),
70068
70924
  render,
70069
70925
  spawn: (cmd, args, options) => new Promise((resolve12, reject) => {
70070
- const child = spawn4(cmd, args, { cwd: options.cwd, stdio: ["ignore", 2, 2] });
70926
+ const child = spawn5(cmd, args, { cwd: options.cwd, stdio: ["ignore", 2, 2] });
70071
70927
  child.once("error", reject);
70072
70928
  child.once("close", (code) => resolve12(code ?? 1));
70073
70929
  }),
70074
70930
  spawnCapture: (cmd, args, options) => new Promise((resolve12, reject) => {
70075
- const child = spawn4(cmd, args, { cwd: options.cwd, stdio: ["ignore", "pipe", "pipe"] });
70931
+ const child = spawn5(cmd, args, { cwd: options.cwd, stdio: ["ignore", "pipe", "pipe"] });
70076
70932
  const chunks = [];
70077
70933
  child.stdout.on("data", (c) => chunks.push(c));
70078
70934
  child.stderr.on("data", (c) => chunks.push(c));
@@ -70155,6 +71011,21 @@ var appOptions = {
70155
71011
  { name: "report", type: "boolean", description: "Post this checkout's scan to the platform, so archiving a flag is refused while code still names it (ADR-125 §4)." },
70156
71012
  { name: "project", type: "string", description: "With --report: the DevOps project id (dvp_…) whose flags the scan is reported into. Required." }
70157
71013
  ],
71014
+ "agent memory": [
71015
+ { name: "hook", type: "string", description: "Run as a Claude Code hook (SessionStart or UserPromptSubmit): read the hook input on stdin, print the hook JSON or nothing, always exit 0." }
71016
+ ],
71017
+ "agent recall": [
71018
+ { name: "words", type: "string", repeated: true, description: "Distinctive words to recall by, comma-separated or repeated." },
71019
+ { name: "handles", type: "string", repeated: true, description: "Entry handles or ids from memory to recall, comma-separated or repeated." }
71020
+ ],
71021
+ "agent remember": [
71022
+ { name: "text", type: "string", description: "The experience, in your own words: what happened, who, what was decided and why, what is still open." },
71023
+ { name: "about", type: "string", repeated: true, description: "Ids of entities it is about, comma-separated or repeated." }
71024
+ ],
71025
+ "agent events wait": [
71026
+ { name: "timeout", type: "string", description: "Give up after this many seconds, print that nothing arrived and exit 0 (default: wait until a letter arrives)." },
71027
+ { name: "session", type: "string", description: "The Claude Code session this waiter wakes: its announced letters and pid file are kept per session, and a second waiter for the same session exits at once (default: one waiter per agent)." }
71028
+ ],
70158
71029
  "canvas import": [
70159
71030
  { name: "name", type: "string", description: "Name for the new canvas (default: the file name without .pen)." },
70160
71031
  { name: "canvas", type: "string", description: "Import into this existing canvas instead of a new one. Whole-canvas replacement: it clears what is already there and requires --yes." },
@@ -70173,15 +71044,15 @@ function flagPortsFor(ports, context, emit, connect) {
70173
71044
  return {
70174
71045
  mode: context.mode,
70175
71046
  emit,
70176
- human: (text2) => {
71047
+ human: (text3) => {
70177
71048
  if (context.mode === "human")
70178
- emit({ kind: "message", channel: "stdout", text: text2 });
71049
+ emit({ kind: "message", channel: "stdout", text: text3 });
70179
71050
  },
70180
71051
  cwd: ports.cwd,
70181
71052
  readFile: ports.readFile,
70182
71053
  git: async (args) => (await ports.spawnCapture("git", [...args], { cwd: ports.cwd })).output,
70183
71054
  client: connect,
70184
- writeFile: (path, text2) => writeFile5(path, text2, "utf8"),
71055
+ writeFile: (path, text3) => writeFile5(path, text3, "utf8"),
70185
71056
  mkdir: async (path) => {
70186
71057
  await mkdir4(path, { recursive: true });
70187
71058
  },
@@ -70205,9 +71076,9 @@ function toolPortsFor(ports, context, emit) {
70205
71076
  return {
70206
71077
  mode: context.mode,
70207
71078
  emit,
70208
- human: (text2) => {
71079
+ human: (text3) => {
70209
71080
  if (context.mode === "human")
70210
- emit({ kind: "message", channel: "stdout", text: text2 });
71081
+ emit({ kind: "message", channel: "stdout", text: text3 });
70211
71082
  },
70212
71083
  cwd: ports.cwd,
70213
71084
  readFile: ports.readFile,
@@ -70222,7 +71093,7 @@ function toolPortsFor(ports, context, emit) {
70222
71093
  },
70223
71094
  git: (args, cwd) => ports.spawnCapture("git", args, { cwd }),
70224
71095
  run: (cmd, args, cwd) => new Promise((resolve12, reject) => {
70225
- const child = spawn4(cmd, args, { cwd, stdio: "inherit" });
71096
+ const child = spawn5(cmd, args, { cwd, stdio: "inherit" });
70226
71097
  child.once("error", reject);
70227
71098
  child.once("close", (code) => resolve12(code ?? 1));
70228
71099
  }),
@@ -70247,7 +71118,7 @@ async function main3(argv, injected = {}) {
70247
71118
  columns: ports.columns,
70248
71119
  now: ports.now(),
70249
71120
  envVars: { NO_COLOR: ports.env.NO_COLOR, FORCE_COLOR: ports.env.FORCE_COLOR, TERM: ports.env.TERM },
70250
- env: ports.env.PRAXIS_ENV ?? "develop"
71121
+ env: ports.env.PRAXIS_ENV ?? DEFAULT_ENV
70251
71122
  };
70252
71123
  let stopProgress = () => {};
70253
71124
  let quiet = false;
@@ -70517,9 +71388,9 @@ Examples:
70517
71388
  },
70518
71389
  mode: ctx.mode,
70519
71390
  emit,
70520
- human: (text2) => {
71391
+ human: (text3) => {
70521
71392
  if (ctx.mode === "human")
70522
- emit({ kind: "message", channel: "stdout", text: text2 });
71393
+ emit({ kind: "message", channel: "stdout", text: text3 });
70523
71394
  },
70524
71395
  cwd: ports.cwd
70525
71396
  });
@@ -70546,14 +71417,14 @@ Examples:
70546
71417
  }, {
70547
71418
  mode: ctx.mode,
70548
71419
  emit,
70549
- human: (text2) => {
71420
+ human: (text3) => {
70550
71421
  if (ctx.mode === "human")
70551
- emit({ kind: "message", channel: "stdout", text: text2 });
71422
+ emit({ kind: "message", channel: "stdout", text: text3 });
70552
71423
  },
70553
71424
  engine: codeRefactorEngine(),
70554
71425
  hasFile: (path2) => existsSync4(path2),
70555
71426
  readFile: ports.readFile,
70556
- writeFile: (path2, text2) => writeFile5(path2, text2, "utf8"),
71427
+ writeFile: (path2, text3) => writeFile5(path2, text3, "utf8"),
70557
71428
  mkdir: async (path2) => {
70558
71429
  await mkdir4(path2, { recursive: true });
70559
71430
  },
@@ -70570,9 +71441,9 @@ Examples:
70570
71441
  const shellPorts = {
70571
71442
  mode: ctx.mode,
70572
71443
  emit,
70573
- human: (text2) => {
71444
+ human: (text3) => {
70574
71445
  if (ctx.mode === "human")
70575
- emit({ kind: "message", channel: "stdout", text: text2 });
71446
+ emit({ kind: "message", channel: "stdout", text: text3 });
70576
71447
  },
70577
71448
  engine: await repositoryEngine(name, () => localEngine(ports.cwd)),
70578
71449
  ...localFilePorts(ports.cwd)
@@ -70585,9 +71456,9 @@ Examples:
70585
71456
  const testPorts = {
70586
71457
  mode: ctx.mode,
70587
71458
  emit,
70588
- human: (text2) => {
71459
+ human: (text3) => {
70589
71460
  if (ctx.mode === "human")
70590
- emit({ kind: "message", channel: "stdout", text: text2 });
71461
+ emit({ kind: "message", channel: "stdout", text: text3 });
70591
71462
  },
70592
71463
  engine: await repositoryEngine(name, () => localEngine(ports.cwd)),
70593
71464
  checkout: await localCheckout(ports.cwd, (cmd, args, options) => ports.spawnCapture(cmd, args, options))
@@ -70596,9 +71467,9 @@ Examples:
70596
71467
  return await devopsTestReport({ path: parsed.positional[0], id: parsed.flags.id?.[0], upload: Boolean(parsed.flags.upload), project: parsed.flags.project?.[0] }, testPorts, {
70597
71468
  mode: ctx.mode,
70598
71469
  emit,
70599
- human: (text2) => {
71470
+ human: (text3) => {
70600
71471
  if (ctx.mode === "human")
70601
- emit({ kind: "message", channel: "stdout", text: text2 });
71472
+ emit({ kind: "message", channel: "stdout", text: text3 });
70602
71473
  },
70603
71474
  root: async () => await checkoutRoot(ports.cwd, ports.readFile),
70604
71475
  readFile: ports.readFile,
@@ -70628,9 +71499,9 @@ Examples:
70628
71499
  git: (args) => ports.spawnCapture("git", args, { cwd: ports.cwd }),
70629
71500
  mode: ctx.mode,
70630
71501
  emit,
70631
- human: (text2) => {
71502
+ human: (text3) => {
70632
71503
  if (ctx.mode === "human")
70633
- emit({ kind: "message", channel: "stdout", text: text2 });
71504
+ emit({ kind: "message", channel: "stdout", text: text3 });
70634
71505
  }
70635
71506
  });
70636
71507
  }
@@ -70680,9 +71551,9 @@ Examples:
70680
71551
  emit({ kind: "object", data: await auth.switchOrganization(parsed.positional[0]) });
70681
71552
  break;
70682
71553
  case "app create": {
70683
- const appPorts = { ...ports, mode: ctx.mode, emit, human: (text2) => {
71554
+ const appPorts = { ...ports, mode: ctx.mode, emit, human: (text3) => {
70684
71555
  if (ctx.mode === "human")
70685
- emit({ kind: "message", channel: "stdout", text: text2 });
71556
+ emit({ kind: "message", channel: "stdout", text: text3 });
70686
71557
  }, random: randomSecret };
70687
71558
  await appCreate({ name: parsed.positional[0], dir: parsed.flags.dir?.[0], template: parsed.flags.template?.[0], install: !parsed.flags["no-install"] }, config.env, appPorts);
70688
71559
  break;
@@ -70711,13 +71582,220 @@ Examples:
70711
71582
  wait: ports.wait,
70712
71583
  mode: ctx.mode,
70713
71584
  emit,
70714
- human: (text2) => {
71585
+ human: (text3) => {
70715
71586
  if (ctx.mode === "human")
70716
- emit({ kind: "message", channel: "stdout", text: text2 });
71587
+ emit({ kind: "message", channel: "stdout", text: text3 });
70717
71588
  },
70718
71589
  cwd: ports.cwd
70719
71590
  });
70720
71591
  }
71592
+ case "agent events channel": {
71593
+ const agent = assumeAgentOf(ports.env);
71594
+ const headers = async () => {
71595
+ const credential = await auth.get(org);
71596
+ return { Authorization: `Bearer ${credential.token}`, ...credential.source === "api-key" ? { "X-API-Key": credential.token } : {} };
71597
+ };
71598
+ const failure2 = (status, body) => `HTTP ${status}${body?.error?.code ? ` ${body.error.code}` : ""}${body?.error?.message ? `: ${String(redact(body.error.message, secrets))}` : ""}`;
71599
+ process.stdin.setEncoding("utf8");
71600
+ return await runChannel({
71601
+ agent,
71602
+ input: process.stdin,
71603
+ send: (frame2) => {
71604
+ process.stdout.write(JSON.stringify(frame2) + `
71605
+ `);
71606
+ },
71607
+ fetchLetters: async () => {
71608
+ const response = await wireFetch(inboxLettersUrl(config.apiUrl, agent), { headers: await headers(), signal: AbortSignal.timeout(30000), redirect: "error" });
71609
+ const body = await response.json().catch(() => null);
71610
+ if (!response.ok)
71611
+ throw new Error(failure2(response.status, body));
71612
+ return lettersOf(body);
71613
+ },
71614
+ openStream: async (signal, lastEventId) => {
71615
+ const response = await wireFetch(eventsStreamUrl(config.apiUrl, agent), { headers: streamHeaders(await headers(), lastEventId), signal, redirect: "error" });
71616
+ if (!response.ok || !response.body) {
71617
+ const body = await response.json().catch(() => null);
71618
+ return { status: response.status, reason: failure2(response.status, body) };
71619
+ }
71620
+ return { status: response.status, chunks: response.body.pipeThrough(new TextDecoderStream) };
71621
+ },
71622
+ sleep: (ms, signal) => new Promise((resolve12) => {
71623
+ const timer = setTimeout(resolve12, ms);
71624
+ signal.addEventListener("abort", () => {
71625
+ clearTimeout(timer);
71626
+ resolve12();
71627
+ }, { once: true });
71628
+ }),
71629
+ log: (line) => {
71630
+ process.stderr.write(String(redact(line, secrets)) + `
71631
+ `);
71632
+ }
71633
+ });
71634
+ }
71635
+ case "agent memory":
71636
+ case "agent recall":
71637
+ case "agent remember": {
71638
+ const agent = assumeAgentOf(ports.env);
71639
+ const mcpPorts = {
71640
+ fetch: (url2, init) => wireFetch(url2, init),
71641
+ headers: async () => {
71642
+ const credential = await auth.get(org);
71643
+ return { Authorization: `Bearer ${credential.token}`, ...credential.source === "api-key" ? { "X-API-Key": credential.token } : {} };
71644
+ }
71645
+ };
71646
+ const url = mcpUrl(config.apiUrl, agent);
71647
+ const hook = parsed.flags.hook?.[0];
71648
+ if (name === "agent memory" && hook !== undefined) {
71649
+ if (hook !== "SessionStart" && hook !== "UserPromptSubmit")
71650
+ throw new UsageError(`--hook takes SessionStart or UserPromptSubmit, not ${hook}`, "Example: praxis agent memory --hook SessionStart");
71651
+ process.stdin.setEncoding("utf8");
71652
+ let raw = "";
71653
+ if (!process.stdin.isTTY)
71654
+ for await (const chunk of process.stdin)
71655
+ raw += chunk;
71656
+ const input = hookInputOf(raw);
71657
+ const seenDir = join12(ports.env.HOME || homedir3(), ".praxis", "cli", "memory-seen");
71658
+ const out = await runMemoryHook(hook, input, {
71659
+ ...mcpPorts,
71660
+ url,
71661
+ timeoutMs: 25000,
71662
+ readSeen: async (id) => JSON.parse(await readFile7(join12(seenDir, `${id}.json`), "utf8")),
71663
+ writeSeen: async (id, paragraphs) => {
71664
+ await mkdir4(seenDir, { recursive: true, mode: 448 });
71665
+ await writeFile5(join12(seenDir, `${id}.json`), JSON.stringify(paragraphs), { mode: 384 });
71666
+ }
71667
+ });
71668
+ if (out !== null)
71669
+ process.stdout.write(out + `
71670
+ `);
71671
+ return 0;
71672
+ }
71673
+ const list = (flag) => (parsed.flags[flag] ?? []).flatMap((value) => value.split(",")).map((value) => value.trim()).filter(Boolean);
71674
+ const args = name === "agent recall" ? { ...list("handles").length ? { handles: list("handles") } : {}, ...list("words").length ? { words: list("words") } : {} } : name === "agent remember" ? { text: parsed.flags.text?.[0] ?? "", ...list("about").length ? { about: list("about") } : {} } : {};
71675
+ if (name === "agent remember" && String(args.text).trim() === "")
71676
+ throw new UsageError("--text is required", 'Example: praxis agent remember --text "今天定了……"');
71677
+ const tool = name === "agent memory" ? MEMORY_TOOL : name === "agent recall" ? RECALL_TOOL : REMEMBER_TOOL;
71678
+ const text3 = memoryBodyOf(await callAgentTool(mcpPorts, url, tool, args, AbortSignal.timeout(60000)));
71679
+ process.stdout.write(text3 + `
71680
+ `);
71681
+ return 0;
71682
+ }
71683
+ case "agent events wait": {
71684
+ const agent = assumeAgentOf(ports.env);
71685
+ const timeoutMs = (() => {
71686
+ try {
71687
+ return timeoutMsOf(parsed.flags.timeout?.[0]);
71688
+ } catch (error) {
71689
+ throw new UsageError(error.message, "Example: praxis agent events wait --timeout 3600");
71690
+ }
71691
+ })();
71692
+ const headers = async () => {
71693
+ const credential = await auth.get(org);
71694
+ return { Authorization: `Bearer ${credential.token}`, ...credential.source === "api-key" ? { "X-API-Key": credential.token } : {} };
71695
+ };
71696
+ const failure2 = (status, body) => `HTTP ${status}${body?.error?.code ? ` ${body.error.code}` : ""}${body?.error?.message ? `: ${String(redact(body.error.message, secrets))}` : ""}`;
71697
+ const session = (() => {
71698
+ try {
71699
+ return sessionOf(parsed.flags.session?.[0]);
71700
+ } catch (error) {
71701
+ throw new UsageError(error.message, "Example: praxis agent events wait --session 0f6c…");
71702
+ }
71703
+ })();
71704
+ const key = waitKeyOf(config.env, agent, session);
71705
+ const waitDir = join12(ports.env.HOME || homedir3(), ".praxis", "cli", "events-wait");
71706
+ const statePath = join12(waitDir, `${key}.json`);
71707
+ const pidPath = join12(waitDir, `${key}.pid`);
71708
+ await mkdir4(waitDir, { recursive: true, mode: 448 });
71709
+ const holder = await acquireWaitLock({
71710
+ self: process.pid,
71711
+ readPid: () => readFile7(pidPath, "utf8").catch(() => null),
71712
+ createPid: (text3) => writeFile5(pidPath, text3, { mode: 384, flag: "wx" }).then(() => true, () => false),
71713
+ replacePid: (text3) => writeFile5(pidPath, text3, { mode: 384 }),
71714
+ probe: async (pid) => {
71715
+ try {
71716
+ process.kill(pid, 0);
71717
+ } catch (error) {
71718
+ if (error.code !== "EPERM")
71719
+ return { alive: false };
71720
+ }
71721
+ const ps = spawnSync("ps", ["-o", "ppid=,command=", "-p", String(pid)], { encoding: "utf8" });
71722
+ const line = ps.stdout?.trim() ?? "";
71723
+ const match = /^(\d+)\s+(.*)$/.exec(line);
71724
+ return match ? { alive: true, ppid: Number(match[1]), command: match[2] } : { alive: false };
71725
+ },
71726
+ terminate: (pid) => {
71727
+ try {
71728
+ process.kill(pid, "SIGTERM");
71729
+ } catch {}
71730
+ }
71731
+ });
71732
+ if (holder !== null) {
71733
+ process.stdout.write(alreadyWaitingNotice(holder) + `
71734
+ `);
71735
+ return 0;
71736
+ }
71737
+ const release = () => {
71738
+ try {
71739
+ if (pidOf(readFileSync3(pidPath, "utf8")) === process.pid)
71740
+ unlinkSync(pidPath);
71741
+ } catch {}
71742
+ };
71743
+ const onSignal = (signal) => {
71744
+ release();
71745
+ process.exit(signal === "SIGINT" ? 130 : 143);
71746
+ };
71747
+ for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"])
71748
+ process.once(signal, onSignal);
71749
+ try {
71750
+ return await runEventsWait({
71751
+ agent,
71752
+ timeoutMs,
71753
+ fetchLetters: async () => {
71754
+ const response = await wireFetch(inboxLettersUrl(config.apiUrl, agent), { headers: await headers(), signal: AbortSignal.timeout(30000), redirect: "error" });
71755
+ const body = await response.json().catch(() => null);
71756
+ if (!response.ok)
71757
+ throw new Error(failure2(response.status, body));
71758
+ return lettersOf(body);
71759
+ },
71760
+ openStream: async (signal, lastEventId) => {
71761
+ const response = await wireFetch(eventsStreamUrl(config.apiUrl, agent), {
71762
+ headers: streamHeaders(await headers(), lastEventId),
71763
+ signal,
71764
+ redirect: "error"
71765
+ });
71766
+ if (!response.ok || !response.body) {
71767
+ const body = await response.json().catch(() => null);
71768
+ return { status: response.status, reason: failure2(response.status, body) };
71769
+ }
71770
+ return { status: response.status, chunks: response.body.pipeThrough(new TextDecoderStream) };
71771
+ },
71772
+ readState: async () => waitStateOf(await readFile7(statePath, "utf8").catch(() => null)),
71773
+ writeState: async (next) => {
71774
+ await mkdir4(dirname10(statePath), { recursive: true, mode: 448 });
71775
+ await writeFile5(statePath, waitStateText(next), { mode: 384 });
71776
+ },
71777
+ print: (line) => {
71778
+ process.stdout.write(line + `
71779
+ `);
71780
+ },
71781
+ log: (line) => {
71782
+ process.stderr.write(String(redact(line, secrets)) + `
71783
+ `);
71784
+ },
71785
+ sleep: (ms, signal) => new Promise((resolve12) => {
71786
+ const timer = setTimeout(resolve12, ms);
71787
+ signal.addEventListener("abort", () => {
71788
+ clearTimeout(timer);
71789
+ resolve12();
71790
+ }, { once: true });
71791
+ })
71792
+ });
71793
+ } finally {
71794
+ release();
71795
+ for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"])
71796
+ process.removeListener(signal, onSignal);
71797
+ }
71798
+ }
70721
71799
  case "canvas import": {
70722
71800
  const authorize = async () => {
70723
71801
  const credential = await auth.get(org);
@@ -70759,7 +71837,7 @@ Examples:
70759
71837
  file: parsed.positional[0],
70760
71838
  name: parsed.flags.name?.[0],
70761
71839
  canvas: parsed.flags.canvas?.[0],
70762
- frames: typeof parsed.flags.frames?.[0] === "string" ? parsed.flags.frames[0].split(",").map((frame) => frame.trim()).filter(Boolean) : undefined,
71840
+ frames: typeof parsed.flags.frames?.[0] === "string" ? parsed.flags.frames[0].split(",").map((frame2) => frame2.trim()).filter(Boolean) : undefined,
70763
71841
  imageRoots: parsed.flags["image-root"],
70764
71842
  dryRun: Boolean(parsed.flags["dry-run"]?.[0]),
70765
71843
  yes: Boolean(flags.yes)
@@ -70773,9 +71851,9 @@ Examples:
70773
71851
  cwd: ports.cwd,
70774
71852
  rpc,
70775
71853
  upload,
70776
- human: (text2) => {
71854
+ human: (text3) => {
70777
71855
  if (ctx.mode === "human")
70778
- emit({ kind: "message", channel: "stdout", text: text2 });
71856
+ emit({ kind: "message", channel: "stdout", text: text3 });
70779
71857
  }
70780
71858
  });
70781
71859
  }
@@ -70807,7 +71885,8 @@ if (true) {
70807
71885
  process.exit(0);
70808
71886
  throw error;
70809
71887
  });
70810
- process.exitCode = await main3(process.argv.slice(2));
71888
+ const argv = process.argv.slice(2);
71889
+ process.exitCode = isDevopsTestRun(route(argv).words) && needsCacheOffReexec(process.env) ? await reexecWithCacheOff() : await main3(argv);
70811
71890
  }
70812
71891
  export {
70813
71892
  main3 as main