@deepraxis/cli 0.3.0-dev.c811f1a → 0.3.0-dev.c81a93f

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.
package/dist/praxis.js CHANGED
@@ -13983,12 +13983,18 @@ var FLAGS;
13983
13983
  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
+ "cognition-per-agent": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "usr_t60d4g5z82rhbtbfrfxfbdxe", ticket: 2506, expires: "2026-11-30", system: "devops" },
13986
13987
  "cognition-weight-driven": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "praxis-bd", ticket: 1760, expires: "2026-12-05", system: "devops" },
13988
+ "computer-archive-volume": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "usr_t60d4g5z82rhbtbfrfxfbdxe", ticket: 2419, expires: "2026-11-30", system: "devops" },
13989
+ crm: { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "usr_rv860m7z9h8szkgma56cd14n", ticket: 2179, expires: "2026-12-31", system: "devops" },
13987
13990
  "delivery-rules-v2": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "usr_t60d4g5z82rhbtbfrfxfbdxe", ticket: 2048, expires: "2026-11-28", system: "devops" },
13991
+ "end-users": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "usr_t60d4g5z82rhbtbfrfxfbdxe", ticket: 2312, expires: "2026-12-15", system: "devops" },
13988
13992
  "model-access-gate": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "usr_t60d4g5z82rhbtbfrfxfbdxe", ticket: 1933, expires: "2026-12-15", system: "devops" },
13989
13993
  "open-project": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "praxis-51", ticket: 1488, expires: "2026-11-25", system: "devops" },
13994
+ "requests-never-hold": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "usr_t60d4g5z82rhbtbfrfxfbdxe", ticket: 2119, expires: "2026-11-29", system: "devops" },
13990
13995
  "requests-v1": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "usr_t60d4g5z82rhbtbfrfxfbdxe", ticket: 2057, expires: "2026-11-28", system: "devops" },
13991
13996
  "router-precommit-hedge": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "usr_t60d4g5z82rhbtbfrfxfbdxe", ticket: 2052, expires: "2026-11-28", system: "devops" },
13997
+ "router-responses-hedge": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "usr_t60d4g5z82rhbtbfrfxfbdxe", ticket: 2149, expires: "2026-11-28", system: "devops" },
13992
13998
  "search-provider-routing": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "praxis-98", ticket: 716, expires: "2026-12-31", system: "devops" },
13993
13999
  "unit-live-probe": { kind: "RELEASE", type: "BOOLEAN", default: false, owner: "usr_t60d4g5z82rhbtbfrfxfbdxe", ticket: null, expires: "2026-11-19", system: "devops" }
13994
14000
  };
@@ -14015,7 +14021,7 @@ function checkFlags(files, registry, today = new Date().toISOString().slice(0, 1
14015
14021
  }
14016
14022
  const registryFile = production.find((f) => f.path.endsWith("flag-registry.generated.ts"));
14017
14023
  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 });
14024
+ const add = (file, offset, message2) => issues.push({ file: file.path, line: lineOf(file.text, offset), message: message2 });
14019
14025
  const referencedKeysIn = (file) => {
14020
14026
  for (const key of registered) {
14021
14027
  const literal = new RegExp(`(?:"|')${key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:"|')`);
@@ -14104,7 +14110,7 @@ async function main() {
14104
14110
  else
14105
14111
  console.log(`Feature flag registry check passed (${Object.keys(FLAGS).length} registered flags).`);
14106
14112
  }
14107
- var isTest = (path) => /(^|\/)(spec|__tests__)(\/|$)|\.(test|spec)\.[cm]?[jt]sx?$/.test(path), lineOf = (text2, offset) => text2.slice(0, offset).split(`
14113
+ var isTest = (path) => /(^|\/)(spec|__tests__)(\/|$)|\.(test|spec)\.[cm]?[jt]sx?$/.test(path), lineOf = (text3, offset) => text3.slice(0, offset).split(`
14108
14114
  `).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
14115
  var init_check_flags = __esm(() => {
14110
14116
  init_flag_registry_generated();
@@ -14302,7 +14308,7 @@ async function checkRegistrySync(ports = {}) {
14302
14308
  }
14303
14309
  async function syncFlags(ports = {}) {
14304
14310
  const registry = ports.registry ?? registryUrl;
14305
- const write = ports.write ?? ((target, text2) => writeFile4(target, text2));
14311
+ const write = ports.write ?? ((target, text3) => writeFile4(target, text3));
14306
14312
  const log = ports.log ?? console.log;
14307
14313
  const error = ports.error ?? console.error;
14308
14314
  const devops = await (ports.devops ?? readDevopsFlags)();
@@ -14539,12 +14545,13 @@ async function runEngineDelegation(delegation, options) {
14539
14545
  }
14540
14546
 
14541
14547
  // src/main.ts
14542
- import { existsSync as existsSync4 } from "node:fs";
14548
+ import { existsSync as existsSync4, readFileSync as readFileSync3, unlinkSync } from "node:fs";
14543
14549
  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";
14550
+ import { dirname as dirname10, join as join12, resolve as resolve11 } from "node:path";
14551
+ import { homedir as homedir3 } from "node:os";
14545
14552
  import { pathToFileURL } from "node:url";
14546
14553
  import { createHash as createHash5 } from "node:crypto";
14547
- import { spawn as spawn4 } from "node:child_process";
14554
+ import { spawn as spawn5 } from "node:child_process";
14548
14555
  import { createInterface } from "node:readline";
14549
14556
 
14550
14557
  // ../../packages/sdk/typescript/src/operations.generated.ts
@@ -15599,8 +15606,8 @@ Idempotent. Access tokens revoked while the customer was blocked stay revoked; s
15599
15606
  {
15600
15607
  resource: "agent.agents.events",
15601
15608
  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.",
15609
+ summary: "Follow an agent live",
15610
+ 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
15611
  http: "GET",
15605
15612
  path: "/agent/v1/agents/{agent_id}/events/stream",
15606
15613
  streaming: "always",
@@ -15626,6 +15633,40 @@ Idempotent. Access tokens revoked while the customer was blocked stay revoked; s
15626
15633
  }
15627
15634
  ]
15628
15635
  },
15636
+ {
15637
+ resource: "agent.agents.inbox.letters",
15638
+ method: "list",
15639
+ summary: "List an assume agent's waiting letters",
15640
+ 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.",
15641
+ http: "GET",
15642
+ path: "/agent/v1/agents/{agent_id}/inbox/letters",
15643
+ streaming: "no",
15644
+ pagination: false,
15645
+ pathParams: [
15646
+ {
15647
+ name: "agent_id",
15648
+ sdkName: "agent_id",
15649
+ 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_…."
15650
+ }
15651
+ ],
15652
+ query: [
15653
+ {
15654
+ name: "unread",
15655
+ type: "boolean",
15656
+ enum: [
15657
+ true
15658
+ ],
15659
+ required: false,
15660
+ description: "Only true is accepted, which is also the default; this read lists waiting (unread) letters and nothing else."
15661
+ },
15662
+ {
15663
+ name: "limit",
15664
+ type: "integer",
15665
+ required: false,
15666
+ description: "How many of the newest unread letters to return, 1 to 50 (default 20); unread always counts every waiting letter."
15667
+ }
15668
+ ]
15669
+ },
15629
15670
  {
15630
15671
  resource: "agent.agents.unarchive",
15631
15672
  method: "create",
@@ -16993,7 +17034,7 @@ delete it. Omit the field to preserve.`
16993
17034
  summary: "List Session Artifacts (Extension)",
16994
17035
  description: `List the files this session delivered; an end-customer token reads its own session.
16995
17036
 
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.`,
17037
+ 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
17038
  http: "GET",
16998
17039
  path: "/agent/v1/sessions/{session_id}/artifacts",
16999
17040
  streaming: "no",
@@ -17013,7 +17054,7 @@ Own-face extension. Returns { data: Artifact[] } ordered by create_time. Each ar
17013
17054
  summary: "Create Artifact Content URL (Extension)",
17014
17055
  description: `Mint a short-lived download address for one file of an artifact.
17015
17056
 
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.`,
17057
+ 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
17058
  http: "POST",
17018
17059
  path: "/agent/v1/sessions/{session_id}/artifacts/{artifact_id}/content_url",
17019
17060
  streaming: "no",
@@ -17232,7 +17273,7 @@ Praxis extension available only on /agent/v1, following Claude Agent SDK getCont
17232
17273
  resource: "agent.sessions.events",
17233
17274
  method: "list",
17234
17275
  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.",
17276
+ 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
17277
  http: "GET",
17237
17278
  path: "/agent/v1/sessions/{session_id}/events",
17238
17279
  streaming: "no",
@@ -29934,7 +29975,7 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
29934
29975
  resource: "devops.units",
29935
29976
  method: "push",
29936
29977
  summary: "Push a unit's branch",
29937
- 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.",
29978
+ 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.",
29938
29979
  http: "POST",
29939
29980
  path: "/devops/v1/units/{id}:push",
29940
29981
  streaming: "no",
@@ -30270,7 +30311,7 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
30270
30311
  resource: "file.uploads",
30271
30312
  method: "createSigned",
30272
30313
  summary: "Create a one-time upload URL",
30273
- description: "Upload a local file of up to 20 GiB from a coding agent without sending bytes through the model. Provide filename (the stored basename), exact byte count and MIME type. Up to 104857600 bytes, PUT the file to url with curl -T photo.png -H 'Content-Type: image/png' '<url>'; success returns 201 with the file object, and reuse returns 410 CAPABILITY_USED. Above that threshold, split the file into part_size chunks (default 64000000 bytes) and PUT each chunk to its numbered parts[].url in any order; an interrupted client GETs status_url to see the received parts and resends only what is missing, then POSTs complete_url without a body. Part PUTs return 200; completion returns 201 with the file object, including its state, or 400 if a part is missing. A processing file can be polled with files.retrieve until active. Identical part bytes may be retried; changed bytes at the same number return 400. Completion reuse returns 410 CAPABILITY_USED. Each PUT requires the exact signed Content-Length; single-PUT Content-Type must match content_type or be omitted. Expired, revoked, invalid, wrong-action or cross-organization URLs return 404. URL lifetime defaults to 900 seconds for single PUT or 604800 (7 days) for multipart, at most 604800; all multipart URLs, including status_url, share an expiry. Multipart creation reserves storage quota. Issuance requires the same unscoped credential as direct file creation. Each issuance creates a new upload and is not idempotent. Example body: {\"filename\":\"photo.png\",\"bytes\":2048,\"content_type\":\"image/png\"}.",
30314
+ description: "Upload a local file of up to 20 GiB from a coding agent without sending bytes through the model. Provide filename (the stored basename), exact byte count and MIME type. Up to 104857600 bytes, PUT the file to url with curl -T photo.png -H 'Content-Type: image/png' '<url>'; success returns 201 with the file object, and reuse returns 410 CAPABILITY_USED. Above that threshold, split the file into part_size chunks (default 64000000 bytes) and PUT each chunk to its numbered parts[].url in any order; an interrupted client GETs status_url to see the received parts and resends only what is missing, then POSTs complete_url without a body. Part PUTs return 200; completion returns 201 with the file object, including its state, or 400 if a part is missing. A processing file can be polled with files.retrieve until active. Identical part bytes may be retried; changed bytes at the same number return 400. Completion reuse returns 410 CAPABILITY_USED. Each PUT requires the exact signed Content-Length; single-PUT Content-Type must match content_type or be omitted. Expired, revoked, invalid or cross-organization URLs return 404, and so does a link whose upload record no longer exists. A URL that is authentic but names another action returns 403 CAPABILITY_MISMATCH: a status link posted to complete_url answers it, and so does a completion link fetched as status_url. URL lifetime defaults to 900 seconds for single PUT or 604800 (7 days) for multipart, at most 604800; all multipart URLs, including status_url, share an expiry. Multipart creation reserves storage quota. Issuance requires the same unscoped credential as direct file creation. Each issuance creates a new upload and is not idempotent. Example body: {\"filename\":\"photo.png\",\"bytes\":2048,\"content_type\":\"image/png\"}.",
30274
30315
  http: "POST",
30275
30316
  path: "/file/v1/uploads/signed",
30276
30317
  streaming: "no",
@@ -40640,16 +40681,18 @@ for more details.`
40640
40681
  type: "string",
40641
40682
  enum: [
40642
40683
  "file",
40643
- "artifact"
40684
+ "artifact",
40685
+ "canvas",
40686
+ "media_asset"
40644
40687
  ],
40645
40688
  required: false,
40646
- description: "Only shares of this object type; file is the only type that creates today."
40689
+ description: "Only shares of this object type; file, canvas and media_asset create today."
40647
40690
  },
40648
40691
  {
40649
40692
  name: "resource_id",
40650
40693
  type: "string",
40651
40694
  required: false,
40652
- description: "Only shares of the object with this id, for example a file id from the File API; combine with resource_type."
40695
+ 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."
40653
40696
  },
40654
40697
  {
40655
40698
  name: "status",
@@ -47221,6 +47264,19 @@ var getAgentConsolidation = (options) => (options.client ?? client).get({
47221
47264
  url: "/agent/v1/agents/{agent_id}/consolidations/{consolidation_id}",
47222
47265
  ...options
47223
47266
  });
47267
+ var listAgentInboxLetters = (options) => (options.client ?? client).get({
47268
+ security: [{
47269
+ key: "BearerAuth",
47270
+ scheme: "bearer",
47271
+ type: "http"
47272
+ }, {
47273
+ key: "ApiKeyAuth",
47274
+ name: "X-API-Key",
47275
+ type: "apiKey"
47276
+ }],
47277
+ url: "/agent/v1/agents/{agent_id}/inbox/letters",
47278
+ ...options
47279
+ });
47224
47280
  var applyAgentVersion = (options) => (options.client ?? client).post({
47225
47281
  security: [{
47226
47282
  key: "BearerAuth",
@@ -58035,6 +58091,11 @@ function createAgent(transport) {
58035
58091
  send: bind(transport, sendAgentEvents),
58036
58092
  stream: bindStream(transport, streamAgentEvents)
58037
58093
  },
58094
+ inbox: {
58095
+ letters: {
58096
+ list: bind(transport, listAgentInboxLetters)
58097
+ }
58098
+ },
58038
58099
  list: bind(transport, agentsList),
58039
58100
  retrieve: bind(transport, agentsRetrieve),
58040
58101
  retrieveAppearance: bind(transport, getAgentAppearance),
@@ -61385,7 +61446,7 @@ function help(commands, prefix, command) {
61385
61446
  ...[...operationOptions(command.op), ...bodyDataOption(command.op), ...globalOptions].map((s) => ` ${describeOption(s, s.required && fieldRequired(command.op, s, s.location ?? "query"))}`),
61386
61447
  ...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" : ""})`) ?? [],
61387
61448
  " -h is an alias of --help",
61388
- "PRAXIS_ENV=develop|production (default: develop); no --env option.",
61449
+ "PRAXIS_ENV=production|develop (default: production; develop must be named); no --env option.",
61389
61450
  "",
61390
61451
  "Examples:",
61391
61452
  ` ${example(command)}`
@@ -61397,7 +61458,7 @@ function help(commands, prefix, command) {
61397
61458
  "Global options:",
61398
61459
  ...globalOptions.map((s) => ` ${describeOption(s)}`),
61399
61460
  " -h is an alias of --help",
61400
- "PRAXIS_ENV=develop|production (default: develop); no --env option.",
61461
+ "PRAXIS_ENV=production|develop (default: production; develop must be named); no --env option.",
61401
61462
  ""
61402
61463
  ];
61403
61464
  const sample = matching.find((c) => c.words.at(-1) === "list") ?? matching[0];
@@ -61885,6 +61946,41 @@ var workflows = [
61885
61946
  platform: "praxis api devops project change create — the platform creates and names a Change; the CLI only lands its branch (ADR-125 §5).",
61886
61947
  docs: "https://docs.deepraxis.com/docs/cli"
61887
61948
  },
61949
+ {
61950
+ words: ["agent", "events", "wait"],
61951
+ usage: "agent events wait [--timeout <seconds>]",
61952
+ 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.",
61953
+ example: "PRAXIS_ASSUME_AGENT=R1M9TQ2X praxis agent events wait",
61954
+ network: "online"
61955
+ },
61956
+ {
61957
+ words: ["agent", "memory"],
61958
+ usage: "agent memory [--hook SessionStart|UserPromptSubmit]",
61959
+ 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.",
61960
+ example: "praxis agent memory",
61961
+ network: "online"
61962
+ },
61963
+ {
61964
+ words: ["agent", "recall"],
61965
+ usage: "agent recall [--words <w,w>] [--handles <id,id>]",
61966
+ 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.",
61967
+ example: "praxis agent recall --words 章程,运维部",
61968
+ network: "online"
61969
+ },
61970
+ {
61971
+ words: ["agent", "remember"],
61972
+ usage: "agent remember --text <experience> [--about <id,id>]",
61973
+ 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.",
61974
+ example: 'praxis agent remember --text "Sean 定了副总裁用钩子载入认知"',
61975
+ network: "online"
61976
+ },
61977
+ {
61978
+ words: ["agent", "events", "channel"],
61979
+ usage: "agent events channel",
61980
+ 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.",
61981
+ example: "claude --dangerously-load-development-channels plugin:assume-agent@deepraxis",
61982
+ network: "online"
61983
+ },
61888
61984
  { 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"' },
61889
61985
  { words: ["skill"], usage: "skill [--install <dir>]", summary: "Print the AI skill, or write <dir>/praxis-cli/SKILL.md." },
61890
61986
  {
@@ -61954,7 +62050,7 @@ function workflowHelp(workflow, options) {
61954
62050
  "Options:",
61955
62051
  ...[...options, ...globalOptions].map((s) => ` ${describeOption(s)}`),
61956
62052
  " -h is an alias of --help",
61957
- "PRAXIS_ENV=develop|production (default: develop); no --env option.",
62053
+ "PRAXIS_ENV=production|develop (default: production; develop must be named); no --env option.",
61958
62054
  ...workflow.requires === "checkout" ? [`Requires: ${CHECKOUT_REQUIREMENT}`] : [],
61959
62055
  ...workflow.notes?.length ? ["", ...workflow.notes] : [],
61960
62056
  ...workflow.network ? ["", `Network: ${workflow.network}`] : [],
@@ -65971,6 +66067,30 @@ function bunTestRun(packagePath, code, output) {
65971
66067
  }
65972
66068
 
65973
66069
  // src/commands/devops-test.ts
66070
+ import { spawn as spawn4 } from "node:child_process";
66071
+ var CACHE_OFF_REEXEC_ENV = "PRAXIS_DEVOPS_TEST_CACHE_OFF";
66072
+ function needsCacheOffReexec(env) {
66073
+ return env.BUN_RUNTIME_TRANSPILER_CACHE_PATH !== "0" && !env[CACHE_OFF_REEXEC_ENV];
66074
+ }
66075
+ function isDevopsTestRun(words) {
66076
+ return words.join(" ") === "devops test";
66077
+ }
66078
+ function spawnInherit(cmd, args, options) {
66079
+ return new Promise((resolveCode) => {
66080
+ const child = spawn4(cmd, [...args], { cwd: options.cwd, env: options.env, stdio: "inherit" });
66081
+ child.once("error", (error) => {
66082
+ console.error(error instanceof Error ? error.message : String(error));
66083
+ resolveCode(1);
66084
+ });
66085
+ child.once("close", (code) => resolveCode(code ?? 1));
66086
+ });
66087
+ }
66088
+ function reexecWithCacheOff(options = {}) {
66089
+ return (options.spawn ?? spawnInherit)(process.execPath, options.argv ?? process.argv.slice(1), {
66090
+ cwd: options.cwd ?? process.cwd(),
66091
+ env: { ...options.env ?? process.env, BUN_RUNTIME_TRANSPILER_CACHE_PATH: "0", [CACHE_OFF_REEXEC_ENV]: "1" }
66092
+ });
66093
+ }
65974
66094
  async function devopsTest(flags, paths, ports) {
65975
66095
  const plan = planTest(flags, paths);
65976
66096
  if (plan.mode.kind === "affected")
@@ -66241,8 +66361,8 @@ async function localEngine(cwd) {
66241
66361
  })
66242
66362
  };
66243
66363
  }
66244
- async function localCheckout(cwd, spawn4) {
66245
- const git2 = (args) => spawn4("git", [...args], { cwd });
66364
+ async function localCheckout(cwd, spawn5) {
66365
+ const git2 = (args) => spawn5("git", [...args], { cwd });
66246
66366
  const required = async (args) => {
66247
66367
  const result = await git2(args);
66248
66368
  if (result.code !== 0)
@@ -66293,7 +66413,7 @@ async function localCheckout(cwd, spawn4) {
66293
66413
  await walk(packagePath);
66294
66414
  return files;
66295
66415
  },
66296
- runTests: (packagePath, files) => spawn4("nice", ["-n", "10", "bun", "test", ...files], { cwd: packagePath })
66416
+ runTests: (packagePath, files) => spawn5("nice", ["-n", "10", "bun", "test", ...files], { cwd: packagePath })
66297
66417
  };
66298
66418
  }
66299
66419
  async function withEngineStdoutOnStderr(body) {
@@ -69445,6 +69565,8 @@ var warningLine = (warning) => {
69445
69565
  return `${warning.code}: ${warning.ref} at ${warning.nodeId}`;
69446
69566
  case "FRAME_NOT_FOUND":
69447
69567
  return `${warning.code}: ${warning.id}`;
69568
+ case "IMAGE_FILE_NOT_FOUND":
69569
+ return `${warning.code}: ${warning.url} (the platform holds no such file) at ${warning.nodeId}`;
69448
69570
  default:
69449
69571
  return `${warning.code}: ${warning.url}`;
69450
69572
  }
@@ -69552,6 +69674,537 @@ async function canvasImport(args, ports) {
69552
69674
  return 0;
69553
69675
  }
69554
69676
 
69677
+ // src/commands/events-wait.ts
69678
+ var DEFAULT_AGENT = "R1M9TQ2X";
69679
+ var BASE_BACKOFF_MS = 1000;
69680
+ var MAX_BACKOFF_MS = 60000;
69681
+ var NOTICE_NAMED = 5;
69682
+ var ANNOUNCED_KEEP = 500;
69683
+ function assumeAgentOf(env) {
69684
+ return env.PRAXIS_ASSUME_AGENT?.trim() || DEFAULT_AGENT;
69685
+ }
69686
+ function sessionOf(raw) {
69687
+ if (raw === undefined)
69688
+ return null;
69689
+ const session = raw.trim();
69690
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(session))
69691
+ throw new Error("--session takes the Claude Code session id (letters, digits, - and _)");
69692
+ return session;
69693
+ }
69694
+ var keyPart = (part) => part.replace(/[^A-Za-z0-9_-]/g, "_");
69695
+ function waitKeyOf(env, agent, session) {
69696
+ return [env, agent, ...session === null ? [] : [session]].map(keyPart).join("-");
69697
+ }
69698
+ function pidOf(raw) {
69699
+ const pid = raw === null ? NaN : Number(raw.trim());
69700
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
69701
+ }
69702
+ function lockDecision(recorded, self, probe) {
69703
+ if (recorded === null || recorded === self || probe === null || !probe.alive)
69704
+ return { kind: "take" };
69705
+ if (!/events\s+wait/.test(probe.command))
69706
+ return { kind: "take" };
69707
+ if (probe.ppid === 1)
69708
+ return { kind: "replace", pid: recorded };
69709
+ return { kind: "refuse", pid: recorded };
69710
+ }
69711
+ function alreadyWaitingNotice(pid) {
69712
+ return `本会话已有 praxis agent events wait 在后台等待(pid ${pid}),不用再启动。`;
69713
+ }
69714
+ async function acquireWaitLock(ports) {
69715
+ for (let attempt = 0;attempt < 3; attempt++) {
69716
+ const recorded = pidOf(await ports.readPid());
69717
+ if (recorded === null) {
69718
+ if (await ports.createPid(String(ports.self)))
69719
+ return null;
69720
+ continue;
69721
+ }
69722
+ const decision = lockDecision(recorded, ports.self, await ports.probe(recorded));
69723
+ if (decision.kind === "refuse")
69724
+ return decision.pid;
69725
+ if (decision.kind === "replace")
69726
+ ports.terminate(decision.pid);
69727
+ await ports.replacePid(String(ports.self));
69728
+ const holder = pidOf(await ports.readPid());
69729
+ return holder === ports.self || holder === null ? null : holder;
69730
+ }
69731
+ return pidOf(await ports.readPid());
69732
+ }
69733
+ function timeoutMsOf(raw) {
69734
+ if (raw === undefined)
69735
+ return null;
69736
+ const seconds = Number(raw);
69737
+ if (!/^\d+(\.\d+)?$/.test(raw.trim()) || !Number.isFinite(seconds) || seconds <= 0)
69738
+ throw new Error("--timeout takes a positive number of seconds");
69739
+ return Math.round(seconds * 1000);
69740
+ }
69741
+ function backoffMs(failures) {
69742
+ if (failures <= 0)
69743
+ return 0;
69744
+ return Math.min(MAX_BACKOFF_MS, BASE_BACKOFF_MS * 2 ** Math.min(failures - 1, 16));
69745
+ }
69746
+ function inboxLettersUrl(apiUrl, agent) {
69747
+ return `${apiUrl}/agent/v1/agents/${encodeURIComponent(agent)}/inbox/letters?unread=true&limit=20`;
69748
+ }
69749
+ function eventsStreamUrl(apiUrl, agent) {
69750
+ return `${apiUrl}/agent/v1/agents/${encodeURIComponent(agent)}/events/stream`;
69751
+ }
69752
+ function streamHeaders(auth, lastEventId) {
69753
+ return { ...auth, Accept: "text/event-stream", ...lastEventId === null ? {} : { "Last-Event-ID": lastEventId } };
69754
+ }
69755
+ function lettersOf(body) {
69756
+ const value = body;
69757
+ if (!value || typeof value.unread !== "number" || !Array.isArray(value.letters))
69758
+ throw new Error("letters answer is not { unread, letters }");
69759
+ const letters = value.letters.filter((letter) => typeof letter === "object" && letter !== null && typeof letter.id === "string" && typeof letter.summary === "string");
69760
+ return { unread: value.unread, letters };
69761
+ }
69762
+ function feedSse(buffer, chunk) {
69763
+ const text2 = (buffer + chunk).replace(/\r\n?/g, `
69764
+ `);
69765
+ const blocks = text2.split(`
69766
+
69767
+ `);
69768
+ const rest = blocks.pop() ?? "";
69769
+ const frames = [];
69770
+ for (const block of blocks) {
69771
+ let event, id;
69772
+ const data = [];
69773
+ for (const line of block.split(`
69774
+ `)) {
69775
+ if (line === "" || line.startsWith(":"))
69776
+ continue;
69777
+ const colon = line.indexOf(":");
69778
+ const field = colon < 0 ? line : line.slice(0, colon);
69779
+ const value = colon < 0 ? "" : line.slice(colon + 1).replace(/^ /, "");
69780
+ if (field === "data")
69781
+ data.push(value);
69782
+ else if (field === "event")
69783
+ event = value;
69784
+ else if (field === "id")
69785
+ id = value;
69786
+ }
69787
+ if (data.length)
69788
+ frames.push({ ...event === undefined ? {} : { event }, ...id === undefined ? {} : { id }, data: data.join(`
69789
+ `) });
69790
+ }
69791
+ return { buffer: rest, frames };
69792
+ }
69793
+ var text2 = (value) => typeof value === "string" && value !== "";
69794
+ function wakeOf(frame) {
69795
+ let event;
69796
+ try {
69797
+ event = JSON.parse(frame.data);
69798
+ } catch {
69799
+ return null;
69800
+ }
69801
+ if (typeof event !== "object" || event === null)
69802
+ return null;
69803
+ if (event.type === "inbox.letter_delivered" && text2(event.letter_id) && typeof event.summary === "string")
69804
+ return { kind: "letter", letter: {
69805
+ id: event.letter_id,
69806
+ sender: typeof event.sender === "string" ? event.sender : "",
69807
+ ...text2(event.sender_name) ? { sender_name: event.sender_name } : {},
69808
+ summary: event.summary,
69809
+ thread: typeof event.thread === "string" ? event.thread : null,
69810
+ create_time: typeof event.create_time === "string" ? event.create_time : ""
69811
+ } };
69812
+ if (event.type === "cognition.ritual_held" && text2(event.title))
69813
+ return { kind: "ritual", ritual: {
69814
+ ritual: text2(event.ritual) ? event.ritual : "",
69815
+ owner: text2(event.owner) ? event.owner : "",
69816
+ title: event.title,
69817
+ engram: text2(event.engram) ? event.engram : ""
69818
+ } };
69819
+ return null;
69820
+ }
69821
+ function ritualNotice(ritual) {
69822
+ const origin = [ritual.owner, ritual.ritual].filter(Boolean).join(" 的仪式 ");
69823
+ return `你获得了一段新记忆:「${ritual.title}」${origin ? `(${origin}${ritual.engram ? `,${ritual.engram}` : ""})` : ""}。处理完再在后台运行 praxis agent events wait。`;
69824
+ }
69825
+ function retryableStatus(status) {
69826
+ return status >= 500 || status === 408 || status === 429;
69827
+ }
69828
+ function planNotice(page, announced) {
69829
+ const seen = new Set(announced);
69830
+ const fresh = page.letters.filter((letter) => !seen.has(letter.id));
69831
+ if (!fresh.length)
69832
+ return { announced };
69833
+ const named = fresh.slice(0, NOTICE_NAMED).map((letter) => `${letter.sender_name || letter.sender}:${letter.summary}(${letter.id})`);
69834
+ const more = fresh.length > NOTICE_NAMED ? `;另有 ${fresh.length - NOTICE_NAMED} 封` : "";
69835
+ const notice = `你有 ${fresh.length} 封新信:${named.join(";")}${more}。用 praxis_assume_inbox(action "read")读取并处理,处理完再在后台运行 praxis agent events wait。`;
69836
+ const next = [...announced, ...fresh.map((letter) => letter.id)];
69837
+ return { notice, announced: next.length > ANNOUNCED_KEEP ? next.slice(next.length - ANNOUNCED_KEEP) : next };
69838
+ }
69839
+ function waitStateOf(raw) {
69840
+ if (raw === null)
69841
+ return { announced: [], lastEventId: null };
69842
+ try {
69843
+ const value = JSON.parse(raw);
69844
+ return {
69845
+ announced: Array.isArray(value.announced) ? value.announced.filter((id) => typeof id === "string") : [],
69846
+ lastEventId: typeof value.last_event_id === "string" && /^\d+$/.test(value.last_event_id) ? value.last_event_id : null
69847
+ };
69848
+ } catch {
69849
+ return { announced: [], lastEventId: null };
69850
+ }
69851
+ }
69852
+ function waitStateText(state) {
69853
+ return JSON.stringify({ announced: state.announced, ...state.lastEventId === null ? {} : { last_event_id: state.lastEventId } });
69854
+ }
69855
+ var message = (error) => error instanceof Error ? error.message : String(error);
69856
+ async function runEventsWait(ports) {
69857
+ const stop = new AbortController;
69858
+ let timedOut = false;
69859
+ const timer = ports.timeoutMs === null ? undefined : setTimeout(() => {
69860
+ timedOut = true;
69861
+ stop.abort();
69862
+ }, ports.timeoutMs);
69863
+ const state = await ports.readState();
69864
+ let announced = state.announced;
69865
+ let lastEventId = state.lastEventId;
69866
+ const announceLetters = async (page) => {
69867
+ const planned = planNotice(page, announced);
69868
+ if (!planned.notice)
69869
+ return false;
69870
+ announced = planned.announced;
69871
+ await ports.writeState({ announced, lastEventId });
69872
+ ports.print(planned.notice);
69873
+ return true;
69874
+ };
69875
+ const announce = async () => announceLetters(await ports.fetchLetters());
69876
+ try {
69877
+ try {
69878
+ if (await announce())
69879
+ return 0;
69880
+ } catch (error) {
69881
+ ports.log(`praxis agent events wait: reading letters failed: ${message(error)}`);
69882
+ }
69883
+ ports.log(`praxis agent events wait: waiting for letters to assume agent ${ports.agent}`);
69884
+ let failures = 0;
69885
+ while (!stop.signal.aborted) {
69886
+ if (failures)
69887
+ await ports.sleep(backoffMs(failures), stop.signal);
69888
+ if (stop.signal.aborted)
69889
+ break;
69890
+ try {
69891
+ const opened = await ports.openStream(stop.signal, lastEventId);
69892
+ if (opened.status < 200 || opened.status >= 300 || !opened.chunks) {
69893
+ if (!retryableStatus(opened.status)) {
69894
+ ports.log(`praxis agent events wait: the event stream was refused (HTTP ${opened.status}${opened.reason ? `: ${opened.reason}` : ""})`);
69895
+ return 1;
69896
+ }
69897
+ throw new Error(`HTTP ${opened.status}`);
69898
+ }
69899
+ if (await announce())
69900
+ return 0;
69901
+ if (failures)
69902
+ ports.log("praxis agent events wait: event stream reconnected");
69903
+ failures = 0;
69904
+ let buffer = "";
69905
+ for await (const chunk of opened.chunks) {
69906
+ const fed = feedSse(buffer, chunk);
69907
+ buffer = fed.buffer;
69908
+ for (const frame of fed.frames) {
69909
+ const wake = wakeOf(frame);
69910
+ if (wake !== null && frame.id !== undefined)
69911
+ lastEventId = frame.id;
69912
+ if (wake?.kind === "letter" && await announceLetters({ unread: 1, letters: [wake.letter] }))
69913
+ return 0;
69914
+ if (wake?.kind === "ritual") {
69915
+ await ports.writeState({ announced, lastEventId });
69916
+ ports.print(ritualNotice(wake.ritual));
69917
+ return 0;
69918
+ }
69919
+ }
69920
+ }
69921
+ throw new Error("the event stream ended");
69922
+ } catch (error) {
69923
+ if (stop.signal.aborted)
69924
+ break;
69925
+ failures += 1;
69926
+ ports.log(`praxis agent events wait: ${message(error)} (${failures} in a row, reconnecting in ${backoffMs(failures) / 1000}s)`);
69927
+ }
69928
+ }
69929
+ if (timedOut)
69930
+ ports.print(`${(ports.timeoutMs ?? 0) / 1000} 秒内没有新信。需要继续等待时再在后台运行 praxis agent events wait。`);
69931
+ return 0;
69932
+ } finally {
69933
+ if (timer)
69934
+ clearTimeout(timer);
69935
+ stop.abort();
69936
+ }
69937
+ }
69938
+
69939
+ // src/commands/events-channel.ts
69940
+ var CHANNEL_SOURCE = "assume-agent";
69941
+ var SERVER_NAME = "assume-channel";
69942
+ var DEFAULT_PROTOCOL_VERSION = "2025-06-18";
69943
+ var BACKLOG_NAMED = 5;
69944
+ function channelInstructions(agent) {
69945
+ return [
69946
+ `Events from your Praxis assume agent ${agent} arrive as <channel source="${CHANNEL_SOURCE}" kind="letter" letter_id="…" sender="…">.`,
69947
+ '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.',
69948
+ 'kind="ritual": the agent was given a new memory (a ritual was held); its knowledge is refreshed, nothing to reply to.',
69949
+ "The channel is one-way: answer through the praxis_assume_* tools, not back through the channel."
69950
+ ].join(`
69951
+ `);
69952
+ }
69953
+ function initializeResult(params, agent) {
69954
+ const asked = params?.protocolVersion;
69955
+ return {
69956
+ protocolVersion: typeof asked === "string" ? asked : DEFAULT_PROTOCOL_VERSION,
69957
+ capabilities: { experimental: { "claude/channel": {} } },
69958
+ serverInfo: { name: SERVER_NAME, version: "0.1.0" },
69959
+ instructions: channelInstructions(agent)
69960
+ };
69961
+ }
69962
+ function replyTo(message2, agent) {
69963
+ if (message2.id === undefined || message2.id === null || typeof message2.method !== "string")
69964
+ return null;
69965
+ const reply = (body) => ({ jsonrpc: "2.0", id: message2.id, ...body });
69966
+ switch (message2.method) {
69967
+ case "initialize":
69968
+ return reply({ result: initializeResult(message2.params, agent) });
69969
+ case "ping":
69970
+ return reply({ result: {} });
69971
+ default:
69972
+ return reply({ error: { code: -32601, message: `Method not found: ${message2.method}` } });
69973
+ }
69974
+ }
69975
+ var sender = (letter) => letter.sender_name || letter.sender;
69976
+ var readHint = 'Read it with praxis_assume_inbox (action "read").';
69977
+ var frame = (content, meta) => ({ jsonrpc: "2.0", method: "notifications/claude/channel", params: { content, meta } });
69978
+ function letterNotification(letter) {
69979
+ return frame(`${sender(letter)}: ${letter.summary}
69980
+ ${readHint}`, { kind: "letter", letter_id: letter.id, sender: letter.sender, ...letter.sender_name ? { sender_name: letter.sender_name } : {} });
69981
+ }
69982
+ function backlogNotification(letters) {
69983
+ const named = letters.slice(0, BACKLOG_NAMED).map((letter) => `${sender(letter)}: ${letter.summary} (${letter.id})`);
69984
+ const more = letters.length > BACKLOG_NAMED ? `; ${letters.length - BACKLOG_NAMED} more` : "";
69985
+ return frame(`${letters.length} unread letter(s) waiting: ${named.join("; ")}${more}
69986
+ ${readHint}`, { kind: "letter", letter_id: letters[0].id, sender: letters[0].sender, count: String(letters.length) });
69987
+ }
69988
+ function ritualNotification(ritual) {
69989
+ 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 } : {} });
69990
+ }
69991
+ async function runChannel(ports) {
69992
+ const stop = new AbortController;
69993
+ const seen = new Set;
69994
+ let lastEventId = null;
69995
+ let follower = null;
69996
+ const fresh = (letters) => letters.filter((letter) => !seen.has(letter.id) && (seen.add(letter.id), true));
69997
+ const catchUp = async () => {
69998
+ const letters = fresh((await ports.fetchLetters()).letters);
69999
+ if (letters.length)
70000
+ ports.send(backlogNotification(letters));
70001
+ };
70002
+ const follow = async () => {
70003
+ let failures = 0;
70004
+ while (!stop.signal.aborted) {
70005
+ if (failures)
70006
+ await ports.sleep(backoffMs(failures), stop.signal);
70007
+ if (stop.signal.aborted)
70008
+ break;
70009
+ try {
70010
+ const opened = await ports.openStream(stop.signal, lastEventId);
70011
+ if (opened.status < 200 || opened.status >= 300 || !opened.chunks) {
70012
+ if (!retryableStatus(opened.status)) {
70013
+ ports.log(`assume-channel: the event stream was refused (HTTP ${opened.status}${opened.reason ? `: ${opened.reason}` : ""})`);
70014
+ return;
70015
+ }
70016
+ throw new Error(`HTTP ${opened.status}`);
70017
+ }
70018
+ try {
70019
+ await catchUp();
70020
+ } catch (error) {
70021
+ ports.log(`assume-channel: reading letters failed: ${error instanceof Error ? error.message : error}`);
70022
+ }
70023
+ if (failures)
70024
+ ports.log("assume-channel: event stream reconnected");
70025
+ failures = 0;
70026
+ let buffer2 = "";
70027
+ for await (const chunk of opened.chunks) {
70028
+ const fed = feedSse(buffer2, chunk);
70029
+ buffer2 = fed.buffer;
70030
+ for (const raw of fed.frames) {
70031
+ const wake = wakeOf(raw);
70032
+ if (wake === null)
70033
+ continue;
70034
+ if (raw.id !== undefined)
70035
+ lastEventId = raw.id;
70036
+ if (wake.kind === "letter") {
70037
+ if (fresh([wake.letter]).length)
70038
+ ports.send(letterNotification(wake.letter));
70039
+ } else
70040
+ ports.send(ritualNotification(wake.ritual));
70041
+ }
70042
+ }
70043
+ throw new Error("the event stream ended");
70044
+ } catch (error) {
70045
+ if (stop.signal.aborted)
70046
+ break;
70047
+ failures += 1;
70048
+ ports.log(`assume-channel: ${error instanceof Error ? error.message : error} (${failures} in a row, reconnecting in ${backoffMs(failures) / 1000}s)`);
70049
+ }
70050
+ }
70051
+ };
70052
+ let buffer = "";
70053
+ const handle = (line) => {
70054
+ if (!line.trim())
70055
+ return;
70056
+ let message2;
70057
+ try {
70058
+ message2 = JSON.parse(line);
70059
+ } catch {
70060
+ ports.log("assume-channel: ignored a line that is not JSON");
70061
+ return;
70062
+ }
70063
+ const reply = replyTo(message2, ports.agent);
70064
+ if (reply)
70065
+ ports.send(reply);
70066
+ if (message2.method === "notifications/initialized" && follower === null)
70067
+ follower = follow();
70068
+ };
70069
+ for await (const chunk of ports.input) {
70070
+ buffer += chunk;
70071
+ const lines = buffer.split(`
70072
+ `);
70073
+ buffer = lines.pop() ?? "";
70074
+ for (const line of lines)
70075
+ handle(line);
70076
+ }
70077
+ handle(buffer);
70078
+ stop.abort();
70079
+ await follower;
70080
+ return 0;
70081
+ }
70082
+
70083
+ // src/commands/agent-memory.ts
70084
+ var MEMORY_TOOL = "praxis_assume_memory";
70085
+ var RECALL_TOOL = "praxis_assume_recall";
70086
+ var REMEMBER_TOOL = "praxis_assume_remember";
70087
+ function mcpUrl(apiUrl, agent) {
70088
+ return `${apiUrl}/agent/v1/agents/${encodeURIComponent(agent)}/mcp`;
70089
+ }
70090
+ function rpcAnswerOf(body, id) {
70091
+ const candidates2 = body.trimStart().startsWith("{") ? [body] : body.split(`
70092
+ `).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim());
70093
+ for (const candidate of candidates2) {
70094
+ try {
70095
+ const parsed = JSON.parse(candidate);
70096
+ if (parsed.id === id)
70097
+ return parsed;
70098
+ } catch {}
70099
+ }
70100
+ return null;
70101
+ }
70102
+ function toolTextOf(result) {
70103
+ const value = result;
70104
+ const text3 = (value?.content ?? []).filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text).join(`
70105
+ `).trim();
70106
+ return value?.isError === true ? { ok: false, reason: text3 || "the tool refused" } : { ok: true, text: text3 };
70107
+ }
70108
+ async function callAgentTool(ports, url, name, args, signal) {
70109
+ const base = { ...await ports.headers(), "Content-Type": "application/json", Accept: "application/json, text/event-stream" };
70110
+ const post = (body, session2) => ports.fetch(url, {
70111
+ method: "POST",
70112
+ headers: { ...base, ...session2 === undefined ? {} : { "Mcp-Session-Id": session2 } },
70113
+ body: JSON.stringify(body),
70114
+ ...signal === undefined ? {} : { signal },
70115
+ redirect: "error"
70116
+ });
70117
+ const init = await post({ jsonrpc: "2.0", id: 1, method: "initialize", params: {
70118
+ protocolVersion: "2025-06-18",
70119
+ capabilities: {},
70120
+ clientInfo: { name: "praxis-cli-memory", version: "1" }
70121
+ } });
70122
+ const initBody = await init.text();
70123
+ if (!init.ok)
70124
+ throw new Error(`HTTP ${init.status} on initialize`);
70125
+ const session = init.headers.get("Mcp-Session-Id") ?? undefined;
70126
+ const initAnswer = rpcAnswerOf(initBody, 1);
70127
+ if (initAnswer?.error)
70128
+ throw new Error(initAnswer.error.message ?? "initialize failed");
70129
+ await post({ jsonrpc: "2.0", method: "notifications/initialized" }, session).then((r) => r.text()).catch(() => "");
70130
+ const call3 = await post({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name, arguments: args } }, session);
70131
+ const callBody = await call3.text();
70132
+ if (!call3.ok)
70133
+ throw new Error(`HTTP ${call3.status} on ${name}`);
70134
+ const answer = rpcAnswerOf(callBody, 2);
70135
+ if (answer === null)
70136
+ throw new Error(`no answer from ${name}`);
70137
+ if (answer.error)
70138
+ throw new Error(answer.error.message ?? `${name} failed`);
70139
+ const text3 = toolTextOf(answer.result);
70140
+ if (!text3.ok)
70141
+ throw new Error(text3.reason);
70142
+ return text3.text;
70143
+ }
70144
+ function memoryBodyOf(text3) {
70145
+ return text3.split(`
70146
+ `).filter((line) => {
70147
+ const trimmed = line.trim();
70148
+ return !/^shell: acon_/.test(trimmed) && !/^你有 \d+ 封未读信/.test(trimmed) && !/^You have \d+ unread letter/.test(trimmed);
70149
+ }).join(`
70150
+ `).trim();
70151
+ }
70152
+ function paragraphKey(paragraph) {
70153
+ return paragraph.replace(/\s*\[n\d+\]/g, "").replace(/\s+/g, " ").trim();
70154
+ }
70155
+ function newParagraphs(memory, seen) {
70156
+ const seenKeys = new Set([...seen].map(paragraphKey));
70157
+ return memory.split(/\n{2,}/).map((part) => part.trim()).filter((part) => part !== "" && !seenKeys.has(paragraphKey(part)));
70158
+ }
70159
+ 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">
70160
+ ${body}
70161
+ </memory>`;
70162
+ var MEMORY_CHANGED_FRAME = (body) => `<memory_since_start source="praxis-assume" note="what came to mind since this conversation last read your memory">
70163
+ ${body}
70164
+ </memory_since_start>`;
70165
+ function hookOutput(event, context) {
70166
+ if (context === null || context.trim() === "")
70167
+ return null;
70168
+ return JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: context } });
70169
+ }
70170
+ function hookInputOf(raw) {
70171
+ try {
70172
+ const parsed = JSON.parse(raw);
70173
+ const sessionId = typeof parsed.session_id === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(parsed.session_id) ? parsed.session_id : null;
70174
+ return { sessionId, source: typeof parsed.source === "string" ? parsed.source : null };
70175
+ } catch {
70176
+ return { sessionId: null, source: null };
70177
+ }
70178
+ }
70179
+ async function runMemoryHook(event, input, ports) {
70180
+ try {
70181
+ const memory = memoryBodyOf(await callAgentTool(ports, ports.url, MEMORY_TOOL, {}, AbortSignal.timeout(ports.timeoutMs)));
70182
+ if (memory === "")
70183
+ return null;
70184
+ const all = newParagraphs(memory, new Set);
70185
+ if (event === "SessionStart") {
70186
+ if (input.sessionId !== null)
70187
+ await ports.writeSeen(input.sessionId, all).catch(() => {
70188
+ return;
70189
+ });
70190
+ return hookOutput(event, MEMORY_FRAME(memory));
70191
+ }
70192
+ const seen = input.sessionId === null ? [] : await ports.readSeen(input.sessionId).catch(() => []);
70193
+ const fresh = newParagraphs(memory, new Set(seen));
70194
+ if (fresh.length === 0)
70195
+ return null;
70196
+ if (input.sessionId !== null)
70197
+ await ports.writeSeen(input.sessionId, [...seen, ...fresh]).catch(() => {
70198
+ return;
70199
+ });
70200
+ return hookOutput(event, MEMORY_CHANGED_FRAME(fresh.join(`
70201
+
70202
+ `)));
70203
+ } catch {
70204
+ return null;
70205
+ }
70206
+ }
70207
+
69555
70208
  // src/main.ts
69556
70209
  import { spawnSync } from "node:child_process";
69557
70210
 
@@ -69669,15 +70322,15 @@ class ModelStream {
69669
70322
  finishReason = "unknown";
69670
70323
  usage;
69671
70324
  add(event) {
69672
- const data = streamData(event), message = record(data.message), response = record(data.response);
70325
+ const data = streamData(event), message2 = record(data.message), response = record(data.response);
69673
70326
  this.chunks.push(streamText(event));
69674
70327
  const choices = Array.isArray(data.choices) ? data.choices : [];
69675
- 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;
70328
+ 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;
69676
70329
  if (typeof reason2 === "string" && reason2)
69677
70330
  this.finishReason = reason2;
69678
70331
  else if (["response.completed", "response.incomplete", "response.failed"].includes(String(data.type)))
69679
70332
  this.finishReason = String(data.type).slice("response.".length);
69680
- for (const usage of [message.usage, data.usage, response.usage]) {
70333
+ for (const usage of [message2.usage, data.usage, response.usage]) {
69681
70334
  if (usage !== null && typeof usage === "object" && !Array.isArray(usage))
69682
70335
  this.usage = { ...this.usage, ...record(usage) };
69683
70336
  }
@@ -69742,8 +70395,8 @@ function isSuccess(verb, ctx) {
69742
70395
  }
69743
70396
  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" };
69744
70397
  var deleted = (verb) => /^(delete|remove|purge)(-|$)/.test(verb);
69745
- function width(text2) {
69746
- return [...text2].reduce((sum, ch) => {
70398
+ function width(text3) {
70399
+ return [...text3].reduce((sum, ch) => {
69747
70400
  const cp = ch.codePointAt(0);
69748
70401
  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);
69749
70402
  }, 0);
@@ -69751,13 +70404,13 @@ function width(text2) {
69751
70404
  function truncate(value, size) {
69752
70405
  if (width(value) <= size)
69753
70406
  return value;
69754
- let text2 = "";
70407
+ let text3 = "";
69755
70408
  for (const ch of value) {
69756
- if (width(text2 + ch) > size - 1)
70409
+ if (width(text3 + ch) > size - 1)
69757
70410
  break;
69758
- text2 += ch;
70411
+ text3 += ch;
69759
70412
  }
69760
- return text2 + "…";
70413
+ return text3 + "…";
69761
70414
  }
69762
70415
  function table(items, ctx, paint) {
69763
70416
  const columns = columnsFor(items);
@@ -69790,13 +70443,13 @@ function table(items, ctx, paint) {
69790
70443
  sizes[index]--;
69791
70444
  }
69792
70445
  const line = (row, header) => row.map((v, i) => {
69793
- const text2 = truncate(v, sizes[i]);
69794
- let styled = header ? paint.dim(text2) : text2;
70446
+ const text3 = truncate(v, sizes[i]);
70447
+ let styled = header ? paint.dim(text3) : text3;
69795
70448
  if (!header && ["status", "state"].includes(columns[i])) {
69796
70449
  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;
69797
- styled = color(text2);
70450
+ styled = color(text3);
69798
70451
  }
69799
- return styled + (i === row.length - 1 ? "" : " ".repeat(Math.max(0, sizes[i] - width(text2))));
70452
+ return styled + (i === row.length - 1 ? "" : " ".repeat(Math.max(0, sizes[i] - width(text3))));
69800
70453
  }).join(" ");
69801
70454
  return [line(headers, true), ...rows.map((row) => line(row, false))].join(`
69802
70455
  `) + `
@@ -69895,9 +70548,9 @@ function renderHuman(result, ctx) {
69895
70548
  }
69896
70549
 
69897
70550
  // src/output/agent.ts
69898
- function cell(text2) {
69899
- const chars = [...text2];
69900
- const limited = chars.length > 500 ? chars.slice(0, 500).join("") + `…[+${chars.length - 500} chars, use --json]` : text2;
70551
+ function cell(text3) {
70552
+ const chars = [...text3];
70553
+ const limited = chars.length > 500 ? chars.slice(0, 500).join("") + `…[+${chars.length - 500} chars, use --json]` : text3;
69901
70554
  return limited.replace(/\\/g, "\\\\").replace(/\|/g, "\\|").replace(/\r?\n/g, "<br>").replace(/\r/g, "<br>");
69902
70555
  }
69903
70556
  function renderAgent(result, ctx) {
@@ -69908,9 +70561,9 @@ function renderAgent(result, ctx) {
69908
70561
  if (modelStream(result.op)) {
69909
70562
  if (!result.summary)
69910
70563
  return {};
69911
- const { text: text2, finish_reason, usage } = result.summary;
69912
- return { stdout: `${text2}${text2.endsWith(`
69913
- `) || !text2 ? "" : `
70564
+ const { text: text3, finish_reason, usage } = result.summary;
70565
+ return { stdout: `${text3}${text3.endsWith(`
70566
+ `) || !text3 ? "" : `
69914
70567
  `}finish_reason: ${finish_reason}
69915
70568
  ${usage ? `usage: ${JSON.stringify(usage)}
69916
70569
  ` : ""}` };
@@ -70129,18 +70782,18 @@ function errorInput(error, ctx) {
70129
70782
  const details = candidate !== null && typeof candidate === "object" && !Array.isArray(candidate) ? candidate : undefined;
70130
70783
  const problem = serverProblem(Object.keys(nested).length ? nested : raw);
70131
70784
  const serverText = (value) => typeof value === "string" && value.trim() ? value : undefined;
70132
- let message = error instanceof Error ? error.message : "Unexpected error";
70133
- const prefix = message.match(/^([A-Z][A-Z0-9_]+):\s*/)?.[1];
70785
+ let message2 = error instanceof Error ? error.message : "Unexpected error";
70786
+ const prefix = message2.match(/^([A-Z][A-Z0-9_]+):\s*/)?.[1];
70134
70787
  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");
70135
70788
  let stripped = false;
70136
- while (message.startsWith(`${code}:`)) {
70137
- message = message.slice(code.length + 1).trimStart();
70789
+ while (message2.startsWith(`${code}:`)) {
70790
+ message2 = message2.slice(code.length + 1).trimStart();
70138
70791
  stripped = true;
70139
70792
  }
70140
70793
  if (stripped)
70141
- message = `${humanize(code)}${message ? `: ${message}` : ""}`;
70794
+ message2 = `${humanize(code)}${message2 ? `: ${message2}` : ""}`;
70142
70795
  const status = sdk?.status, request_id = sdk?.requestId;
70143
- message = serverText(problem?.detail) ?? serverText(problem?.title) ?? message;
70796
+ message2 = serverText(problem?.detail) ?? serverText(problem?.title) ?? message2;
70144
70797
  const authFailure = status === 401 || ["NOT_LOGGED_IN", "UNAUTHENTICATED", "TOKEN_REVOKED", "LOGIN_FAILED", "MANAGED_LOGIN_EXPIRED"].includes(code);
70145
70798
  const source = ctx.credentialSource ?? "login";
70146
70799
  let hint3 = genericHint;
@@ -70158,19 +70811,19 @@ function errorInput(error, ctx) {
70158
70811
  hint3 = "Rate limited; retry later.";
70159
70812
  else if (status !== undefined && status >= 500)
70160
70813
  hint3 = `Server error; retry later.${request_id ? ` Request id: ${request_id}.` : ""}`;
70161
- 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 } : {} };
70814
+ 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 } : {} };
70162
70815
  }
70163
70816
 
70164
70817
  // src/output/progress.ts
70165
- function startProgress(ctx, write = (text2) => writeOutput({ stderr: text2 })) {
70818
+ function startProgress(ctx, write = (text3) => writeOutput({ stderr: text3 })) {
70166
70819
  if (ctx.mode !== "human" || !ctx.stderrIsTTY)
70167
70820
  return () => {};
70168
70821
  let interval;
70169
- let shown = false, frame = 0;
70822
+ let shown = false, frame2 = 0;
70170
70823
  const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
70171
70824
  const tick = () => {
70172
70825
  shown = true;
70173
- write(`\r${frames[frame++ % frames.length]} Loading…`);
70826
+ write(`\r${frames[frame2++ % frames.length]} Loading…`);
70174
70827
  };
70175
70828
  const timer = setTimeout(() => {
70176
70829
  tick();
@@ -70188,7 +70841,7 @@ function startProgress(ctx, write = (text2) => writeOutput({ stderr: text2 })) {
70188
70841
  }
70189
70842
 
70190
70843
  // src/main.ts
70191
- var version = "0.3.0-dev.c811f1a";
70844
+ var version = "0.3.0-dev.c81a93f";
70192
70845
  var commands = commandTree(operations);
70193
70846
  var manual = [...workflows.map((w) => w.words), [API_WORD]];
70194
70847
  function route(argv) {
@@ -70270,7 +70923,7 @@ var defaults = {
70270
70923
  return;
70271
70924
  const cmd = process.platform === "darwin" ? ["open", url] : process.platform === "win32" ? ["rundll32", "url.dll,FileProtocolHandler", url] : ["xdg-open", url];
70272
70925
  await new Promise((resolve12, reject) => {
70273
- const child = spawn4(cmd[0], cmd.slice(1), { stdio: "ignore" });
70926
+ const child = spawn5(cmd[0], cmd.slice(1), { stdio: "ignore" });
70274
70927
  child.once("error", reject);
70275
70928
  child.once("close", () => resolve12());
70276
70929
  });
@@ -70279,12 +70932,12 @@ var defaults = {
70279
70932
  wait: (ms) => new Promise((resolve12) => setTimeout(resolve12, ms)),
70280
70933
  render,
70281
70934
  spawn: (cmd, args, options) => new Promise((resolve12, reject) => {
70282
- const child = spawn4(cmd, args, { cwd: options.cwd, stdio: ["ignore", 2, 2] });
70935
+ const child = spawn5(cmd, args, { cwd: options.cwd, stdio: ["ignore", 2, 2] });
70283
70936
  child.once("error", reject);
70284
70937
  child.once("close", (code) => resolve12(code ?? 1));
70285
70938
  }),
70286
70939
  spawnCapture: (cmd, args, options) => new Promise((resolve12, reject) => {
70287
- const child = spawn4(cmd, args, { cwd: options.cwd, stdio: ["ignore", "pipe", "pipe"] });
70940
+ const child = spawn5(cmd, args, { cwd: options.cwd, stdio: ["ignore", "pipe", "pipe"] });
70288
70941
  const chunks = [];
70289
70942
  child.stdout.on("data", (c) => chunks.push(c));
70290
70943
  child.stderr.on("data", (c) => chunks.push(c));
@@ -70367,6 +71020,21 @@ var appOptions = {
70367
71020
  { 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)." },
70368
71021
  { name: "project", type: "string", description: "With --report: the DevOps project id (dvp_…) whose flags the scan is reported into. Required." }
70369
71022
  ],
71023
+ "agent memory": [
71024
+ { 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." }
71025
+ ],
71026
+ "agent recall": [
71027
+ { name: "words", type: "string", repeated: true, description: "Distinctive words to recall by, comma-separated or repeated." },
71028
+ { name: "handles", type: "string", repeated: true, description: "Entry handles or ids from memory to recall, comma-separated or repeated." }
71029
+ ],
71030
+ "agent remember": [
71031
+ { name: "text", type: "string", description: "The experience, in your own words: what happened, who, what was decided and why, what is still open." },
71032
+ { name: "about", type: "string", repeated: true, description: "Ids of entities it is about, comma-separated or repeated." }
71033
+ ],
71034
+ "agent events wait": [
71035
+ { name: "timeout", type: "string", description: "Give up after this many seconds, print that nothing arrived and exit 0 (default: wait until a letter arrives)." },
71036
+ { 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)." }
71037
+ ],
70370
71038
  "canvas import": [
70371
71039
  { name: "name", type: "string", description: "Name for the new canvas (default: the file name without .pen)." },
70372
71040
  { 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." },
@@ -70385,15 +71053,15 @@ function flagPortsFor(ports, context, emit, connect) {
70385
71053
  return {
70386
71054
  mode: context.mode,
70387
71055
  emit,
70388
- human: (text2) => {
71056
+ human: (text3) => {
70389
71057
  if (context.mode === "human")
70390
- emit({ kind: "message", channel: "stdout", text: text2 });
71058
+ emit({ kind: "message", channel: "stdout", text: text3 });
70391
71059
  },
70392
71060
  cwd: ports.cwd,
70393
71061
  readFile: ports.readFile,
70394
71062
  git: async (args) => (await ports.spawnCapture("git", [...args], { cwd: ports.cwd })).output,
70395
71063
  client: connect,
70396
- writeFile: (path, text2) => writeFile5(path, text2, "utf8"),
71064
+ writeFile: (path, text3) => writeFile5(path, text3, "utf8"),
70397
71065
  mkdir: async (path) => {
70398
71066
  await mkdir4(path, { recursive: true });
70399
71067
  },
@@ -70417,9 +71085,9 @@ function toolPortsFor(ports, context, emit) {
70417
71085
  return {
70418
71086
  mode: context.mode,
70419
71087
  emit,
70420
- human: (text2) => {
71088
+ human: (text3) => {
70421
71089
  if (context.mode === "human")
70422
- emit({ kind: "message", channel: "stdout", text: text2 });
71090
+ emit({ kind: "message", channel: "stdout", text: text3 });
70423
71091
  },
70424
71092
  cwd: ports.cwd,
70425
71093
  readFile: ports.readFile,
@@ -70434,7 +71102,7 @@ function toolPortsFor(ports, context, emit) {
70434
71102
  },
70435
71103
  git: (args, cwd) => ports.spawnCapture("git", args, { cwd }),
70436
71104
  run: (cmd, args, cwd) => new Promise((resolve12, reject) => {
70437
- const child = spawn4(cmd, args, { cwd, stdio: "inherit" });
71105
+ const child = spawn5(cmd, args, { cwd, stdio: "inherit" });
70438
71106
  child.once("error", reject);
70439
71107
  child.once("close", (code) => resolve12(code ?? 1));
70440
71108
  }),
@@ -70459,7 +71127,7 @@ async function main3(argv, injected = {}) {
70459
71127
  columns: ports.columns,
70460
71128
  now: ports.now(),
70461
71129
  envVars: { NO_COLOR: ports.env.NO_COLOR, FORCE_COLOR: ports.env.FORCE_COLOR, TERM: ports.env.TERM },
70462
- env: ports.env.PRAXIS_ENV ?? "develop"
71130
+ env: ports.env.PRAXIS_ENV ?? DEFAULT_ENV
70463
71131
  };
70464
71132
  let stopProgress = () => {};
70465
71133
  let quiet = false;
@@ -70729,9 +71397,9 @@ Examples:
70729
71397
  },
70730
71398
  mode: ctx.mode,
70731
71399
  emit,
70732
- human: (text2) => {
71400
+ human: (text3) => {
70733
71401
  if (ctx.mode === "human")
70734
- emit({ kind: "message", channel: "stdout", text: text2 });
71402
+ emit({ kind: "message", channel: "stdout", text: text3 });
70735
71403
  },
70736
71404
  cwd: ports.cwd
70737
71405
  });
@@ -70758,14 +71426,14 @@ Examples:
70758
71426
  }, {
70759
71427
  mode: ctx.mode,
70760
71428
  emit,
70761
- human: (text2) => {
71429
+ human: (text3) => {
70762
71430
  if (ctx.mode === "human")
70763
- emit({ kind: "message", channel: "stdout", text: text2 });
71431
+ emit({ kind: "message", channel: "stdout", text: text3 });
70764
71432
  },
70765
71433
  engine: codeRefactorEngine(),
70766
71434
  hasFile: (path2) => existsSync4(path2),
70767
71435
  readFile: ports.readFile,
70768
- writeFile: (path2, text2) => writeFile5(path2, text2, "utf8"),
71436
+ writeFile: (path2, text3) => writeFile5(path2, text3, "utf8"),
70769
71437
  mkdir: async (path2) => {
70770
71438
  await mkdir4(path2, { recursive: true });
70771
71439
  },
@@ -70782,9 +71450,9 @@ Examples:
70782
71450
  const shellPorts = {
70783
71451
  mode: ctx.mode,
70784
71452
  emit,
70785
- human: (text2) => {
71453
+ human: (text3) => {
70786
71454
  if (ctx.mode === "human")
70787
- emit({ kind: "message", channel: "stdout", text: text2 });
71455
+ emit({ kind: "message", channel: "stdout", text: text3 });
70788
71456
  },
70789
71457
  engine: await repositoryEngine(name, () => localEngine(ports.cwd)),
70790
71458
  ...localFilePorts(ports.cwd)
@@ -70797,9 +71465,9 @@ Examples:
70797
71465
  const testPorts = {
70798
71466
  mode: ctx.mode,
70799
71467
  emit,
70800
- human: (text2) => {
71468
+ human: (text3) => {
70801
71469
  if (ctx.mode === "human")
70802
- emit({ kind: "message", channel: "stdout", text: text2 });
71470
+ emit({ kind: "message", channel: "stdout", text: text3 });
70803
71471
  },
70804
71472
  engine: await repositoryEngine(name, () => localEngine(ports.cwd)),
70805
71473
  checkout: await localCheckout(ports.cwd, (cmd, args, options) => ports.spawnCapture(cmd, args, options))
@@ -70808,9 +71476,9 @@ Examples:
70808
71476
  return await devopsTestReport({ path: parsed.positional[0], id: parsed.flags.id?.[0], upload: Boolean(parsed.flags.upload), project: parsed.flags.project?.[0] }, testPorts, {
70809
71477
  mode: ctx.mode,
70810
71478
  emit,
70811
- human: (text2) => {
71479
+ human: (text3) => {
70812
71480
  if (ctx.mode === "human")
70813
- emit({ kind: "message", channel: "stdout", text: text2 });
71481
+ emit({ kind: "message", channel: "stdout", text: text3 });
70814
71482
  },
70815
71483
  root: async () => await checkoutRoot(ports.cwd, ports.readFile),
70816
71484
  readFile: ports.readFile,
@@ -70840,9 +71508,9 @@ Examples:
70840
71508
  git: (args) => ports.spawnCapture("git", args, { cwd: ports.cwd }),
70841
71509
  mode: ctx.mode,
70842
71510
  emit,
70843
- human: (text2) => {
71511
+ human: (text3) => {
70844
71512
  if (ctx.mode === "human")
70845
- emit({ kind: "message", channel: "stdout", text: text2 });
71513
+ emit({ kind: "message", channel: "stdout", text: text3 });
70846
71514
  }
70847
71515
  });
70848
71516
  }
@@ -70892,9 +71560,9 @@ Examples:
70892
71560
  emit({ kind: "object", data: await auth.switchOrganization(parsed.positional[0]) });
70893
71561
  break;
70894
71562
  case "app create": {
70895
- const appPorts = { ...ports, mode: ctx.mode, emit, human: (text2) => {
71563
+ const appPorts = { ...ports, mode: ctx.mode, emit, human: (text3) => {
70896
71564
  if (ctx.mode === "human")
70897
- emit({ kind: "message", channel: "stdout", text: text2 });
71565
+ emit({ kind: "message", channel: "stdout", text: text3 });
70898
71566
  }, random: randomSecret };
70899
71567
  await appCreate({ name: parsed.positional[0], dir: parsed.flags.dir?.[0], template: parsed.flags.template?.[0], install: !parsed.flags["no-install"] }, config.env, appPorts);
70900
71568
  break;
@@ -70923,13 +71591,220 @@ Examples:
70923
71591
  wait: ports.wait,
70924
71592
  mode: ctx.mode,
70925
71593
  emit,
70926
- human: (text2) => {
71594
+ human: (text3) => {
70927
71595
  if (ctx.mode === "human")
70928
- emit({ kind: "message", channel: "stdout", text: text2 });
71596
+ emit({ kind: "message", channel: "stdout", text: text3 });
70929
71597
  },
70930
71598
  cwd: ports.cwd
70931
71599
  });
70932
71600
  }
71601
+ case "agent events channel": {
71602
+ const agent = assumeAgentOf(ports.env);
71603
+ const headers = async () => {
71604
+ const credential = await auth.get(org);
71605
+ return { Authorization: `Bearer ${credential.token}`, ...credential.source === "api-key" ? { "X-API-Key": credential.token } : {} };
71606
+ };
71607
+ const failure2 = (status, body) => `HTTP ${status}${body?.error?.code ? ` ${body.error.code}` : ""}${body?.error?.message ? `: ${String(redact(body.error.message, secrets))}` : ""}`;
71608
+ process.stdin.setEncoding("utf8");
71609
+ return await runChannel({
71610
+ agent,
71611
+ input: process.stdin,
71612
+ send: (frame2) => {
71613
+ process.stdout.write(JSON.stringify(frame2) + `
71614
+ `);
71615
+ },
71616
+ fetchLetters: async () => {
71617
+ const response = await wireFetch(inboxLettersUrl(config.apiUrl, agent), { headers: await headers(), signal: AbortSignal.timeout(30000), redirect: "error" });
71618
+ const body = await response.json().catch(() => null);
71619
+ if (!response.ok)
71620
+ throw new Error(failure2(response.status, body));
71621
+ return lettersOf(body);
71622
+ },
71623
+ openStream: async (signal, lastEventId) => {
71624
+ const response = await wireFetch(eventsStreamUrl(config.apiUrl, agent), { headers: streamHeaders(await headers(), lastEventId), signal, redirect: "error" });
71625
+ if (!response.ok || !response.body) {
71626
+ const body = await response.json().catch(() => null);
71627
+ return { status: response.status, reason: failure2(response.status, body) };
71628
+ }
71629
+ return { status: response.status, chunks: response.body.pipeThrough(new TextDecoderStream) };
71630
+ },
71631
+ sleep: (ms, signal) => new Promise((resolve12) => {
71632
+ const timer = setTimeout(resolve12, ms);
71633
+ signal.addEventListener("abort", () => {
71634
+ clearTimeout(timer);
71635
+ resolve12();
71636
+ }, { once: true });
71637
+ }),
71638
+ log: (line) => {
71639
+ process.stderr.write(String(redact(line, secrets)) + `
71640
+ `);
71641
+ }
71642
+ });
71643
+ }
71644
+ case "agent memory":
71645
+ case "agent recall":
71646
+ case "agent remember": {
71647
+ const agent = assumeAgentOf(ports.env);
71648
+ const mcpPorts = {
71649
+ fetch: (url2, init) => wireFetch(url2, init),
71650
+ headers: async () => {
71651
+ const credential = await auth.get(org);
71652
+ return { Authorization: `Bearer ${credential.token}`, ...credential.source === "api-key" ? { "X-API-Key": credential.token } : {} };
71653
+ }
71654
+ };
71655
+ const url = mcpUrl(config.apiUrl, agent);
71656
+ const hook = parsed.flags.hook?.[0];
71657
+ if (name === "agent memory" && hook !== undefined) {
71658
+ if (hook !== "SessionStart" && hook !== "UserPromptSubmit")
71659
+ throw new UsageError(`--hook takes SessionStart or UserPromptSubmit, not ${hook}`, "Example: praxis agent memory --hook SessionStart");
71660
+ process.stdin.setEncoding("utf8");
71661
+ let raw = "";
71662
+ if (!process.stdin.isTTY)
71663
+ for await (const chunk of process.stdin)
71664
+ raw += chunk;
71665
+ const input = hookInputOf(raw);
71666
+ const seenDir = join12(ports.env.HOME || homedir3(), ".praxis", "cli", "memory-seen");
71667
+ const out = await runMemoryHook(hook, input, {
71668
+ ...mcpPorts,
71669
+ url,
71670
+ timeoutMs: 25000,
71671
+ readSeen: async (id) => JSON.parse(await readFile7(join12(seenDir, `${id}.json`), "utf8")),
71672
+ writeSeen: async (id, paragraphs) => {
71673
+ await mkdir4(seenDir, { recursive: true, mode: 448 });
71674
+ await writeFile5(join12(seenDir, `${id}.json`), JSON.stringify(paragraphs), { mode: 384 });
71675
+ }
71676
+ });
71677
+ if (out !== null)
71678
+ process.stdout.write(out + `
71679
+ `);
71680
+ return 0;
71681
+ }
71682
+ const list = (flag) => (parsed.flags[flag] ?? []).flatMap((value) => value.split(",")).map((value) => value.trim()).filter(Boolean);
71683
+ 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") } : {} } : {};
71684
+ if (name === "agent remember" && String(args.text).trim() === "")
71685
+ throw new UsageError("--text is required", 'Example: praxis agent remember --text "今天定了……"');
71686
+ const tool = name === "agent memory" ? MEMORY_TOOL : name === "agent recall" ? RECALL_TOOL : REMEMBER_TOOL;
71687
+ const text3 = memoryBodyOf(await callAgentTool(mcpPorts, url, tool, args, AbortSignal.timeout(60000)));
71688
+ process.stdout.write(text3 + `
71689
+ `);
71690
+ return 0;
71691
+ }
71692
+ case "agent events wait": {
71693
+ const agent = assumeAgentOf(ports.env);
71694
+ const timeoutMs = (() => {
71695
+ try {
71696
+ return timeoutMsOf(parsed.flags.timeout?.[0]);
71697
+ } catch (error) {
71698
+ throw new UsageError(error.message, "Example: praxis agent events wait --timeout 3600");
71699
+ }
71700
+ })();
71701
+ const headers = async () => {
71702
+ const credential = await auth.get(org);
71703
+ return { Authorization: `Bearer ${credential.token}`, ...credential.source === "api-key" ? { "X-API-Key": credential.token } : {} };
71704
+ };
71705
+ const failure2 = (status, body) => `HTTP ${status}${body?.error?.code ? ` ${body.error.code}` : ""}${body?.error?.message ? `: ${String(redact(body.error.message, secrets))}` : ""}`;
71706
+ const session = (() => {
71707
+ try {
71708
+ return sessionOf(parsed.flags.session?.[0]);
71709
+ } catch (error) {
71710
+ throw new UsageError(error.message, "Example: praxis agent events wait --session 0f6c…");
71711
+ }
71712
+ })();
71713
+ const key = waitKeyOf(config.env, agent, session);
71714
+ const waitDir = join12(ports.env.HOME || homedir3(), ".praxis", "cli", "events-wait");
71715
+ const statePath = join12(waitDir, `${key}.json`);
71716
+ const pidPath = join12(waitDir, `${key}.pid`);
71717
+ await mkdir4(waitDir, { recursive: true, mode: 448 });
71718
+ const holder = await acquireWaitLock({
71719
+ self: process.pid,
71720
+ readPid: () => readFile7(pidPath, "utf8").catch(() => null),
71721
+ createPid: (text3) => writeFile5(pidPath, text3, { mode: 384, flag: "wx" }).then(() => true, () => false),
71722
+ replacePid: (text3) => writeFile5(pidPath, text3, { mode: 384 }),
71723
+ probe: async (pid) => {
71724
+ try {
71725
+ process.kill(pid, 0);
71726
+ } catch (error) {
71727
+ if (error.code !== "EPERM")
71728
+ return { alive: false };
71729
+ }
71730
+ const ps = spawnSync("ps", ["-o", "ppid=,command=", "-p", String(pid)], { encoding: "utf8" });
71731
+ const line = ps.stdout?.trim() ?? "";
71732
+ const match = /^(\d+)\s+(.*)$/.exec(line);
71733
+ return match ? { alive: true, ppid: Number(match[1]), command: match[2] } : { alive: false };
71734
+ },
71735
+ terminate: (pid) => {
71736
+ try {
71737
+ process.kill(pid, "SIGTERM");
71738
+ } catch {}
71739
+ }
71740
+ });
71741
+ if (holder !== null) {
71742
+ process.stdout.write(alreadyWaitingNotice(holder) + `
71743
+ `);
71744
+ return 0;
71745
+ }
71746
+ const release = () => {
71747
+ try {
71748
+ if (pidOf(readFileSync3(pidPath, "utf8")) === process.pid)
71749
+ unlinkSync(pidPath);
71750
+ } catch {}
71751
+ };
71752
+ const onSignal = (signal) => {
71753
+ release();
71754
+ process.exit(signal === "SIGINT" ? 130 : 143);
71755
+ };
71756
+ for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"])
71757
+ process.once(signal, onSignal);
71758
+ try {
71759
+ return await runEventsWait({
71760
+ agent,
71761
+ timeoutMs,
71762
+ fetchLetters: async () => {
71763
+ const response = await wireFetch(inboxLettersUrl(config.apiUrl, agent), { headers: await headers(), signal: AbortSignal.timeout(30000), redirect: "error" });
71764
+ const body = await response.json().catch(() => null);
71765
+ if (!response.ok)
71766
+ throw new Error(failure2(response.status, body));
71767
+ return lettersOf(body);
71768
+ },
71769
+ openStream: async (signal, lastEventId) => {
71770
+ const response = await wireFetch(eventsStreamUrl(config.apiUrl, agent), {
71771
+ headers: streamHeaders(await headers(), lastEventId),
71772
+ signal,
71773
+ redirect: "error"
71774
+ });
71775
+ if (!response.ok || !response.body) {
71776
+ const body = await response.json().catch(() => null);
71777
+ return { status: response.status, reason: failure2(response.status, body) };
71778
+ }
71779
+ return { status: response.status, chunks: response.body.pipeThrough(new TextDecoderStream) };
71780
+ },
71781
+ readState: async () => waitStateOf(await readFile7(statePath, "utf8").catch(() => null)),
71782
+ writeState: async (next) => {
71783
+ await mkdir4(dirname10(statePath), { recursive: true, mode: 448 });
71784
+ await writeFile5(statePath, waitStateText(next), { mode: 384 });
71785
+ },
71786
+ print: (line) => {
71787
+ process.stdout.write(line + `
71788
+ `);
71789
+ },
71790
+ log: (line) => {
71791
+ process.stderr.write(String(redact(line, secrets)) + `
71792
+ `);
71793
+ },
71794
+ sleep: (ms, signal) => new Promise((resolve12) => {
71795
+ const timer = setTimeout(resolve12, ms);
71796
+ signal.addEventListener("abort", () => {
71797
+ clearTimeout(timer);
71798
+ resolve12();
71799
+ }, { once: true });
71800
+ })
71801
+ });
71802
+ } finally {
71803
+ release();
71804
+ for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"])
71805
+ process.removeListener(signal, onSignal);
71806
+ }
71807
+ }
70933
71808
  case "canvas import": {
70934
71809
  const authorize = async () => {
70935
71810
  const credential = await auth.get(org);
@@ -70971,7 +71846,7 @@ Examples:
70971
71846
  file: parsed.positional[0],
70972
71847
  name: parsed.flags.name?.[0],
70973
71848
  canvas: parsed.flags.canvas?.[0],
70974
- frames: typeof parsed.flags.frames?.[0] === "string" ? parsed.flags.frames[0].split(",").map((frame) => frame.trim()).filter(Boolean) : undefined,
71849
+ frames: typeof parsed.flags.frames?.[0] === "string" ? parsed.flags.frames[0].split(",").map((frame2) => frame2.trim()).filter(Boolean) : undefined,
70975
71850
  imageRoots: parsed.flags["image-root"],
70976
71851
  dryRun: Boolean(parsed.flags["dry-run"]?.[0]),
70977
71852
  yes: Boolean(flags.yes)
@@ -70985,9 +71860,9 @@ Examples:
70985
71860
  cwd: ports.cwd,
70986
71861
  rpc,
70987
71862
  upload,
70988
- human: (text2) => {
71863
+ human: (text3) => {
70989
71864
  if (ctx.mode === "human")
70990
- emit({ kind: "message", channel: "stdout", text: text2 });
71865
+ emit({ kind: "message", channel: "stdout", text: text3 });
70991
71866
  }
70992
71867
  });
70993
71868
  }
@@ -71019,7 +71894,8 @@ if (true) {
71019
71894
  process.exit(0);
71020
71895
  throw error;
71021
71896
  });
71022
- process.exitCode = await main3(process.argv.slice(2));
71897
+ const argv = process.argv.slice(2);
71898
+ process.exitCode = isDevopsTestRun(route(argv).words) && needsCacheOffReexec(process.env) ? await reexecWithCacheOff() : await main3(argv);
71023
71899
  }
71024
71900
  export {
71025
71901
  main3 as main