dal-code 1.0.20 → 1.0.23

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 (113) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/bun/register-bedrock.js +1 -0
  3. package/dist/core/agent-session.js +3 -3
  4. package/dist/core/http-dispatcher.js +1 -1
  5. package/dist/core/model-resolver.js +1 -1
  6. package/dist/core/model-runtime.js +1 -1
  7. package/dist/core/provider-composer.js +1 -1
  8. package/dist/core/sdk.js +1 -1
  9. package/dist/core/settings-manager.js +1 -1
  10. package/dist/core/system-prompt.js +8 -8
  11. package/dist/core/tools/bash-read-only.js +4 -0
  12. package/dist/core/tools/bash.js +13 -13
  13. package/dist/core/tools/tool-definition-wrapper.js +1 -1
  14. package/dist/modes/interactive/interactive-mode.js +14 -14
  15. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  16. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  17. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  18. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  19. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  20. package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
  21. package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
  22. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  23. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +1 -1
  24. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  25. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +1 -1
  26. package/dist/node_modules/@dalcode/dal-plugins/package.json +2 -2
  27. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  28. package/dist/node_modules/@dalcode/dal-router/package.json +4 -4
  29. package/dist/node_modules/@dalcode/dal-router/src/index.js +4 -4
  30. package/dist/node_modules/@dalcode/dal-router/src/pool.js +1 -1
  31. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  32. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  33. package/dist/node_modules/@dalcode/dal-subagent/src/agents.js +2 -2
  34. package/dist/node_modules/@dalcode/dal-subagent/src/index.js +9 -7
  35. package/dist/node_modules/@dalcode/dal-subagent/src/process-runner.js +3 -0
  36. package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
  37. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  38. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  39. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  40. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  41. package/dist/node_modules/@dalcode/deepailab/src/index.js +3 -3
  42. package/dist/node_modules/@earendil-works/chord/package.json +1 -1
  43. package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js +1 -1
  44. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/reducer.js +1 -0
  45. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/errors.js +1 -0
  46. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl-repo.js +1 -0
  47. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl-storage.js +5 -0
  48. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl.js +1 -0
  49. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory-repo.js +1 -0
  50. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory-storage.js +1 -0
  51. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/repo-utils.js +1 -0
  52. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/state.js +1 -0
  53. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance.js +1 -0
  54. package/dist/node_modules/@earendil-works/pi-agent-core/dist/search/scanning.js +1 -0
  55. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +4 -4
  56. package/dist/node_modules/@earendil-works/pi-ai/dist/api/cloudflare-gateway-binding.js +1 -0
  57. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  58. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
  59. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  60. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  61. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  62. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  63. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/pi-user-agent.js +1 -1
  64. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  65. package/dist/node_modules/@earendil-works/pi-client/dist/session-handle.js +1 -0
  66. package/dist/node_modules/@earendil-works/pi-client/dist/state.js +1 -0
  67. package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
  68. package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
  69. package/dist/node_modules/@earendil-works/pi-server/dist/cli.js +16 -0
  70. package/dist/node_modules/@earendil-works/pi-server/dist/config.js +1 -0
  71. package/dist/node_modules/@earendil-works/pi-server/dist/handler.js +1 -0
  72. package/dist/node_modules/@earendil-works/pi-server/dist/ipc/client.js +2 -0
  73. package/dist/node_modules/@earendil-works/pi-server/dist/ipc/protocol.js +2 -0
  74. package/dist/node_modules/@earendil-works/pi-server/dist/ipc/server.js +3 -0
  75. package/dist/node_modules/@earendil-works/pi-server/dist/protocol.js +1 -0
  76. package/dist/node_modules/@earendil-works/pi-server/dist/radius.js +1 -0
  77. package/dist/node_modules/@earendil-works/pi-server/dist/rpc-process.js +4 -0
  78. package/dist/node_modules/@earendil-works/pi-server/dist/serve.js +1 -0
  79. package/dist/node_modules/@earendil-works/pi-server/dist/sessions.js +1 -0
  80. package/dist/node_modules/@earendil-works/pi-server/dist/snapshots.js +1 -0
  81. package/dist/node_modules/@earendil-works/pi-server/dist/storage.js +1 -0
  82. package/dist/node_modules/@earendil-works/pi-server/dist/supervisor.js +1 -0
  83. package/dist/node_modules/@earendil-works/pi-server/dist/testing/service.js +1 -0
  84. package/dist/node_modules/@earendil-works/pi-server/package.json +5 -5
  85. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/branch-cache.js +7 -0
  86. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/search-backend.js +36 -0
  87. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/storage/branch-entries.js +25 -0
  88. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/storage/branch-tips.js +2 -0
  89. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/storage/entries.js +7 -0
  90. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/storage/facts.js +20 -0
  91. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/storage/lanes.js +26 -0
  92. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/storage/records.js +9 -0
  93. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/storage/session-sequences.js +1 -0
  94. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/storage/session-stats.js +10 -0
  95. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/storage/sessions.js +29 -0
  96. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/storage/writer-leases.js +14 -0
  97. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/package.json +3 -3
  98. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  99. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  100. package/dist/server/create-harness.js +1 -0
  101. package/dist/utils/clipboard-image.js +1 -1
  102. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  103. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  104. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  105. package/examples/extensions/gondolin/package-lock.json +2 -2
  106. package/examples/extensions/gondolin/package.json +1 -1
  107. package/examples/extensions/sandbox/package-lock.json +2 -2
  108. package/examples/extensions/sandbox/package.json +1 -1
  109. package/examples/extensions/with-deps/package-lock.json +2 -2
  110. package/examples/extensions/with-deps/package.json +1 -1
  111. package/npm-shrinkwrap.json +2 -2
  112. package/package.json +1 -1
  113. package/dist/node_modules/@earendil-works/pi-agent-core/dist/__probe.js +0 -1
@@ -1 +1 @@
1
- var s=Object.defineProperty;var n=(o,r)=>s(o,"name",{value:r,configurable:!0});function t(){return typeof process>"u"||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.("node:os")??null}n(t,"loadNodeOs");const e=t();function u(){return e?`pi (${e.platform()} ${e.release()}; ${e.arch()})`:"pi (browser)"}n(u,"getPiUserAgent");export{u as getPiUserAgent};
1
+ var s=Object.defineProperty;var n=(o,r)=>s(o,"name",{value:r,configurable:!0});function t(){return typeof process>"u"||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.("node:os")??null}n(t,"loadNodeOs");const e=t();function u(){return e?`dal (${e.platform()} ${e.release()}; ${e.arch()})`:"dal (browser)"}n(u,"getPiUserAgent");export{u as getPiUserAgent};
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@earendil-works/pi-ai",
3
- "version": "1.0.20",
3
+ "version": "1.0.23",
4
4
  "description": "Unified LLM API with automatic model discovery and provider configuration",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -54,7 +54,7 @@
54
54
  "dependencies": {
55
55
  "@anthropic-ai/sdk": "0.124.0",
56
56
  "@aws-sdk/client-bedrock-runtime": "3.1127.0",
57
- "@earendil-works/pi-telemetry": "^1.0.20",
57
+ "@earendil-works/pi-telemetry": "^1.0.23",
58
58
  "@google/genai": "2.21.0",
59
59
  "@opentelemetry/api": "1.9.0",
60
60
  "@smithy/node-http-handler": "4.12.1",
@@ -0,0 +1 @@
1
+ var n=Object.defineProperty;var e=(i,s)=>n(i,"name",{value:s,configurable:!0});class r{static{e(this,"SessionHandle")}id;#s;constructor(s,t){this.id=s,this.#s=t}get attached(){return this.#s.isAttached()}get active(){return this.attached}get snapshot(){return this.#s.getSnapshot()}subscribe(s){return this.#s.subscribe(s)}onEvent(s){return this.#s.onEvent(s)}async detach(){await this.#s.detach()}dispose(){return this.#s.dispose()}[Symbol.asyncDispose](){return this.dispose()}async prompt(s){return(await this.#t({command:"prompt",sessionId:this.id,text:s})).session}async steer(s){return(await this.#t({command:"steer",sessionId:this.id,text:s})).session}async abort(){return(await this.#t({command:"abort",sessionId:this.id})).session}async setModel(s){return(await this.#t({command:"set_model",sessionId:this.id,model:s})).session}async setThinking(s){return(await this.#t({command:"set_thinking",sessionId:this.id,thinkingLevel:s})).session}async subscribeExtensionUi(){await this.#t({command:"subscribe_extension_ui",sessionId:this.id})}async answerExtensionUi(s,t){await this.#t({command:"extension_ui_answer",sessionId:this.id,requestId:s,answer:t})}#t(s){return this.#s.request(s)}}export{r as SessionHandle};
@@ -0,0 +1 @@
1
+ var h=Object.defineProperty;var r=(t,s)=>h(t,"name",{value:s,configurable:!0});import{toError as a}from"./errors.js";class f{static{r(this,"ClientState")}#s=new Map;#e=new Set;#i=new Set;#r=new Set;#o=new Map;#h=new Map;#a;#t;constructor(s){this.#a=s}get snapshot(){return this.#t}reset(){this.#t=void 0,this.#s.clear(),this.#e.clear()}clearAttachments(){this.#e.clear()}dispose(){this.reset(),this.#i.clear(),this.#r.clear(),this.#o.clear(),this.#h.clear()}getSessionSnapshot(s){return this.#s.get(s)}isSessionAttached(s){return this.#e.has(s)}forgetSessionSnapshot(s){const e=this.#s.get(s);return this.#s.delete(s),e}restoreSessionSnapshot(s){this.#s.has(s.id)||this.#s.set(s.id,s)}subscribe(s){return this.#i.add(s),()=>this.#i.delete(s)}onEvent(s){return this.#r.add(s),()=>this.#r.delete(s)}subscribeSession(s,e){return n(this.#o,s,e)}onSessionEvent(s,e){return n(this.#h,s,e)}applyResult(s){if(s.command!=="list"){if(s.command==="detach"){this.#e.delete(s.sessionId);const e=this.#s.get(s.sessionId);e&&this.#d({...e,attached:!1},!0);return}"session"in s&&this.#d(s.session)}}applyEvent(s){s.type==="server_snapshot"&&this.applyServerSnapshot(s.snapshot),s.type==="session_snapshot"&&this.#d(s.snapshot),s.type==="session_removed"&&(this.#s.delete(s.sessionId),this.#e.delete(s.sessionId)),this.#n(this.#r,s);const e=d(s);e&&this.#n(this.#h.get(e),s)}applyServerSnapshot(s){this.#t&&s.revision<this.#t.revision||(this.#t=s,this.#n(this.#i,s))}#d(s,e=!1){const i=this.#s.get(s.id);!e&&i&&s.revision<i.revision||(this.#s.set(s.id,s),s.attached?this.#e.add(s.id):this.#e.delete(s.id),this.#n(this.#o.get(s.id),s))}#n(s,e){for(const i of s??[])try{i(e)}catch(o){this.#p(o)}}#p(s){if(this.#a)try{this.#a(a(s))}catch{}}}function n(t,s,e){let i=t.get(s);return i||(i=new Set,t.set(s,i)),i.add(e),()=>{i.delete(e),i.size===0&&t.delete(s)}}r(n,"addMappedListener");function d(t){if(t.type==="session_snapshot")return t.snapshot.id;if(t.type==="session_progress"||t.type==="session_removed"||t.type==="extension_ui")return t.sessionId}r(d,"getEventSessionId");export{f as ClientState};
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@earendil-works/pi-client",
3
- "version": "1.0.20",
3
+ "version": "1.0.23",
4
4
  "description": "Transport-neutral client for remote pi sessions over framed CBOR bytes",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -40,7 +40,7 @@
40
40
  "node": ">=22.19.0"
41
41
  },
42
42
  "dependencies": {
43
- "@earendil-works/chord": "^1.0.20",
44
- "@earendil-works/pi-protocol": "^1.0.20"
43
+ "@earendil-works/chord": "^1.0.23",
44
+ "@earendil-works/pi-protocol": "^1.0.23"
45
45
  }
46
46
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@earendil-works/pi-protocol",
3
- "version": "1.0.20",
3
+ "version": "1.0.23",
4
4
  "description": "Transport-neutral CBOR protocol for remote pi sessions",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -33,7 +33,7 @@
33
33
  "node": ">=22.19.0"
34
34
  },
35
35
  "dependencies": {
36
- "@earendil-works/chord": "^1.0.20",
36
+ "@earendil-works/chord": "^1.0.23",
37
37
  "typebox": "1.3.27"
38
38
  }
39
39
  }
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ var u=Object.defineProperty;var t=(e,n)=>u(e,"name",{value:n,configurable:!0});import{readFileSync as v}from"node:fs";import{createConnection as w}from"node:net";import{dirname as g,join as x}from"node:path";import{cwd as S}from"node:process";import{fileURLToPath as y}from"node:url";import{getSocketPath as h}from"./config.js";import{sendIpcRequest as i}from"./ipc/client.js";import{encodeMessage as p}from"./ipc/protocol.js";import{serve as _}from"./serve.js";const J=y(import.meta.url),O=g(J),m=JSON.parse(v(x(O,"../package.json"),"utf-8"));function d(){console.log(`server v${m.version}
3
+
4
+ Usage:
5
+ server serve
6
+ server list
7
+ server spawn [--cwd <path>] [--label <label>]
8
+ server status <instance-id>
9
+ server stop <instance-id>
10
+ server rpc <instance-id> <json-command>
11
+ server rpc-stream <instance-id>
12
+ server --help
13
+ server --version
14
+
15
+ RPC stream stdin expects JSONL RpcCommand or extension_ui_response messages.`)}t(d,"printHelp");function c(e){console.log(JSON.stringify(e,null,2))}t(c,"printResponse");function l(e,n){const s=e.indexOf(n);if(!(s===-1||s+1>=e.length))return e[s+1]}t(l,"getFlagValue");async function U(e){const n=w(h());let s="";process.stdin.setEncoding("utf8"),await new Promise((r,o)=>{n.once("connect",()=>{n.write(p({type:"rpc_stream",instanceId:e})),r()}),n.once("error",o)}),n.on("data",r=>{process.stdout.write(r.toString())}),console.error(`connected to rpc stream ${e}; send JSONL RpcCommand or extension_ui_response on stdin`),n.on("error",r=>{console.error(r instanceof Error?r.message:String(r)),process.exit(1)}),n.on("end",()=>{process.exit(0)}),process.stdin.on("data",r=>{for(s+=r;;){const o=s.indexOf(`
16
+ `);if(o===-1)return;const a=s.slice(0,o).trim();if(s=s.slice(o+1),!a)continue;const f=JSON.parse(a);n.write(p(f))}})}t(U,"rpcStream");async function N(){const e=process.argv.slice(2);if((e.length===0||e[0]==="--help"||e[0]==="-h")&&(d(),process.exit(0)),(e[0]==="--version"||e[0]==="-v")&&(console.log(m.version),process.exit(0)),e[0]==="serve"){await _();return}if(e[0]==="list"){c(await i({type:"list"}));return}if(e[0]==="spawn"){const n=l(e,"--cwd")??S(),s=l(e,"--label");c(await i({type:"spawn",cwd:n,label:s}));return}if(e[0]==="status"){const n=e[1];n||(console.error("Usage: server status <instance-id>"),process.exit(1)),c(await i({type:"status",instanceId:n}));return}if(e[0]==="stop"){const n=e[1];n||(console.error("Usage: server stop <instance-id>"),process.exit(1)),c(await i({type:"stop",instanceId:n}));return}if(e[0]==="rpc"){const n=e[1],s=e[2];(!n||!s)&&(console.error("Usage: server rpc <instance-id> <json-command>"),process.exit(1)),c(await i({type:"rpc",instanceId:n,command:JSON.parse(s)}));return}if(e[0]==="rpc-stream"){const n=e[1];n||(console.error("Usage: server rpc-stream <instance-id>"),process.exit(1)),await U(n);return}console.error(`Unknown command: ${e[0]}`),d(),process.exit(1)}t(N,"main"),await N();
@@ -0,0 +1 @@
1
+ var a=Object.defineProperty;var n=(t,r)=>a(t,"name",{value:r,configurable:!0});import{existsSync as u,readFileSync as p}from"node:fs";import{homedir as m}from"node:os";import{dirname as i,join as e}from"node:path";import{fileURLToPath as f}from"node:url";const h=".pi",l="PI_SERVER_DIR",_=f(import.meta.url),s=i(_),d=import.meta.url.includes("$bunfs")||import.meta.url.includes("~BUN")||import.meta.url.includes("%7EBUN");function g(){let t=s;for(;t!==i(t);){const r=e(t,"package.json");if(u(r))return r;t=i(t)}return e(s,"package.json")}n(g,"getPackageJsonPath");let c={};try{c=JSON.parse(p(g(),"utf-8"))}catch(t){if(t.code!=="ENOENT")throw t}const x=c.version||"0.0.0";function o(){const t=process.env[l];if(t)return t;const r=process.env.PI_CONFIG_DIR||e(m(),h);return e(r,"server")}n(o,"getServerDir");function S(){return e(o(),"auth.json")}n(S,"getAuthPath");function k(){return e(o(),"machine.json")}n(k,"getMachinePath");function v(){return e(o(),"instances.json")}n(v,"getInstancesPath");function D(){return e(o(),"server.sock")}n(D,"getSocketPath");export{x as VERSION,S as getAuthPath,v as getInstancesPath,k as getMachinePath,o as getServerDir,D as getSocketPath,d as isBunBinary};
@@ -0,0 +1 @@
1
+ var u=Object.defineProperty;var s=(n,t)=>u(n,"name",{value:t,configurable:!0});import{supervisor as e}from"./supervisor.js";function c(n){return{id:n.id,status:n.status,cwd:n.cwd,label:n.label,sessionId:n.sessionId,sessionFile:n.sessionFile,radiusPiId:n.radiusPiId}}s(c,"toInstanceSummary");function r(n){return{type:"error",ok:!1,error:`Unknown instance: ${n}`}}s(r,"unknownInstanceError");async function w(n){switch(n.type){case"spawn":{const t=await e.spawnInstance({cwd:n.cwd,label:n.label});return{type:"spawn_result",ok:!0,instance:c(t)}}case"list":return{type:"list_result",ok:!0,instances:e.listInstances().map(c)};case"status":{const t=e.getInstance(n.instanceId);return t?{type:"status_result",ok:!0,instance:c(t)}:r(n.instanceId)}case"stop":return await e.stopInstance(n.instanceId)?{type:"stop_result",ok:!0,instanceId:n.instanceId}:r(n.instanceId);case"rpc":{const t=await e.handleRpc(n.instanceId,n.command);return t?{type:"rpc_result",ok:!0,response:t}:r(n.instanceId)}case"rpc_stream":{const t=e.getInstance(n.instanceId);return t?{type:"rpc_ready",ok:!0,instance:c(t)}:r(n.instanceId)}}}s(w,"handleIpcRequest");function f(n,t,o,p){const a=e.openRpcStream(n,o,p);if(a)return{async handleRequest(i){if(i.type==="extension_ui_response"){a.handleUiResponse(i);return}const d=await a.handleRpc(i);t(d)},close(){a.close()}}}s(f,"openRpcStream");export{w as handleIpcRequest,f as openRpcStream};
@@ -0,0 +1,2 @@
1
+ var m=Object.defineProperty;var a=(o,n)=>m(o,"name",{value:n,configurable:!0});import{createConnection as p}from"node:net";import{getSocketPath as w}from"../config.js";import{encodeMessage as k,parseResponseLine as g}from"./protocol.js";async function S(o){const n=w();return new Promise((l,s)=>{const e=p(n);let c="",r=!1;const t=a(()=>{e.removeAllListeners(),e.end()},"cleanup");e.on("connect",()=>{e.write(k(o))}),e.on("data",i=>{c+=i.toString();const f=c.indexOf(`
2
+ `);if(f===-1)return;const u=c.slice(0,f).trim();if(u)try{r=!0,l(g(u)),t()}catch(d){r=!0,s(d),t()}}),e.on("error",i=>{r||(r=!0,s(i),t())}),e.on("end",()=>{r||(r=!0,s(new Error(`Server socket closed before a response was received: ${n}`)),t())})})}a(S,"sendIpcRequest");export{S as sendIpcRequest};
@@ -0,0 +1,2 @@
1
+ var t=Object.defineProperty;var n=(e,r)=>t(e,"name",{value:r,configurable:!0});function u(e){return`${JSON.stringify(e)}
2
+ `}n(u,"encodeMessage");function o(e){return JSON.parse(e)}n(o,"parseRequestLine");function a(e){return JSON.parse(e)}n(a,"parseResponseLine");export{u as encodeMessage,o as parseRequestLine,a as parseResponseLine};
@@ -0,0 +1,3 @@
1
+ var v=Object.defineProperty;var p=(n,s)=>v(n,"name",{value:s,configurable:!0});import{existsSync as g,unlinkSync as N}from"node:fs";import{createConnection as L,createServer as I}from"node:net";import{getSocketPath as x}from"../config.js";import{encodeMessage as i,parseRequestLine as O}from"./protocol.js";async function T(n){const s=x();await R(s);const c=I(e=>{let r="";e.on("data",async f=>{r+=f.toString();const t=r.indexOf(`
2
+ `);if(t===-1)return;const y=r.slice(0,t).trim();if(r=r.slice(t+1),!!y)try{const o=O(y);if(o.type==="rpc_stream"){const l=await n(o);if(!l.ok||l.type!=="rpc_ready"||!l.instance){e.end(i(l));return}e.removeAllListeners("data");const m=n.openRpcStream(o.instanceId,a=>{e.write(i(a))},a=>{e.write(i(a))},a=>{e.write(i(a))});if(!m){e.end(i({type:"error",ok:!1,error:`Unknown instance: ${o.instanceId}`}));return}e.write(i(l));let S=Promise.resolve();e.on("data",a=>{for(r+=a.toString();;){const w=r.indexOf(`
3
+ `);if(w===-1)break;const E=r.slice(0,w).trim();r=r.slice(w+1),E&&(S=S.then(async()=>{try{await m.handleRequest(JSON.parse(E))}catch(u){e.write(i({type:"error",ok:!1,error:u instanceof Error?u.message:String(u)}))}}).catch(u=>{e.write(i({type:"error",ok:!1,error:u.message}))}))}}),e.once("close",()=>m.close());return}const d=await n(o);e.end(i(d))}catch(o){const d={type:"error",ok:!1,error:o instanceof Error?o.message:String(o)};e.end(i(d))}})});return await new Promise((e,r)=>{c.once("error",r),c.listen(s,()=>{c.off("error",r),e()})}),c}p(T,"startIpcServer");async function R(n){if(!g(n))return;if(await h(n))throw new Error(`server is already running: ${n}`);N(n)}p(R,"removeStaleSocketIfNeeded");async function h(n){return new Promise((s,c)=>{const e=L(n);let r=!1;const f=p(t=>{r||(r=!0,e.removeAllListeners(),e.destroy(),s(t))},"finish");e.on("connect",()=>f(!0)),e.on("error",t=>{if(t.code==="ECONNREFUSED"||t.code==="ENOENT"){f(!1);return}if(t.code==="EPIPE"||t.code==="ECONNRESET"){f(!1);return}r||(r=!0,e.removeAllListeners(),e.destroy(),c(t))})})}p(h,"isSocketLive");export{T as startIpcServer};
@@ -0,0 +1 @@
1
+ var m=Object.defineProperty;var i=(t,e)=>m(t,"name",{value:e,configurable:!0});import{getSupportedThinkingLevels as h}from"@earendil-works/pi-ai";function u(t){if(!(t===void 0||!Number.isFinite(t)))return Math.max(0,Math.floor(t))}i(u,"nonNegativeInteger");function c(t){return Number.isFinite(t)?Math.max(0,t):0}i(c,"nonNegativeNumber");function r(t,e){if(typeof t!="string"||t.length===0)throw new TypeError(`${e} must be a non-empty string`);return t}i(r,"identifier");function p(t){if(!Number.isSafeInteger(t)||t<0)throw new TypeError("Protocol timestamps must be non-negative integers");return t}i(p,"timestamp");function d(t,e=new Set){if(t===null||typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError("Protocol JSON numbers must be finite");return t}if(typeof t!="object")throw new TypeError(`Unsupported protocol JSON value: ${typeof t}`);if(e.has(t))throw new TypeError("Protocol JSON values must not contain circular references");const o=Object.getPrototypeOf(t);if(!Array.isArray(t)&&o!==Object.prototype&&o!==null)throw new TypeError("Protocol JSON objects must be plain objects");e.add(t);try{if(Array.isArray(t))return Array.from(t,s=>d(s,e));const n={};for(const[s,a]of Object.entries(t))n[s]=d(a,e);return n}finally{e.delete(t)}}i(d,"toProtocolJsonValue");function l(t,e=new Set){if(t===null||typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number")return Number.isFinite(t)?t:String(t);if(typeof t=="bigint")return t.toString();if(!(t===void 0||typeof t=="function"||typeof t=="symbol")){if(t instanceof Date)return t.toISOString();if(typeof t!="object")return String(t);if(e.has(t))return"[Circular]";e.add(t);try{if(Array.isArray(t))return Array.from(t,n=>l(n,e)??null);const o={};for(const[n,s]of Object.entries(t)){const a=l(s,e);a!==void 0&&(o[n]=a)}return o}finally{e.delete(t)}}}i(l,"sanitizeProtocolDetails");function y(t){if(!t)return;const e=u(t.reasoning);return{input:u(t.input)??0,output:u(t.output)??0,cacheRead:u(t.cacheRead)??0,cacheWrite:u(t.cacheWrite)??0,...e===void 0?{}:{reasoning:e},totalTokens:u(t.totalTokens)??0,cost:{input:c(t.cost.input),output:c(t.cost.output),cacheRead:c(t.cost.cacheRead),cacheWrite:c(t.cost.cacheWrite),total:c(t.cost.total)}}}i(y,"toProtocolUsage");function g(t,e){return{provider:r(t.provider,"Model provider"),id:r(t.id,"Model id"),name:r(t.name,"Model name"),api:r(t.api,"Model API"),reasoning:t.reasoning,input:[...t.input],contextWindow:Math.max(1,Math.floor(t.contextWindow)),maxTokens:Math.max(1,Math.floor(t.maxTokens)),cost:{input:c(t.cost.input),output:c(t.cost.output),cacheRead:c(t.cost.cacheRead),cacheWrite:c(t.cost.cacheWrite)},supportedThinkingLevels:h(t),authenticated:e}}i(g,"toProtocolModelMetadata");function x(t){return typeof t=="string"?[{type:"text",text:t}]:t.map(e=>{switch(e.type){case"text":return{type:"text",text:e.text};case"image":return{type:"image",data:e.data,mimeType:e.mimeType};default:return e}})}i(x,"toProtocolUserContent");function N(t,e){return{id:r(e.id,"Transcript item id"),role:"user",content:x(t.content),timestamp:p(t.timestamp)}}i(N,"toProtocolUserMessage");function T(t){return t.content.map(e=>{switch(e.type){case"text":return{type:"text",text:e.text};case"thinking":return{type:"thinking",thinking:e.thinking,...e.redacted===void 0?{}:{redacted:e.redacted}};case"toolCall":return{type:"toolCall",toolCallId:r(e.id,"Tool call id"),toolName:r(e.name,"Tool call name"),input:d(e.arguments)};default:return e}})}i(T,"toProtocolAssistantContent");function P(t,e){const o=y(t.usage),n={id:r(e.id,"Transcript item id"),role:"assistant",content:T(t),model:{provider:r(t.provider,"Assistant provider"),id:r(t.model,"Assistant model")},...t.responseModel===void 0?{}:{responseModel:r(t.responseModel,"Assistant response model")},...o?{usage:o}:{},timestamp:p(t.timestamp)};switch(t.stopReason){case"pending":return{...n,status:"streaming"};case"stop":case"length":case"toolUse":return{...n,status:"complete",stopReason:t.stopReason};case"deferred":throw new TypeError("Deferred assistant messages are not supported by protocol v1");case"error":if(t.errorMessage?.length===0)throw new TypeError("Assistant error messages must not be empty");return{...n,status:"error",stopReason:"error",...t.errorMessage===void 0?{}:{errorMessage:t.errorMessage}};case"aborted":return{...n,status:"aborted",stopReason:"aborted",...t.errorMessage===void 0?{}:{errorMessage:t.errorMessage}};default:return t.stopReason}}i(P,"toProtocolAssistantMessage");function b(t){return t.map(e=>{switch(e.type){case"text":return{type:"text",text:e.text};case"image":return{type:"image",data:e.data,mimeType:e.mimeType};default:return e}})}i(b,"toProtocolToolContent");function A(t,e){const o=r(e.call.id,"Tool call id"),n=r(e.call.name,"Tool call name");if(r(t.toolCallId,"Tool result call id")!==o)throw new TypeError(`Tool result ${t.toolCallId} does not match tool call ${o}`);if(r(t.toolName,"Tool result name")!==n)throw new TypeError(`Tool result ${t.toolName} does not match tool call ${n}`);const s=l(t.details),a=y(t.usage),f={id:r(e.id,"Transcript item id"),role:"tool",toolCallId:o,toolName:n,input:d(e.call.arguments),content:b(t.content),...s===void 0?{}:{details:s},...a?{usage:a}:{},timestamp:p(t.timestamp)};return t.isError?{...f,status:"error",isError:!0}:{...f,status:"complete",isError:!1}}i(A,"toProtocolToolResultMessage");export{l as sanitizeProtocolDetails,P as toProtocolAssistantMessage,d as toProtocolJsonValue,g as toProtocolModelMetadata,A as toProtocolToolResultMessage,y as toProtocolUsage,N as toProtocolUserMessage};
@@ -0,0 +1 @@
1
+ var C=Object.defineProperty;var s=(i,t)=>C(i,"name",{value:t,configurable:!0});import{hostname as l,platform as T}from"node:os";import{readStoredCredential as y}from"@earendil-works/pi-coding-agent";import{getServerDir as S,getSocketPath as w,VERSION as F}from"./config.js";import{loadMachine as f,saveMachine as v}from"./storage.js";const A="https://radius.pi.dev/",E="/v1/",p=3,_=1e3,b=3e4,$="radius";class h extends Error{static{s(this,"RadiusHttpError")}status;constructor(t,e){super(e),this.name="RadiusHttpError",this.status=t}}async function g(i,t){const e=await fetch(new URL(i,H()),{method:"POST",headers:{Authorization:`Bearer ${P()}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!e.ok)throw new h(e.status,`Radius request failed: ${e.status} ${await e.text()}`);return await e.json()}s(g,"post");async function u(i,t){const e=await fetch(new URL(i,H()),{method:"POST",headers:{Authorization:`Bearer ${P()}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!e.ok)throw new h(e.status,`Radius request failed: ${e.status} ${await e.text()}`)}s(u,"maybePost");function d(i){return i instanceof h&&i.status===404}s(d,"isNotFoundError");function c(i){const t=Math.min(b,_*2**Math.max(0,i-1)),e=Math.floor(Math.random()*Math.max(250,t/4));return Math.min(b,t+e)}s(c,"computeBackoffDelayMs");function R(i){return i instanceof h?`HTTP ${i.status}: ${i.message}`:i instanceof Error?i.message:String(i)}s(R,"formatRadiusError");function m(i,t,e,a,r){console.error(`${i} ${t} failed (attempt ${a}); retrying in ${e}ms: ${R(r)}`)}s(m,"logRadiusRetry");function I(){return process.env.PI_RADIUS_URL||A}s(I,"getRadiusUrl");function H(){const i=process.env.PI_RADIUS_SERVER_URL;return i||new URL(E,I()).toString()}s(H,"getRadiusServerBaseUrl");function M(){const i=y($);return i?.type==="oauth"?i:void 0}s(M,"getStoredRadiusCredential");function P(){const i=M();if(typeof i?.access=="string"&&i.access)return i.access;const t=process.env.RADIUS_API_KEY;if(t)return t;throw new Error("Radius credentials are required in ~/.pi/agent/auth.json or RADIUS_API_KEY")}s(P,"getRadiusAccessToken");function o(){return!!M()?.access||!!process.env.RADIUS_API_KEY}s(o,"isRadiusEnabled");class U{static{s(this,"RadiusPresence")}machineHeartbeatTimer;machineHeartbeatIntervalMs=0;machineConsecutiveNotFoundCount=0;machineTransientFailureCount=0;piHeartbeatStates=new Map;machine;coordinator;setCoordinator(t){this.coordinator=t}async start(t){if(!o())return;const e=await this.registerMachine(t);return this.startMachineHeartbeat(e.heartbeatIntervalMs),this.machine}async stop(){this.machineHeartbeatTimer&&(clearTimeout(this.machineHeartbeatTimer),this.machineHeartbeatTimer=void 0);for(const[t,e]of this.piHeartbeatStates)e.timer&&clearTimeout(e.timer),this.piHeartbeatStates.delete(t);if(!(!this.machine||!o()))try{await u(`machines/${this.machine.id}/disconnect`,{})}catch(t){if(!d(t))throw t}}async registerPi(t){if(!o())return t;const e=this.machine??f();if(!e)throw new Error("No registered machine available for Pi registration");const a=await g("pis/register",{machineId:e.id,label:t.label,cwd:t.cwd,hostname:l(),pid:process.pid,transport:"local-rpc",capabilities:{rpc:!0,relay:!1,iroh:!1},sessionId:t.sessionId}),r={...t,radiusPiId:a.id};return this.startPiHeartbeat(t.id,a.heartbeatIntervalMs,a.id),r}async disconnectPi(t){const e=this.piHeartbeatStates.get(t.id);if(e&&(e.timer&&clearTimeout(e.timer),this.piHeartbeatStates.delete(t.id)),!(!o()||!t.radiusPiId))try{await u(`pis/${t.radiusPiId}/disconnect`,{})}catch(a){if(!d(a))throw a}}async registerMachine(t){const e=this.machine??f(),a=await g("machines/register",{machineId:e?.id,label:t,hostname:l(),platform:T(),arch:process.arch,version:F,capabilities:{spawn:!0,relay:!1,iroh:!1}}),r=new Date().toISOString();return this.machine={id:a.id,createdAt:e?.createdAt??r,lastSeenAt:r,label:t},v(this.machine),this.machineConsecutiveNotFoundCount=0,this.machineTransientFailureCount=0,a}startMachineHeartbeat(t){this.machineHeartbeatIntervalMs=t,this.scheduleMachineHeartbeat(t)}scheduleMachineHeartbeat(t){this.machineHeartbeatTimer&&clearTimeout(this.machineHeartbeatTimer),this.machineHeartbeatTimer=setTimeout(()=>{this.heartbeatMachine()},t)}startPiHeartbeat(t,e,a){const r=this.piHeartbeatStates.get(t);r?.timer&&clearTimeout(r.timer);const n=r??{intervalMs:e,radiusPiId:a,consecutiveNotFoundCount:0,transientFailureCount:0};n.intervalMs=e,n.radiusPiId=a,n.consecutiveNotFoundCount=0,n.transientFailureCount=0,this.piHeartbeatStates.set(t,n),this.schedulePiHeartbeat(t,e)}schedulePiHeartbeat(t,e){const a=this.piHeartbeatStates.get(t);a&&(a.timer&&clearTimeout(a.timer),a.timer=setTimeout(()=>{this.heartbeatPi(t)},e))}async heartbeatMachine(){if(!(!this.machine||!o()))try{await u(`machines/${this.machine.id}/heartbeat`,{cwd:S(),socketPath:w()}),this.machineConsecutiveNotFoundCount=0,this.machineTransientFailureCount=0,this.scheduleMachineHeartbeat(this.machineHeartbeatIntervalMs)}catch(t){if(!d(t)){this.machineTransientFailureCount+=1;const e=c(this.machineTransientFailureCount);m("Radius machine","heartbeat",e,this.machineTransientFailureCount,t),this.scheduleMachineHeartbeat(e);return}if(this.machineTransientFailureCount=0,this.machineConsecutiveNotFoundCount+=1,this.machineConsecutiveNotFoundCount<p){this.scheduleMachineHeartbeat(this.machineHeartbeatIntervalMs);return}try{await this.reRegisterMachineAndPis()}catch(e){this.machineTransientFailureCount+=1;const a=c(this.machineTransientFailureCount);m("Radius machine","re-registration",a,this.machineTransientFailureCount,e),this.scheduleMachineHeartbeat(a)}}}async heartbeatPi(t){if(!o())return;const e=this.piHeartbeatStates.get(t);if(e)try{await u(`pis/${e.radiusPiId}/heartbeat`,{}),e.consecutiveNotFoundCount=0,e.transientFailureCount=0,this.schedulePiHeartbeat(t,e.intervalMs)}catch(a){if(!d(a)){e.transientFailureCount+=1;const r=c(e.transientFailureCount);m(`Radius Pi ${t}`,"heartbeat",r,e.transientFailureCount,a),this.schedulePiHeartbeat(t,r);return}if(e.transientFailureCount=0,e.consecutiveNotFoundCount+=1,e.consecutiveNotFoundCount<p){this.schedulePiHeartbeat(t,e.intervalMs);return}try{if(!await this.reRegisterPi(t)){const n=c(1);console.error(`Radius Pi ${t} re-registration skipped; retrying in ${n}ms`),this.schedulePiHeartbeat(t,n)}}catch(r){e.transientFailureCount+=1;const n=c(e.transientFailureCount);m(`Radius Pi ${t}`,"re-registration",n,e.transientFailureCount,r),this.schedulePiHeartbeat(t,n)}}}async reRegisterMachineAndPis(){const t=await this.registerMachine(this.machine?.label);this.startMachineHeartbeat(t.heartbeatIntervalMs);const e=this.coordinator?.listLiveInstances()??[];for(const a of e)try{await this.reRegisterPi(a.id)}catch(r){console.error(`Radius Pi ${a.id} re-registration failed: ${R(r)}`)}}async reRegisterPi(t){const e=this.coordinator?.getLiveInstance(t);if(!e){const r=this.piHeartbeatStates.get(t);return r&&(r.timer&&clearTimeout(r.timer),this.piHeartbeatStates.delete(t)),!1}if(!this.machine)return await this.reRegisterMachineAndPis(),!0;const a=await this.registerPi(e);return this.coordinator?.updateInstance(a),!0}}const B=new U;export{U as RadiusPresence,P as getRadiusAccessToken,H as getRadiusServerBaseUrl,I as getRadiusUrl,o as isRadiusEnabled,B as radiusPresence};
@@ -0,0 +1,4 @@
1
+ var c=Object.defineProperty;var i=(r,e)=>c(r,"name",{value:e,configurable:!0});import{spawn as u}from"node:child_process";import{randomUUID as p}from"node:crypto";import{createRequire as h}from"node:module";import{dirname as a,join as f}from"node:path";import{isBunBinary as l}from"./config.js";const m=h(import.meta.url);function g(r){return r instanceof Error?r:new Error(String(r))}i(g,"toError");class w{static{i(this,"RpcProcessInstance")}process;exited=!1;nextRequestId=0;stdoutBuffer="";stderrBuffer="";pendingRequests=new Map;eventListeners=new Set;exitListeners=new Set;uiRequestHandler;constructor(e){const t=this.getSpawnCommand();if(this.process=u(t.command,t.args,{cwd:e.cwd,env:process.env,stdio:["pipe","pipe","pipe"]}),!this.process.stdin||!this.process.stdout)throw new Error("Failed to create RPC process stdio");this.attachListeners()}getSpawnCommand(){return l?{command:f(a(process.execPath),process.platform==="win32"?"pi.exe":"pi"),args:["--mode","rpc"]}:{command:process.execPath,args:[m.resolve("@earendil-works/pi-coding-agent/rpc-entry")]}}attachListeners(){this.process.stdout?.setEncoding("utf8"),this.process.stdout?.on("data",e=>{for(this.stdoutBuffer+=e;;){const t=this.stdoutBuffer.indexOf(`
2
+ `);if(t===-1)break;const s=this.stdoutBuffer.slice(0,t).trim();this.stdoutBuffer=this.stdoutBuffer.slice(t+1),s&&this.handleLine(s)}}),this.process.stderr?.setEncoding("utf8"),this.process.stderr?.on("data",e=>{this.stderrBuffer+=e}),this.process.once("error",e=>{this.exited=!0;const t=new Error(`RPC process error: ${e.message}. Stderr: ${this.stderrBuffer}`);this.rejectAllPending(t),this.notifyExit(t)}),this.process.once("exit",(e,t)=>{this.exited=!0;const s=new Error(`RPC process exited (code=${e} signal=${t}). Stderr: ${this.stderrBuffer}`);this.rejectAllPending(s),this.notifyExit(s)})}handleLine(e){const t=JSON.parse(e);switch(t.type){case"response":{if(!t.id)return;const s=this.pendingRequests.get(t.id);if(!s)return;this.pendingRequests.delete(t.id),s.resolve(t);return}case"extension_ui_request":{this.uiRequestHandler?.(t);return}default:for(const s of this.eventListeners)s(t)}}rejectAllPending(e){for(const[t,s]of this.pendingRequests)this.pendingRequests.delete(t),s.reject(e)}notifyExit(e){for(const t of this.exitListeners)t(e)}send(e){if(this.exited)throw new Error(`RPC process is not running. Stderr: ${this.stderrBuffer}`);const t=e.id??`server_${++this.nextRequestId}_${p()}`,s={...e,id:t};return new Promise((d,n)=>{this.pendingRequests.set(t,{resolve:d,reject:n}),this.process.stdin?.write(`${JSON.stringify(s)}
3
+ `,o=>{o&&(this.pendingRequests.delete(t),n(g(o)))})})}handleUiResponse(e){this.exited||this.process.stdin?.write(`${JSON.stringify(e)}
4
+ `)}setUiRequestHandler(e){this.uiRequestHandler=e}onEvent(e){return this.eventListeners.add(e),()=>{this.eventListeners.delete(e)}}onExit(e){return this.exitListeners.add(e),()=>{this.exitListeners.delete(e)}}async dispose(){this.uiRequestHandler=void 0,this.rejectAllPending(new Error("RPC process disposed")),!this.exited&&(this.process.kill("SIGTERM"),await new Promise(e=>{this.process.once("exit",()=>e())}))}}function L(r){return new w(r)}i(L,"createRpcProcessInstance");export{w as RpcProcessInstance,L as createRpcProcessInstance};
@@ -0,0 +1 @@
1
+ var l=Object.defineProperty;var t=(e,r)=>l(e,"name",{value:r,configurable:!0});import{existsSync as n,mkdirSync as p,unlinkSync as a}from"node:fs";import{dirname as m}from"node:path";import{getSocketPath as u}from"./config.js";import{handleIpcRequest as f,openRpcStream as g}from"./handler.js";import{startIpcServer as h}from"./ipc/server.js";import{getRadiusServerBaseUrl as w,isRadiusEnabled as v,radiusPresence as c}from"./radius.js";import{supervisor as d}from"./supervisor.js";async function E(){const e=u();p(m(e),{recursive:!0});const r=await h(Object.assign(f,{openRpcStream:g}));try{if(await d.recoverAfterRestart(),v()){const o=await c.start();console.log(`radius integration enabled: ${e} -> ${w()}`),o&&console.log(`radius machine id: ${o.id}`)}else console.log("radius integration disabled: login radius in ~/.pi/agent/auth.json or set RADIUS_API_KEY")}catch(o){throw r.close(),n(e)&&a(e),o}console.log(`server listening on ${e}`);let s;const i=t(async o=>{s&&(await s,process.exit(o)),s=(async()=>{r.close(),await d.shutdown(),await c.stop(),n(e)&&a(e)})(),await s,process.exit(o)},"shutdown");process.on("SIGINT",()=>{i(0)}),process.on("SIGTERM",()=>{i(0)}),process.on("uncaughtException",o=>{console.error(o),i(1)}),process.on("unhandledRejection",o=>{console.error(o),i(1)}),await new Promise(()=>{})}t(E,"serve");export{E as serve};
@@ -0,0 +1 @@
1
+ var c=Object.defineProperty;var d=(o,s)=>c(o,"name",{value:s,configurable:!0});import{randomUUID as p}from"node:crypto";import{PiServerError as a}from"./errors.js";function h(o){return{id:o.id,createdAt:o.createdAt,updatedAt:o.updatedAt,sessionName:o.name,cwd:o.cwd}}d(h,"toMetadata");class f{static{d(this,"LiveSessionManager")}options;liveSessions=new Map;openingSessions=new Map;constructor(s){this.options=s}async executeCommand(s,t){switch(t.command){case"list":return{command:"list",sessions:await this.listMetadata()};case"create":{const e=p(),i={id:e,cwd:t.cwd,name:t.name,model:t.model,thinkingLevel:t.thinkingLevel},n=await this.acquire(e,()=>this.options.service.createSession(i));await this.attach(s,n);const r=this.forConnection(await this.broadcastSnapshot(n),s);return this.options.broadcastServerSnapshot(),{command:"create",session:r}}case"attach":{const e=await this.acquire(t.sessionId,()=>this.options.service.openSession(t.sessionId));await this.attach(s,e);const i=this.forConnection(await this.broadcastSnapshot(e),s);return this.options.broadcastServerSnapshot(),{command:"attach",session:i}}case"detach":{const e=this.liveSessions.get(t.sessionId);return s.sessionIds.has(t.sessionId)&&(s.sessionIds.delete(t.sessionId),s.extensionUiSessions.delete(t.sessionId),e&&(e.connections.delete(s),e.connections.size>0&&!e.terminal&&!e.disposing&&await this.broadcastSnapshot(e),await this.maybeDispose(e)),this.options.broadcastServerSnapshot()),{command:"detach",sessionId:t.sessionId}}case"prompt":{const e=this.requireAttached(s,t.sessionId);return{command:"prompt",session:await this.runOperation(s,e,()=>e.runtime.prompt({text:t.text}))}}case"steer":{const e=this.requireAttached(s,t.sessionId);return{command:"steer",session:await this.runOperation(s,e,()=>e.runtime.steer({text:t.text}))}}case"abort":{const e=this.requireAttached(s,t.sessionId);return{command:"abort",session:await this.runOperation(s,e,()=>e.runtime.abort())}}case"set_model":{const e=this.requireAttached(s,t.sessionId);return{command:"set_model",session:await this.runOperation(s,e,()=>e.runtime.setModel(t.model))}}case"set_thinking":{const e=this.requireAttached(s,t.sessionId);return{command:"set_thinking",session:await this.runOperation(s,e,()=>e.runtime.setThinking(t.thinkingLevel))}}case"subscribe_extension_ui":return this.requireAttached(s,t.sessionId),s.extensionUiSessions.add(t.sessionId),{command:"subscribe_extension_ui",sessionId:t.sessionId};case"extension_ui_answer":return await this.requireAttached(s,t.sessionId).runtime.answerExtensionUi(t.requestId,t.answer),{command:"extension_ui_answer",sessionId:t.sessionId,requestId:t.requestId}}}async disconnect(s){const t=[...s.sessionIds].map(i=>this.liveSessions.get(i)).filter(i=>i!==void 0);s.sessionIds.clear(),s.extensionUiSessions.clear();for(const i of t)i.connections.delete(s);const e=await Promise.allSettled(t.map(i=>this.maybeDispose(i)));for(const i of e)i.status==="rejected"&&this.options.reportError(i.reason)}async listMetadata(){const s=await this.options.service.listSessions(),t=await Promise.all([...this.liveSessions.values()].filter(n=>!n.disposing).map(async n=>[n.id,await this.normalizedSnapshot(n)])),e=new Map(t),i=s.map(n=>{const r=e.get(n.id);return r?(e.delete(n.id),{...n,...h(r)}):n});for(const n of e.values())i.push(h(n));return i}async close(){const s=await Promise.allSettled([...this.openingSessions.values()]);for(const e of s)e.status==="rejected"&&this.options.reportError(e.reason);const t=[...this.liveSessions.values()];this.liveSessions.clear(),await Promise.all(t.map(async e=>{if(e.disposing){await e.disposing;return}e.unsubscribe(),await e.runtime.dispose()}))}async runOperation(s,t,e){t.operationCount+=1;try{return await e(),this.forConnection(await this.broadcastSnapshot(t),s)}finally{t.operationCount-=1,this.scheduleMaybeDispose(t)}}async acquire(s,t){for(;;){const e=this.liveSessions.get(s);if(e){if(e.terminal)throw new a("session_locked",`Session runtime is terminating: ${s}`);if(e.disposing){await e.disposing;continue}return e}const i=this.openingSessions.get(s);if(i)return i;const n=this.create(s,t);this.openingSessions.set(s,n);try{return await n}finally{this.openingSessions.get(s)===n&&this.openingSessions.delete(s)}}}async create(s,t){const e=await t();if(this.options.isClosing())throw await e.dispose(),new Error("PiServer closed while acquiring a session runtime");let i;try{const n=await e.snapshot();if(n.id!==s)throw new a("invalid_request",`Service returned session ${n.id} for server-assigned session ${s}`);return i={id:s,runtime:e,connections:new Set,unsubscribe:d(()=>{},"unsubscribe"),operationCount:0,ready:!1,terminal:!1},i.unsubscribe=e.subscribe(r=>this.handleRuntimeEvent(i,r)),this.liveSessions.set(s,i),i.ready=!0,i}catch(n){i&&i.unsubscribe();try{await e.dispose()}catch(r){this.options.reportError(r)}throw n}}handleRuntimeEvent(s,t){if(t.type==="error"){this.terminate(s,t.error).catch(e=>this.options.reportError(e));return}if(t.type==="progress"){const e={type:"event",event:{type:"session_progress",sessionId:s.id,progress:t.progress}};for(const i of s.connections)this.options.sendMessage(i,e)}else if(t.type==="extension_ui"){const e={type:"event",event:{type:"extension_ui",sessionId:s.id,payload:t.payload}};for(const i of s.connections)i.extensionUiSessions.has(s.id)&&this.options.sendMessage(i,e)}else this.broadcastSnapshot(s).catch(e=>this.options.reportError(e));this.scheduleMaybeDispose(s)}async terminate(s,t){if(s.terminal)return;s.terminal=!0,this.options.reportError(t),s.unsubscribe();const e=[...s.connections];await Promise.all(e.map(i=>this.options.closeConnection(i.connection))),await Promise.all(e.map(i=>this.options.disconnect(i))),await this.maybeDispose(s)}async normalizedSnapshot(s){const t=await s.runtime.snapshot();if(t.id!==s.id)throw new a("invalid_request",`Runtime session ID changed from ${s.id} to ${t.id}`);return{...t,phase:s.runtime.getPhase(),attached:s.connections.size>0,locked:!0}}forConnection(s,t){return{...s,attached:t.sessionIds.has(s.id)}}async broadcastSnapshot(s){const t=await this.normalizedSnapshot(s),e={type:"event",event:{type:"session_snapshot",snapshot:t}};for(const i of s.connections)this.options.sendMessage(i,e);return t}async attach(s,t){if(s.disconnected||s.stage!=="ready"||s.connection.closed)throw await this.maybeDispose(t),new a("invalid_request","Connection closed while attaching to a session");s.sessionIds.add(t.id),t.connections.add(s)}requireAttached(s,t){if(!s.sessionIds.has(t))throw new a("invalid_request",`Connection is not attached to session ${t}`);const e=this.liveSessions.get(t);if(!e||e.terminal||e.disposing)throw new a("not_found",`Session is not live: ${t}`);return e}scheduleMaybeDispose(s){this.maybeDispose(s).catch(t=>this.options.reportError(t))}async maybeDispose(s){if(this.options.isClosing()||!s.ready||s.disposing||s.connections.size>0||s.operationCount>0||!s.terminal&&s.runtime.getPhase()!=="idle")return s.disposing;s.unsubscribe(),s.disposing=(async()=>{try{await s.runtime.dispose()}finally{this.liveSessions.get(s.id)===s&&this.liveSessions.delete(s.id)}})(),await s.disposing,this.options.isClosing()||this.options.broadcastServerSnapshot()}}export{f as LiveSessionManager};
@@ -0,0 +1 @@
1
+ var a=Object.defineProperty;var i=(e,s)=>a(e,"name",{value:s,configurable:!0});import{PROTOCOL_VERSION as c}from"@earendil-works/pi-protocol";class l{static{i(this,"ServerSnapshotPublisher")}options;revision=0;broadcastQueue=Promise.resolve();constructor(s){this.options=s}get currentRevision(){return this.revision}async get(s){return{serverId:this.options.serverId,protocolVersion:c,revision:this.revision,sessions:await this.options.listSessions(),models:s??await this.options.service.listModels()}}broadcast(){const s=this.broadcastQueue.then(()=>this.performBroadcast());return this.broadcastQueue=s.catch(o=>this.options.reportError(o)),s}async performBroadcast(){const s=[...this.options.connections].filter(t=>t.stage==="ready"&&!t.disconnected);if(s.length===0||this.options.isClosing())return;const o=++this.revision,r=await this.options.service.listModels(),n={type:"event",event:{type:"server_snapshot",snapshot:{...await this.get(r),revision:o}}};for(const t of s)await this.options.sendMessage(t,n)}}export{l as ServerSnapshotPublisher};
@@ -0,0 +1 @@
1
+ var h=Object.defineProperty;var t=(n,e)=>h(n,"name",{value:e,configurable:!0});import{existsSync as i,mkdirSync as x,readFileSync as a,rmSync as S,writeFileSync as u}from"node:fs";import{getInstancesPath as f,getMachinePath as c,getServerDir as l}from"./config.js";function d(){const n=l();i(n)||x(n,{recursive:!0})}t(d,"ensureServerDir");function I(){const n=c();if(!i(n))return;const e=a(n,"utf-8");return JSON.parse(e)}t(I,"loadMachine");function g(n){d(),u(c(),JSON.stringify(n,null,2))}t(g,"saveMachine");function P(){const n=c();i(n)&&S(n)}t(P,"deleteMachine");function s(){const n=f();if(!i(n))return[];const e=a(n,"utf-8");return JSON.parse(e)}t(s,"loadInstances");function o(n){d(),u(f(),JSON.stringify(n,null,2))}t(o,"saveInstances");function J(n){return s().find(e=>e.id===n)}t(J,"getInstance");function M(n){const e=s(),r=e.findIndex(p=>p.id===n.id);if(r===-1){e.push(n),o(e);return}e[r]=n,o(e)}t(M,"upsertInstance");function N(n){const e=s().filter(r=>r.id!==n);o(e)}t(N,"removeInstance");export{P as deleteMachine,J as getInstance,s as loadInstances,I as loadMachine,N as removeInstance,o as saveInstances,g as saveMachine,M as upsertInstance};
@@ -0,0 +1 @@
1
+ var S=Object.defineProperty;var c=(n,e)=>S(n,"name",{value:e,configurable:!0});import{randomUUID as w}from"node:crypto";import{radiusPresence as d}from"./radius.js";import{createRpcProcessInstance as R}from"./rpc-process.js";import{getInstance as g,loadInstances as I,removeInstance as P,saveInstances as l,upsertInstance as u}from"./storage.js";function o(n){return{...n}}c(o,"cloneInstance");const b=new Set(["new_session","switch_session","fork","clone","set_session_name","prompt"]);function f(n){return b.has(n.type)}c(f,"shouldRefreshSessionMetadata");function y(n){return n.success===!0&&n.command==="get_state"&&"data"in n}c(y,"isGetStateSuccess");class A{static{c(this,"ServerSupervisor")}liveInstances=new Map;setStatus(e,s){e.record={...e.record,status:s,lastSeenAt:new Date().toISOString()},u(e.record)}updateRecord(e,s){e.record={...e.record,...s,lastSeenAt:new Date().toISOString()},s.radiusPiId!==void 0&&(e.resources.radiusPiId=s.radiusPiId),s.sessionId!==void 0&&(e.resources.sessionId=s.sessionId),u(e.record)}clearBindings(e){e.unsubscribeEvents?.(),e.unsubscribeExit?.(),e.unsubscribeEvents=void 0,e.unsubscribeExit=void 0,e.onUiRequest=void 0,e.resources.rpcProcess?.setUiRequestHandler(void 0)}bindRpcProcess(e,s){this.clearBindings(e),e.resources.rpcProcess=s,e.unsubscribeEvents=s.onEvent(t=>{for(const r of e.subscribers)r(t)}),e.unsubscribeExit=s.onExit(t=>{this.handleUnexpectedRpcExit(e,t)}),s.setUiRequestHandler(t=>{e.onUiRequest?.(t)})}async handleUnexpectedRpcExit(e,s){if(this.liveInstances.get(e.record.id)===e&&!(e.record.status==="stopping"||e.record.status==="stopped")){if(this.setStatus(e,"error"),this.clearBindings(e),e.resources.rpcProcess=void 0,e.resources.radiusPiId)try{await d.disconnectPi(e.record),this.updateRecord(e,{radiusPiId:void 0})}catch(t){console.error(`Failed to disconnect Radius Pi ${e.record.id}: ${String(t)}`)}this.liveInstances.delete(e.record.id)}}getRpcProcess(e){return e.resources.rpcProcess}async syncInstanceRecord(e){const s=this.getRpcProcess(e);if(!s){this.updateRecord(e,{});return}const t=await s.send({type:"get_state"});if(!y(t)){this.updateRecord(e,{});return}this.updateRecord(e,{sessionId:t.data.sessionId,sessionFile:t.data.sessionFile})}async cleanupAcquiredResources(e){const s=e.resources.rpcProcess;this.clearBindings(e),e.resources.radiusPiId&&(await d.disconnectPi(e.record),e.resources.radiusPiId=void 0,e.record={...e.record,radiusPiId:void 0,lastSeenAt:new Date().toISOString()}),e.resources.sessionId=void 0,s&&(e.resources.rpcProcess=void 0,await s.dispose())}async failSpawn(e,s){this.setStatus(e,"error");try{await this.cleanupAcquiredResources(e)}finally{this.setStatus(e,"stopped"),this.liveInstances.delete(e.record.id)}throw s}updateInstance(e){const s=this.liveInstances.get(e.id);s&&(s.record=e,s.resources.radiusPiId=e.radiusPiId,s.resources.sessionId=e.sessionId),u(e)}openRpcStream(e,s,t){const r=this.liveInstances.get(e),i=r?this.getRpcProcess(r):void 0;if(!(!r||!i))return r.subscribers.add(s),r.onUiRequest=t,{handleRpc:c(async a=>{const h=await i.send(a);return f(a)&&await this.syncInstanceRecord(r),h},"handleRpc"),handleUiResponse:c(a=>{i.handleUiResponse(a)},"handleUiResponse"),close:c(()=>{r.onUiRequest===t&&(r.onUiRequest=void 0),r.subscribers.delete(s)},"close")}}getLiveInstance(e){const s=this.liveInstances.get(e);return s?o(s.record):void 0}listLiveInstances(){return[...this.liveInstances.values()].map(e=>o(e.record))}async recoverAfterRestart(){const e=new Date().toISOString(),s=I().map(t=>({...t,status:t.status==="online"||t.status==="starting"?"stopped":t.status,lastSeenAt:e}));for(const t of s)await d.disconnectPi(t);l(s)}listInstances(){return I().map(o)}getInstance(e){const s=this.liveInstances.get(e);if(s)return o(s.record);const t=g(e);return t?o(t):void 0}async spawnInstance(e){const s=new Date().toISOString(),t={record:{id:w(),status:"starting",cwd:e.cwd,createdAt:s,lastSeenAt:s,label:e.label},resources:{},subscribers:new Set};this.liveInstances.set(t.record.id,t),u(t.record);try{const r=R({cwd:e.cwd});this.bindRpcProcess(t,r),await this.syncInstanceRecord(t);const i=await d.registerPi(t.record);return this.updateRecord(t,{radiusPiId:i.radiusPiId}),this.setStatus(t,"online"),o(t.record)}catch(r){return await this.failSpawn(t,r)}}async stopInstance(e){const s=this.liveInstances.get(e);if(s){this.setStatus(s,"stopping");try{await this.cleanupAcquiredResources(s)}finally{s.record={...s.record,status:"stopped",lastSeenAt:new Date().toISOString()},this.liveInstances.delete(e),P(e)}return o(s.record)}}async handleRpc(e,s){const t=this.liveInstances.get(e),r=t?this.getRpcProcess(t):void 0;if(!t||!r)return;const i=await r.send(s);return f(s)&&await this.syncInstanceRecord(t),i}async shutdown(){for(const e of[...this.liveInstances.keys()])await this.stopInstance(e)}}const p=new A;d.setCoordinator({getLiveInstance(n){return p.getLiveInstance(n)},listLiveInstances(){return p.listLiveInstances()},updateInstance(n){p.updateInstance(n)}});export{A as ServerSupervisor,p as supervisor};
@@ -0,0 +1 @@
1
+ var p=Object.defineProperty;var r=(o,e)=>p(o,"name",{value:e,configurable:!0});import{PiServerError as i}from"../errors.js";const d={provider:"test",id:"small",name:"Test Small",api:"test-api",reasoning:!0,input:["text","image"],contextWindow:16e3,maxTokens:2e3,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},supportedThinkingLevels:["off","medium","high"],authenticated:!0};class a{static{r(this,"Deferred")}promise;resolvePromise;constructor(){this.promise=new Promise(e=>{this.resolvePromise=e})}resolve(e){this.resolvePromise(e)}}class u{static{r(this,"TestSessionRuntime")}disposed=new a;disposeCount=0;steers=[];extensionUiAnswers=[];stored;onDispose;listeners=new Set;pendingPrompt;pendingExtensionUi=new Map;constructor(e,s){this.stored=e,this.onDispose=s}snapshot(){return structuredClone(this.stored.snapshot)}getPhase(){return this.stored.snapshot.phase}async prompt(e){if(this.getPhase()!=="idle")throw new i("busy","A prompt is already running");const s=new a;this.pendingPrompt={input:e,done:s},this.update({phase:"turn",transcript:[...this.stored.snapshot.transcript,{id:`user-${this.stored.snapshot.revision+1}`,role:"user",content:[{type:"text",text:e.text}],timestamp:this.stored.snapshot.revision+1}]});const n=await s.promise==="complete"?{id:`assistant-${this.stored.snapshot.revision+1}`,role:"assistant",content:[{type:"text",text:`reply:${e.text}`}],status:"complete",model:this.stored.snapshot.model,stopReason:"stop",timestamp:this.stored.snapshot.revision+1}:{id:`assistant-${this.stored.snapshot.revision+1}`,role:"assistant",content:[{type:"text",text:""}],status:"aborted",model:this.stored.snapshot.model,stopReason:"aborted",timestamp:this.stored.snapshot.revision+1};this.update({phase:"idle",transcript:[...this.stored.snapshot.transcript,n]}),this.pendingPrompt=void 0}async steer(e){if(this.getPhase()==="idle")throw new i("busy","There is no active prompt to steer");this.steers.push(e),this.update({queuedSteerCount:this.stored.snapshot.queuedSteerCount+1,queuedSteer:[...this.stored.snapshot.queuedSteer,{id:`steer-${this.stored.snapshot.revision+1}`,role:"user",content:[{type:"text",text:e.text}],timestamp:this.stored.snapshot.revision+1}]})}async abort(){if(!this.pendingPrompt)throw new i("busy","There is no active prompt to abort");this.pendingPrompt.done.resolve("aborted")}async setModel(e){if(this.getPhase()!=="idle")throw new i("busy","Session is busy");this.update({model:e})}async setThinking(e){if(this.getPhase()!=="idle")throw new i("busy","Session is busy");this.update({thinkingLevel:e})}async answerExtensionUi(e,s){this.extensionUiAnswers.push({requestId:e,answer:s});const t=this.pendingExtensionUi.get(e);t&&(this.pendingExtensionUi.delete(e),t.resolve(void 0))}emitExtensionUi(e){for(const s of this.listeners)s({type:"extension_ui",payload:e})}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async dispose(){this.disposeCount+=1,this.onDispose(),this.disposed.resolve(void 0)}setPhase(e){this.stored.snapshot={...this.stored.snapshot,phase:e}}finishPrompt(){if(!this.pendingPrompt)throw new Error("No prompt is pending");this.pendingPrompt.done.resolve("complete")}emitProgress(e){for(const s of this.listeners)s({type:"progress",progress:e})}emitError(e){for(const s of this.listeners)s({type:"error",error:e})}emitSnapshot(){for(const e of this.listeners)e({type:"snapshot"})}update(e){this.stored.snapshot={...this.stored.snapshot,...e,revision:this.stored.snapshot.revision+1,updatedAt:this.stored.snapshot.updatedAt+1},this.emitSnapshot()}}class m{static{r(this,"TestServerService")}sessions=new Map;runtimes=new Map;locked=new Set;lastCreatedId;nextListDelay;async listSessions(){const e=this.nextListDelay;return e&&(this.nextListDelay=void 0,e.entered.resolve(void 0),await e.release.promise),[...this.sessions.values()].map(({snapshot:s})=>({id:s.id,createdAt:s.createdAt,updatedAt:s.updatedAt,sessionName:s.name,cwd:s.cwd}))}async listModels(){return[d]}async createSession(e){if(this.lastCreatedId=e.id,this.sessions.has(e.id))throw new i("session_locked","Session already exists");return this.seed(e.id,e.name,e.cwd,e.model,e.thinkingLevel),this.acquire(e.id)}async openSession(e){if(!this.sessions.has(e))throw new i("not_found",`Unknown session: ${e}`);if(this.locked.has(e))throw new i("session_locked",`Session is locked: ${e}`);return this.acquire(e)}seed(e="session-1",s=`Session ${e}`,t="/tmp/pi-server-conformance",n={provider:d.provider,id:d.id},h="off"){this.sessions.set(e,{snapshot:{id:e,name:s,cwd:t,createdAt:1,updatedAt:1,phase:"idle",model:n,thinkingLevel:h,attached:!1,locked:!1,revision:0,transcript:[],queuedSteer:[],queuedSteerCount:0}})}delayNextList(){const e={entered:new a,release:new a};return this.nextListDelay=e,e}latestRuntime(e){const s=this.runtimes.get(e);if(!s?.length)throw new Error(`No runtime for ${e}`);return s.at(-1)}acquire(e){const s=this.sessions.get(e);if(!s)throw new Error(`Unknown session: ${e}`);this.locked.add(e);const t=new u(s,()=>this.locked.delete(e)),n=this.runtimes.get(e)??[];return n.push(t),this.runtimes.set(e,n),t}}export{a as Deferred,d as TEST_MODEL,m as TestServerService,u as TestSessionRuntime};
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@earendil-works/pi-server",
3
- "version": "1.0.20",
3
+ "version": "1.0.23",
4
4
  "description": "experimental server package for pi",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -39,9 +39,9 @@
39
39
  "node": ">=22.19.0"
40
40
  },
41
41
  "dependencies": {
42
- "@earendil-works/chord": "^1.0.20",
43
- "@earendil-works/pi-agent-core": "^1.0.20",
44
- "@earendil-works/pi-ai": "^1.0.20",
45
- "@earendil-works/pi-protocol": "^1.0.20"
42
+ "@earendil-works/chord": "^1.0.23",
43
+ "@earendil-works/pi-agent-core": "^1.0.23",
44
+ "@earendil-works/pi-ai": "^1.0.23",
45
+ "@earendil-works/pi-protocol": "^1.0.23"
46
46
  }
47
47
  }
@@ -0,0 +1,7 @@
1
+ var A=Object.defineProperty;var h=(r,c)=>A(r,"name",{value:c,configurable:!0});import{SessionError as f}from"@earendil-works/pi-agent-core";import{uuidv7 as B}from"@earendil-works/pi-ai";import{sql as o}from"./sql.js";import{copyBranchEntriesThroughSeq as T,deleteBranchEntries as O,insertBranchEntriesForPath as x,insertBranchEntry as p,readBranchContainingEntry as R}from"./storage/branch-entries.js";import{deleteBranchTips as m,insertBranchTip as S,readBranchTipBranchId as C,updateBranchTip as w}from"./storage/branch-tips.js";function L(r,c){m(r,c),O(r,c)}h(L,"deleteBranchCache");function d(r,c){const a=o`SELECT leaf.id
2
+ FROM entries AS leaf
3
+ WHERE leaf.session_id = ${c}
4
+ AND NOT EXISTS (
5
+ SELECT 1 FROM entries AS child WHERE child.session_id = leaf.session_id AND child.parent_id = leaf.id
6
+ )
7
+ ORDER BY leaf.seq`.all(r);L(r,c);for(const n of a)N(r,c,n.id)}h(d,"rebuildBranchCache");function N(r,c,a){o`SAVEPOINT build_branch_cache`.exec(r);try{const n=B();x(r,c,n,a),S(r,c,a,n),o`RELEASE SAVEPOINT build_branch_cache`.exec(r)}catch(n){try{o`ROLLBACK TO SAVEPOINT build_branch_cache`.exec(r),o`RELEASE SAVEPOINT build_branch_cache`.exec(r)}catch{}throw n instanceof f?n:new f("storage",`Failed to build SQLite branch cache at entry ${a}`,n instanceof Error?n:void 0)}}h(N,"buildCachedBranch");function g(r,c,a,n,e,t,i,E){if(p(r,c,a,e,t,i,E),!w(r,c,a,n,e))throw new f("invalid_entry",`Branch tip ${n} changed during append`)}h(g,"extendBranch");function q(r,c,a,n,e,t,i){if(i===null){const _=B();p(r,c,_,a,n,e,t),S(r,c,a,_);return}const E=C(r,c,i);if(E!==void 0){g(r,c,E,i,a,n,e,t);return}const l=R(r,c,i);if(!l)throw new f("invalid_entry",`Branch cache has no branch containing parent entry ${i}`);const u=B();T(r,c,u,l.branchId,l.entrySeq),p(r,c,u,a,n,e,t),S(r,c,a,u)}h(q,"appendEntryToBranchCache");export{q as appendEntryToBranchCache,N as buildCachedBranch,L as deleteBranchCache,d as rebuildBranchCache};
@@ -0,0 +1,36 @@
1
+ var T=Object.defineProperty;var a=(e,s)=>T(e,"name",{value:s,configurable:!0});import{SessionError as m}from"@earendil-works/pi-agent-core";import{applyMigrations as I}from"./migrations.js";import{sql as o}from"./sql.js";import{decodeSessionMetadata as A}from"./storage/sessions.js";function f(e,s){if(!e.ok){const t=e.error.code==="not_found"?"not_found":"storage";throw new m(t,`${s}: ${e.error.message}`,e.error)}return e.value}a(f,"getFileSystemResultOrThrow");function N(e){const s=e.replace(/[\\/]+$/,""),t=Math.max(s.lastIndexOf("/"),s.lastIndexOf("\\"));return t<0?".":t===0?s.slice(0,1):s.slice(0,t)}a(N,"getParentPath");function h(e){if(!e?.aborted)return;if(e.reason instanceof Error)throw e.reason;const s=new Error("The operation was aborted");throw s.name="AbortError",s}a(h,"throwIfAborted");function p(e){o`PRAGMA journal_mode=WAL`.exec(e),o`PRAGMA synchronous=FULL`.exec(e),o`PRAGMA busy_timeout=5000`.exec(e)}a(p,"configureSqliteDatabase");function _(e,s){return!!o`SELECT 1 AS found FROM sqlite_master WHERE type = 'table' AND name = ${s} LIMIT 1`.get(e)}a(_,"tableExists");function u(e){o`INSERT INTO session_search_fts(session_search_fts) VALUES('rebuild')`.run(e)}a(u,"rebuildSearchIndex");function y(e){const s=_(e,"session_search_fts"),t=_(e,"entries");e.transaction(()=>{o`
2
+ CREATE VIRTUAL TABLE IF NOT EXISTS session_search_fts USING fts5(
3
+ payload,
4
+ content = 'entries',
5
+ content_rowid = 'rowid',
6
+ tokenize = 'trigram remove_diacritics 1'
7
+ );
8
+ CREATE TRIGGER IF NOT EXISTS session_search_fts_ai AFTER INSERT ON entries BEGIN
9
+ INSERT INTO session_search_fts(rowid, payload) VALUES (new.rowid, new.payload);
10
+ END;
11
+ CREATE TRIGGER IF NOT EXISTS session_search_fts_ad AFTER DELETE ON entries BEGIN
12
+ INSERT INTO session_search_fts(session_search_fts, rowid, payload) VALUES('delete', old.rowid, old.payload);
13
+ END;
14
+ CREATE TRIGGER IF NOT EXISTS session_search_fts_au AFTER UPDATE OF payload ON entries BEGIN
15
+ INSERT INTO session_search_fts(session_search_fts, rowid, payload) VALUES('delete', old.rowid, old.payload);
16
+ INSERT INTO session_search_fts(rowid, payload) VALUES (new.rowid, new.payload);
17
+ END;
18
+ `.exec(e),!s&&t&&u(e)})}a(y,"ensureSearchSchema");class w{static{a(this,"SqliteSessionSearch")}options;databasePath;constructor(s){this.options=s}async getDatabasePath(){return this.databasePath||(this.databasePath=f(await this.options.env.absolutePath(this.options.databasePath),`Failed to resolve SQLite search database ${this.options.databasePath}`)),this.databasePath}async openDatabase(){const s=await this.getDatabasePath(),t=N(s);f(await this.options.env.createDir(t,{recursive:!0}),`Failed to create SQLite search directory ${t}`);const r=await this.options.sqlite.open(s);try{return p(r),await I(r),y(r),r}catch(n){throw r.close(),n}}async*search(s,t={}){const r=s.trim();if(!r||t.limit!==void 0&&t.limit<=0||t.entryTypes?.length===0)return;h(t.signal);const n=await this.openDatabase();try{const E=`"${r.replaceAll('"','""')}"`,c=["session_search_fts MATCH ?"],d=[E];t.entryTypes!==void 0&&(c.push(`se.type IN (${t.entryTypes.map(()=>"?").join(", ")})`),d.push(...t.entryTypes));const l=n.prepare(`SELECT s.id, s.created_at, s.metadata, s.cwd, s.parent_session_id,
19
+ name_fact.seq IS NOT NULL AS has_session_name,
20
+ name_fact.value AS session_name,
21
+ se.id AS entry_id, se.timestamp, bm25(session_search_fts) AS score
22
+ FROM session_search_fts
23
+ JOIN entries AS se ON se.rowid = session_search_fts.rowid
24
+ JOIN sessions AS s ON s.id = se.session_id
25
+ LEFT JOIN facts AS name_fact
26
+ ON name_fact.session_id = s.id
27
+ AND name_fact.kind = 'name'
28
+ AND name_fact.key IS NULL
29
+ AND name_fact.seq = (
30
+ SELECT MAX(f.seq)
31
+ FROM facts AS f
32
+ WHERE f.session_id = s.id AND f.kind = 'name' AND f.key IS NULL
33
+ )
34
+ WHERE ${c.join(" AND ")}
35
+ ORDER BY score
36
+ LIMIT ?`).iterate(...d,t.limit??-1),S=await this.getDatabasePath();for(const i of l)h(t.signal),yield{sessionId:i.id,metadata:A(i,S),entryId:i.entry_id,timestamp:i.timestamp,score:i.score}}finally{n.close()}}}function F(e){return new w(e)}a(F,"createSqliteSessionSearch");export{F as createSqliteSessionSearch};
@@ -0,0 +1,25 @@
1
+ var $=Object.defineProperty;var c=(r,t)=>$(r,"name",{value:t,configurable:!0});import{SessionError as _}from"@earendil-works/pi-agent-core";import{joinSqlFragments as y,sql as e}from"../sql.js";function R(r,t,s){const n=e`SELECT branch_id, entry_seq
2
+ FROM branch_entries
3
+ WHERE session_id = ${t} AND entry_id = ${s}
4
+ ORDER BY branch_id
5
+ LIMIT 1`.get(r);if(n)return{branchId:n.branch_id,leafSeq:n.entry_seq}}c(R,"readCachedBranch");function T(r,t,s,n){const i=n.order==="oldestFirst",d=[];n.stopAtType!==void 0&&d.push(e`stop.entry_type = ${n.stopAtType}`),n.stopAtId!==void 0&&d.push(e`stop.entry_id = ${n.stopAtId}`);const o=i?e`MIN`:e`MAX`,a=i?e`<=`:e`>=`,h=i?e`>`:e`<`,E=i?e`ASC`:e`DESC`,f=d.length===0?e``:e`SELECT ${o}(stop.entry_seq)
6
+ FROM branch_entries AS stop
7
+ WHERE stop.session_id = ${t}
8
+ AND stop.branch_id = ${s.branchId}
9
+ AND stop.entry_seq <= ${s.leafSeq}
10
+ AND (${y(d," OR ")})`,p=[e`b.session_id = ${t}`,e`b.branch_id = ${s.branchId}`,e`b.entry_seq <= ${s.leafSeq}`];d.length>0&&p.push(e`b.entry_seq ${a} COALESCE((${f}), ${i?s.leafSeq:0})`),n.cursor!==void 0&&p.push(e`b.entry_seq ${h} ${n.cursor.afterSeq}`),n.type!==void 0&&p.push(e`b.entry_type = ${n.type}`),n.customType!==void 0&&p.push(e`b.custom_type = ${n.customType}`);const u=n.limit===void 0?e``:e` LIMIT ${n.limit}`;return e`SELECT e.session_id, e.id, e.seq AS entry_seq, e.parent_id, e.type, e.timestamp, e.payload
11
+ FROM branch_entries AS b
12
+ JOIN entries AS e ON e.session_id = b.session_id AND e.id = b.entry_id
13
+ WHERE ${y(p," AND ")}
14
+ ORDER BY b.entry_seq ${E}${u}`.all(r)}c(T,"queryCachedBranchRows");function I(r,t){e`DELETE FROM branch_entries WHERE session_id = ${t}`.run(r)}c(I,"deleteBranchEntries");function b(r,t,s,n,i,d,o){e`INSERT INTO branch_entries
15
+ (session_id, branch_id, entry_id, entry_seq, entry_type, custom_type)
16
+ VALUES (${t}, ${s}, ${n}, ${i}, ${d}, ${o})`.run(r)}c(b,"insertBranchEntry");function l(r){if(r.type!=="custom")return null;try{const t=JSON.parse(r.payload);if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Payload is not an object");const s=t.customType;if(typeof s!="string")throw new Error("Invalid custom payload");return s}catch(t){throw new _("invalid_entry",`Invalid SQLite session entry ${r.id}: failed to decode entry ${r.id}`,t instanceof Error?t:void 0)}}c(l,"customTypeFromPayload");function N(r,t,s,n){const i=[],d=new Set;let o=n;for(;o!==null;){if(d.has(o))throw new _("invalid_entry",`Entry parent cycle at ${o}`);d.add(o);const a=e`SELECT id, seq, parent_id, type, payload
17
+ FROM entries
18
+ WHERE session_id = ${t} AND id = ${o}`.get(r);if(!a)throw new _("invalid_entry",`Entry ${o} not found`);i.push(a),o=a.parent_id}for(const a of i.reverse())b(r,t,s,a.id,a.seq,a.type,l(a))}c(N,"insertBranchEntriesForPath");function O(r,t,s){const n=e`SELECT b.branch_id, b.entry_seq
19
+ FROM branch_entries AS b
20
+ WHERE b.session_id = ${t} AND b.entry_id = ${s}
21
+ ORDER BY b.branch_id
22
+ LIMIT 1`.get(r);return n===void 0?void 0:{branchId:n.branch_id,entrySeq:n.entry_seq}}c(O,"readBranchContainingEntry");function q(r,t,s,n,i){e`INSERT INTO branch_entries (session_id, branch_id, entry_id, entry_seq, entry_type, custom_type)
23
+ SELECT session_id, ${s}, entry_id, entry_seq, entry_type, custom_type
24
+ FROM branch_entries
25
+ WHERE session_id = ${t} AND branch_id = ${n} AND entry_seq <= ${i}`.run(r)}c(q,"copyBranchEntriesThroughSeq");export{q as copyBranchEntriesThroughSeq,I as deleteBranchEntries,N as insertBranchEntriesForPath,b as insertBranchEntry,T as queryCachedBranchRows,O as readBranchContainingEntry,R as readCachedBranch};
@@ -0,0 +1,2 @@
1
+ var c=Object.defineProperty;var t=(i,n)=>c(i,"name",{value:n,configurable:!0});import{sql as s}from"../sql.js";function E(i,n){return s`SELECT tip_id FROM branch_tips WHERE session_id = ${n} ORDER BY tip_id`.all(i).map(r=>r.tip_id)}t(E,"readBranchTipIds");function o(i,n,r){return s`SELECT branch_id FROM branch_tips WHERE session_id = ${n} AND tip_id = ${r}`.get(i)?.branch_id}t(o,"readBranchTipBranchId");function h(i,n,r,p){s`INSERT INTO branch_tips (session_id, tip_id, branch_id) VALUES (${n}, ${r}, ${p})`.run(i)}t(h,"insertBranchTip");function u(i,n,r,p,e){return s`UPDATE branch_tips SET tip_id = ${e}
2
+ WHERE session_id = ${n} AND branch_id = ${r} AND tip_id = ${p}`.run(i).changes===1}t(u,"updateBranchTip");function T(i,n){s`DELETE FROM branch_tips WHERE session_id = ${n}`.run(i)}t(T,"deleteBranchTips");export{T as deleteBranchTips,h as insertBranchTip,o as readBranchTipBranchId,E as readBranchTipIds,u as updateBranchTip};
@@ -0,0 +1,7 @@
1
+ var $=Object.defineProperty;var r=(s,i)=>$(s,"name",{value:i,configurable:!0});import{sql as t}from"../sql.js";function f(s){const{type:i,id:e,seq:n,parentId:a,timestamp:o,...d}=s;return d}r(f,"entryPayload");function m(s,i,e){t`INSERT INTO entries (session_id, id, seq, parent_id, type, timestamp, payload)
2
+ VALUES (${i}, ${e.id}, ${e.seq}, ${e.parentId}, ${e.type}, ${e.timestamp}, ${e.payload})`.run(s)}r(m,"insertEntryRow");function y(s,i,e){return t`SELECT session_id, seq, id, parent_id, type, timestamp, payload
3
+ FROM entries
4
+ WHERE session_id = ${i} AND id = ${e}`.get(s)}r(y,"readEntryRow");function l(s,i,e={}){const n=e.order==="oldestFirst",a=e.afterSeq===void 0?t``:t` AND seq > ${e.afterSeq}`,o=e.cursor===void 0?t``:n?t` AND seq > ${e.cursor.afterSeq}`:t` AND seq < ${e.cursor.afterSeq}`,d=e.type===void 0?t``:t` AND type = ${e.type}`,E=n?t`ASC`:t`DESC`,p=e.limit===void 0?t``:t` LIMIT ${e.limit}`;return t`SELECT session_id, seq, id, parent_id, type, timestamp, payload
5
+ FROM entries
6
+ WHERE session_id = ${i}${a}${o}${d}
7
+ ORDER BY seq ${E}${p}`.all(s)}r(l,"readEntryRows");function q(s,i,e){return!!t`SELECT 1 AS found FROM entries WHERE session_id = ${i} AND id = ${e} LIMIT 1`.get(s)}r(q,"idExistsInEntries");function R(s,i){t`DELETE FROM entries WHERE session_id = ${i}`.run(s)}r(R,"deleteEntryRows");export{R as deleteEntryRows,f as entryPayload,q as idExistsInEntries,m as insertEntryRow,y as readEntryRow,l as readEntryRows};
@@ -0,0 +1,20 @@
1
+ var f=Object.defineProperty;var t=(e,s)=>f(e,"name",{value:s,configurable:!0});import{sql as i}from"../sql.js";function o(e,s,n,a,d,E){i`INSERT INTO facts (session_id, seq, kind, key, value) VALUES (${s}, ${n}, ${a}, ${d}, ${E})`.run(e)}t(o,"appendFact");function k(e,s,n,a){return i`SELECT session_id, seq, kind, key, value
2
+ FROM facts INDEXED BY idx_facts_session_kind_key_seq
3
+ WHERE session_id = ${s} AND kind = ${n} AND key IS ${a}
4
+ ORDER BY seq DESC
5
+ LIMIT 1`.get(e)}t(k,"readLatestFact");function r(e,s){return i`SELECT f.key, f.value
6
+ FROM facts AS f INDEXED BY idx_facts_session_kind_key_seq
7
+ WHERE f.session_id = ${s}
8
+ AND f.kind = 'label'
9
+ AND f.value IS NOT NULL
10
+ AND f.seq = (
11
+ SELECT MAX(candidate.seq)
12
+ FROM facts AS candidate INDEXED BY idx_facts_session_kind_key_seq
13
+ WHERE candidate.session_id = f.session_id
14
+ AND candidate.kind = f.kind
15
+ AND candidate.key IS f.key
16
+ )
17
+ ORDER BY f.key`.all(e)}t(r,"readLatestLabelFacts");function D(e,s,n={}){const a=n.afterSeq===void 0?i``:i` AND seq > ${n.afterSeq}`,d=n.limit===void 0?i``:i` LIMIT ${n.limit}`;return i`SELECT session_id, seq, kind, key, value
18
+ FROM facts
19
+ WHERE session_id = ${s}${a}
20
+ ORDER BY seq${d}`.all(e)}t(D,"readFactRows");function R(e,s){i`DELETE FROM facts WHERE session_id = ${s}`.run(e)}t(R,"deleteFactRows");export{o as appendFact,R as deleteFactRows,D as readFactRows,k as readLatestFact,r as readLatestLabelFacts};
@@ -0,0 +1,26 @@
1
+ var d=Object.defineProperty;var t=(n,i)=>d(n,"name",{value:i,configurable:!0});import{SessionError as r}from"@earendil-works/pi-agent-core";import{sql as s}from"../sql.js";function p(n,i,e="main",o=null){s`INSERT INTO lanes (session_id, lane, leaf_id, open_operation_id)
2
+ VALUES (${i}, ${e}, ${o}, NULL)`.run(n)}t(p,"createInitialLane");function S(n,i){const e=s`SELECT
3
+ l.session_id,
4
+ l.lane,
5
+ l.leaf_id,
6
+ l.open_operation_id,
7
+ (l.leaf_id IS NULL OR EXISTS (
8
+ SELECT 1 FROM entries AS e WHERE e.session_id = l.session_id AND e.id = l.leaf_id
9
+ )) AS leaf_exists
10
+ FROM lanes AS l
11
+ WHERE l.session_id = ${i}
12
+ ORDER BY l.lane`.all(n);for(const o of e)if(o.leaf_exists===0)throw new r("storage",`Lane ${o.lane} points at missing entry ${o.leaf_id}`);return e.map(({session_id:o,lane:a,leaf_id:l,open_operation_id:E})=>({session_id:o,lane:a,leaf_id:l,open_operation_id:E}))}t(S,"readLanes");function f(n,i,e){return s`SELECT session_id, lane, leaf_id, open_operation_id
13
+ FROM lanes
14
+ WHERE session_id = ${i} AND lane = ${e}`.get(n)}t(f,"readLane");function R(n,i,e){const o=s`SELECT
15
+ l.leaf_id,
16
+ (l.leaf_id IS NULL OR EXISTS (
17
+ SELECT 1 FROM entries AS e WHERE e.session_id = l.session_id AND e.id = l.leaf_id
18
+ )) AS leaf_exists
19
+ FROM lanes AS l
20
+ WHERE l.session_id = ${i} AND l.lane = ${e}`.get(n);if(!o)throw new r("invalid_lane",`Lane not found: ${e}`);if(o.leaf_exists===0)throw new r("storage",`Entry ${o.leaf_id} not found`);return{leafId:o.leaf_id}}t(R,"readLaneHead");function c(n,i,e,o,a){s`INSERT INTO lanes (session_id, lane, leaf_id, open_operation_id)
21
+ VALUES (${i}, ${o}, ${a}, NULL)`.run(n),_(n,i,e,o,a)}t(c,"createLane");function T(n,i,e,o,a){if(s`UPDATE lanes SET leaf_id = ${a} WHERE session_id = ${i} AND lane = ${o}`.run(n).changes!==1)throw new r("invalid_lane",`Lane not found: ${o}`);_(n,i,e,o,a)}t(T,"moveLane");function A(n,i,e,o){if(s`UPDATE lanes SET leaf_id = ${o} WHERE session_id = ${i} AND lane = ${e}`.run(n).changes!==1)throw new r("invalid_lane",`Lane not found: ${e}`)}t(A,"setLaneLeaf");function N(n,i,e,o){if(s`UPDATE lanes SET open_operation_id = ${o}
22
+ WHERE session_id = ${i} AND lane = ${e} AND open_operation_id IS NULL`.run(n).changes===1)return;const l=f(n,i,e);throw l?new r("storage",`Lane ${e} already has an open operation ${l.open_operation_id}`):new r("invalid_lane",`Lane not found: ${e}`)}t(N,"startLaneOperation");function w(n,i,e,o){s`UPDATE lanes SET open_operation_id = NULL
23
+ WHERE session_id = ${i} AND lane = ${e} AND open_operation_id = ${o}`.run(n)}t(w,"finishLaneOperation");function D(n,i,e={}){const o=e.afterSeq===void 0?s``:s` AND seq > ${e.afterSeq}`,a=e.limit===void 0?s``:s` LIMIT ${e.limit}`;return s`SELECT session_id, seq, lane, leaf_id
24
+ FROM lane_moves
25
+ WHERE session_id = ${i}${o}
26
+ ORDER BY seq${a}`.all(n)}t(D,"readLaneMoveRows");function O(n,i){s`DELETE FROM lane_moves WHERE session_id = ${i}`.run(n),s`DELETE FROM lanes WHERE session_id = ${i}`.run(n)}t(O,"deleteLaneRows");function _(n,i,e,o,a){s`INSERT INTO lane_moves (session_id, seq, lane, leaf_id) VALUES (${i}, ${e}, ${o}, ${a})`.run(n)}t(_,"appendLaneMove");export{p as createInitialLane,c as createLane,O as deleteLaneRows,w as finishLaneOperation,T as moveLane,f as readLane,R as readLaneHead,D as readLaneMoveRows,S as readLanes,A as setLaneLeaf,N as startLaneOperation};
@@ -0,0 +1,9 @@
1
+ var r=Object.defineProperty;var p=(e,o)=>r(e,"name",{value:o,configurable:!0});import{SessionError as a}from"@earendil-works/pi-agent-core";import{joinSqlFragments as $,sql as i}from"../sql.js";function f(e,o,n){i`INSERT INTO records
2
+ (session_id, seq, id, lane, run_id, type, op_kind, timestamp, payload)
3
+ VALUES (${o}, ${n.seq}, ${n.id}, ${n.lane}, ${n.runId??null}, ${n.type}, ${n.opKind??null}, ${n.timestamp}, ${n.payload})`.run(e)}p(f,"appendRecordRow");function R(e,o,n){return!!i`SELECT 1 AS found FROM records WHERE session_id = ${o} AND id = ${n} LIMIT 1`.get(e)}p(R,"idExistsInRecords");function u(e,o){i`DELETE FROM records WHERE session_id = ${o}`.run(e)}p(u,"deleteRecordRows");function m(e,o,n={}){const t=[i`session_id = ${o}`];n.lane!==void 0&&t.push(i`lane = ${n.lane}`),n.type!==void 0&&t.push(i`type = ${n.type}`),n.runId!==void 0&&t.push(i`run_id = ${n.runId}`),n.operationKind!==void 0&&t.push(i`op_kind = ${n.operationKind}`),n.afterSeq!==void 0&&t.push(i`seq > ${n.afterSeq}`);const s=n.order==="oldestFirst"?i`ASC`:i`DESC`,d=n.limit===void 0?i``:i` LIMIT ${n.limit}`;return i`SELECT session_id, seq, id, lane, run_id, type, op_kind, timestamp, payload
4
+ FROM records
5
+ WHERE ${$(t," AND ")}
6
+ ORDER BY seq ${s}${d}`.all(e)}p(m,"readRecordRows");function c(e,o,n,t={}){const s=i`SELECT open_operation_id FROM lanes WHERE session_id = ${o} AND lane = ${n}`.get(e);if(!s?.open_operation_id)return[];const d=i`SELECT session_id, seq, id, lane, run_id, type, op_kind, timestamp, payload
7
+ FROM records
8
+ WHERE session_id = ${o}
9
+ AND id = ${s.open_operation_id}`.get(e);if(!d)throw new a("storage",`Lane ${n} points at missing open operation ${s.open_operation_id}`);if(d.lane!==n||d.type!=="operation_started")throw new a("storage",`Lane ${n} points at invalid open operation ${s.open_operation_id}`);return[d]}p(c,"readOpenOperationRows");export{f as appendRecordRow,u as deleteRecordRows,R as idExistsInRecords,c as readOpenOperationRows,m as readRecordRows};
@@ -0,0 +1 @@
1
+ var i=Object.defineProperty;var o=(s,e)=>i(s,"name",{value:e,configurable:!0});import{SessionError as r}from"@earendil-works/pi-agent-core";import{sql as t}from"../sql.js";function _(s,e,n=1){t`INSERT INTO session_sequences (session_id, next_seq) VALUES (${e}, ${n})`.run(s)}o(_,"createSequence");function x(s,e){const n=t`SELECT next_seq FROM session_sequences WHERE session_id = ${e}`.get(s);if(!n)throw new r("storage",`Missing sequence row for session ${e}`);return n.next_seq}o(x,"getNextSequence");function u(s,e,n){t`UPDATE session_sequences SET next_seq = ${n} WHERE session_id = ${e}`.run(s)}o(u,"setNextSequence");function S(s,e,n){u(s,e,n+1)}o(S,"advanceSequence");function f(s,e){t`DELETE FROM session_sequences WHERE session_id = ${e}`.run(s)}o(f,"deleteSequence");export{S as advanceSequence,_ as createSequence,f as deleteSequence,x as getNextSequence,u as setNextSequence};
@@ -0,0 +1,10 @@
1
+ var c=Object.defineProperty;var e=(o,s)=>c(o,"name",{value:s,configurable:!0});import{SessionError as a}from"@earendil-works/pi-agent-core";import{sql as n}from"../sql.js";function d(o,s,t=0){n`INSERT INTO session_stats
2
+ (session_id, message_count, cached_tokens, uncached_tokens, total_tokens, cost_total)
3
+ VALUES (${s}, ${t}, 0, 0, 0, 0)`.run(o)}e(d,"createStats");function l(o,s){const t=n`SELECT session_id, message_count, cached_tokens, uncached_tokens, total_tokens, cost_total
4
+ FROM session_stats
5
+ WHERE session_id = ${s}`.get(o);if(!t)throw new a("storage",`Missing stats row for session ${s}`);return{messageCount:t.message_count,cachedTokens:t.cached_tokens,uncachedTokens:t.uncached_tokens,totalTokens:t.total_tokens,costTotal:t.cost_total}}e(l,"readStats");function E(o,s){if(n`UPDATE session_stats SET message_count = message_count + 1 WHERE session_id = ${s}`.run(o).changes!==1)throw new a("storage",`Missing stats row for session ${s}`)}e(E,"incrementMessageCount");function h(o,s,t){if(n`UPDATE session_stats
6
+ SET cached_tokens = cached_tokens + ${t.cacheRead},
7
+ uncached_tokens = uncached_tokens + ${t.input+t.cacheWrite},
8
+ total_tokens = total_tokens + ${t.totalTokens},
9
+ cost_total = cost_total + ${t.cost.total}
10
+ WHERE session_id = ${s}`.run(o).changes!==1)throw new a("storage",`Missing stats row for session ${s}`)}e(h,"addUsageToStats");function k(o,s){n`DELETE FROM session_stats WHERE session_id = ${s}`.run(o)}e(k,"deleteStats");export{h as addUsageToStats,d as createStats,k as deleteStats,E as incrementMessageCount,l as readStats};
@@ -0,0 +1,29 @@
1
+ var d=Object.defineProperty;var a=(e,n)=>d(e,"name",{value:n,configurable:!0});import{assertJsonSerializable as o,SessionError as r}from"@earendil-works/pi-agent-core";import{sql as i}from"../sql.js";function f(e,n){if(e===null)return;let s;try{s=JSON.parse(e)}catch(t){throw new r("storage",`Invalid SQLite session ${n}: metadata is not valid JSON`,t instanceof Error?t:void 0)}if(typeof s!="object"||s===null||Array.isArray(s))throw new r("storage",`Invalid SQLite session ${n}: metadata must be an object`);return s}a(f,"parseMetadata");function E(e,n){return!!i`SELECT 1 AS found FROM sessions WHERE id = ${n}`.get(e)}a(E,"sessionExists");function c(e){if(e===void 0)return null;if(typeof e!="object"||e===null||Array.isArray(e))throw new r("invalid_payload","SQLite session metadata must be an object");return o(e),JSON.stringify(e)}a(c,"serializeMetadata");function l(e,n){i`INSERT INTO sessions (id, created_at, metadata, cwd, parent_session_id)
2
+ VALUES (${n.id}, ${n.createdAt}, ${c(n.metadata)}, ${n.cwd}, ${n.parentSessionId??null})`.run(e)}a(l,"insertSessionRow");function A(e,n){return i`SELECT s.id, s.created_at, s.metadata, s.cwd, s.parent_session_id,
3
+ name_fact.seq IS NOT NULL AS has_session_name,
4
+ name_fact.value AS session_name
5
+ FROM sessions AS s
6
+ LEFT JOIN facts AS name_fact
7
+ ON name_fact.session_id = s.id
8
+ AND name_fact.kind = 'name'
9
+ AND name_fact.key IS NULL
10
+ AND name_fact.seq = (
11
+ SELECT MAX(f.seq)
12
+ FROM facts AS f
13
+ WHERE f.session_id = s.id AND f.kind = 'name' AND f.key IS NULL
14
+ )
15
+ WHERE s.id = ${n}`.get(e)}a(A,"readSessionRow");function N(e,n={}){const s=n.cwd===void 0?i``:i`WHERE s.cwd = ${n.cwd}`;return i`SELECT s.id, s.created_at, s.metadata, s.cwd, s.parent_session_id,
16
+ name_fact.seq IS NOT NULL AS has_session_name,
17
+ name_fact.value AS session_name
18
+ FROM sessions AS s
19
+ LEFT JOIN facts AS name_fact
20
+ ON name_fact.session_id = s.id
21
+ AND name_fact.kind = 'name'
22
+ AND name_fact.key IS NULL
23
+ AND name_fact.seq = (
24
+ SELECT MAX(f.seq)
25
+ FROM facts AS f
26
+ WHERE f.session_id = s.id AND f.kind = 'name' AND f.key IS NULL
27
+ )
28
+ ${s}
29
+ ORDER BY s.created_at DESC`.all(e)}a(N,"readSessionRows");function L(e,n){i`DELETE FROM sessions WHERE id = ${n}`.run(e)}a(L,"deleteSessionRow");function S(e,n){if(e===null)return;let s;try{s=JSON.parse(e)}catch(t){throw new r("storage",`Invalid SQLite session ${n}: name is not valid JSON`,t instanceof Error?t:void 0)}if(typeof s!="string")throw new r("storage",`Invalid SQLite session ${n}: name must be a string`);return s}a(S,"parseSessionName");function p(e,n){const s=f(e.metadata,e.id),t=e.has_session_name===0?void 0:S(e.session_name,e.id);return{id:e.id,createdAt:e.created_at,...t===void 0?{}:{name:t},cwd:e.cwd,path:n,parentSessionId:e.parent_session_id??void 0,metadata:s}}a(p,"decodeSessionMetadata");export{p as decodeSessionMetadata,L as deleteSessionRow,l as insertSessionRow,A as readSessionRow,N as readSessionRows,E as sessionExists};
@@ -0,0 +1,14 @@
1
+ var d=Object.defineProperty;var i=(e,r)=>d(e,"name",{value:r,configurable:!0});import{sql as _}from"../sql.js";function a(e,r,s,o,t){const n=_`INSERT INTO writer_leases (session_id, owner_id, fence, expires_at_ms)
2
+ VALUES (${r}, ${s}, 1, ${t})
3
+ ON CONFLICT(session_id) DO UPDATE SET
4
+ owner_id = excluded.owner_id,
5
+ fence = writer_leases.fence + 1,
6
+ expires_at_ms = excluded.expires_at_ms
7
+ WHERE writer_leases.expires_at_ms <= ${o}
8
+ RETURNING owner_id, fence, expires_at_ms`.get(e);return n===void 0?void 0:{ownerId:n.owner_id,fence:n.fence,expiresAtMs:n.expires_at_ms}}i(a,"acquireWriterLease");function f(e,r,s,o,t){const n=_`UPDATE writer_leases
9
+ SET expires_at_ms = ${t}
10
+ WHERE session_id = ${r}
11
+ AND owner_id = ${s.ownerId}
12
+ AND fence = ${s.fence}
13
+ AND expires_at_ms > ${o}`.run(e);return n.changes===1&&(s.expiresAtMs=t),n.changes===1}i(f,"renewWriterLease");function w(e,r,s){_`DELETE FROM writer_leases
14
+ WHERE session_id = ${r} AND owner_id = ${s.ownerId} AND fence = ${s.fence}`.run(e)}i(w,"releaseWriterLease");function u(e,r){_`DELETE FROM writer_leases WHERE session_id = ${r}`.run(e)}i(u,"deleteWriterLease");export{a as acquireWriterLease,u as deleteWriterLease,w as releaseWriterLease,f as renewWriterLease};
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@earendil-works/pi-session-backend-sqlite-node",
3
- "version": "1.0.20",
3
+ "version": "1.0.23",
4
4
  "description": "Node sqlite session backend for @earendil-works/pi-agent-core sessions",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -27,7 +27,7 @@
27
27
  "node": ">=22.19.0"
28
28
  },
29
29
  "dependencies": {
30
- "@earendil-works/pi-ai": "^1.0.20",
31
- "@earendil-works/pi-agent-core": "^1.0.20"
30
+ "@earendil-works/pi-ai": "^1.0.23",
31
+ "@earendil-works/pi-agent-core": "^1.0.23"
32
32
  }
33
33
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@earendil-works/pi-telemetry",
3
- "version": "1.0.20",
3
+ "version": "1.0.23",
4
4
  "description": "Vendor-neutral telemetry contracts and typed schema utilities for pi",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@earendil-works/pi-tui",
3
- "version": "1.0.20",
3
+ "version": "1.0.23",
4
4
  "description": "Terminal User Interface library with differential rendering for efficient text-based applications",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -0,0 +1 @@
1
+ var h=Object.defineProperty;var s=(e,o)=>h(e,"name",{value:o,configurable:!0});import{AgentHarness as H,createBashTool as O,createEditTool as A,createReadTool as _,createWriteTool as G}from"@earendil-works/pi-agent-core";import{getExperimentalToolSampling as L}from"../core/experimental.js";import{buildSystemPrompt as M}from"../core/system-prompt.js";import{bashToolSystemPromptContribution as P}from"../core/tools/bash.js";import{editToolSystemPromptContribution as v}from"../core/tools/edit.js";import{readToolSystemPromptContribution as y}from"../core/tools/read.js";import{writeToolSystemPromptContribution as E}from"../core/tools/write.js";function d(e,o,p){return{...e,...p,constrainedSampling:L(),execute:s((m,t,n,l)=>e.execute(m,t,n,l,o),"execute")}}s(d,"createCodingAgentHarnessTool");function x(e){const o=e.activeToolNames.flatMap(t=>{const n=e.tools.find(l=>l.name===t);return n?[n]:[]}),p=Object.fromEntries(o.flatMap(t=>{const n=t.promptSnippet?.replace(/[\r\n]+/g," ").replace(/\s+/g," ").trim();return n?[[t.name,n]]:[]})),m=o.flatMap(t=>t.promptGuidelines??[]);return M({...e.systemPromptOptions,cwd:e.cwd,selectedTools:o.map(t=>t.name),toolSnippets:p,promptGuidelines:m})}s(x,"buildCodingAgentHarnessSystemPrompt");async function W(e){const{env:o,bashCommandPrefix:p,sessionFile:m,systemPromptOptions:t,tools:n,activeToolNames:l,systemPrompt:b,...w}=e;let u;const g=s(()=>{if(!u)throw new Error("Coding-agent Harness callback ran before Harness initialization");return u},"getHarness");let c=n;if(c===void 0){const i=await e.session.getMetadata(),a={env:o};c=[d(_(),a,{promptSnippet:y.snippet,promptGuidelines:y.guidelines}),d(O({commandPrefix:p,prepare:s(async r=>{const T=g(),[f,N]=await Promise.all([T.getModel(),T.getThinkingLevel()]);r.env.PI_SESSION_ID=i.id,r.env.PI_SESSION_FILE=m??"",r.env.PI_PROVIDER=f.provider,r.env.PI_MODEL=f.id,r.env.PI_REASONING_LEVEL=N},"prepare")}),a,{promptSnippet:P.snippet,promptGuidelines:P.guidelines}),d(A(),a,{promptSnippet:v.snippet,promptGuidelines:v.guidelines}),d(G(),a,{promptSnippet:E.snippet,promptGuidelines:E.guidelines})]}const I=[...l??c.map(i=>i.name)],C=b??(async()=>{const i=g(),[a,r]=await Promise.all([i.getTools(),i.getActiveTools()]);return x({cwd:o.cwd,tools:a,activeToolNames:r,systemPromptOptions:t})}),S=await H.create({...w,tools:c,activeToolNames:I,systemPrompt:C});return u=S.harness,S}s(W,"createCodingAgentHarness");export{x as buildCodingAgentHarnessSystemPrompt,W as createCodingAgentHarness};
@@ -1 +1 @@
1
- var d=Object.defineProperty;var a=(e,n)=>d(e,"name",{value:n,configurable:!0});import{getNativeClipboard as g}from"@earendil-works/pi-tui";import{randomUUID as y}from"crypto";import{readFileSync as w,unlinkSync as b}from"fs";import{tmpdir as S}from"os";import{join as T}from"path";import{runClipboardCommand as s}from"./clipboard-command.js";import{detectSupportedImageMimeType as I}from"./mime.js";import{loadPhoton as h}from"./photon.js";import{isWSL as P}from"./wsl.js";const m=["image/png","image/jpeg","image/webp","image/gif"],u=1e3,M=5e3;function _(e=process.env){return!!e.WAYLAND_DISPLAY||e.XDG_SESSION_TYPE==="wayland"}a(_,"isWaylandSession");function l(e){return e.split(";")[0]?.trim().toLowerCase()??e.toLowerCase()}a(l,"baseMimeType");function V(e){switch(l(e)){case"image/png":return"png";case"image/jpeg":return"jpg";case"image/webp":return"webp";case"image/gif":return"gif";default:return null}}a(V,"extensionForImageMimeType");function f(e){const n=e.map(t=>t.trim()).filter(Boolean).map(t=>({raw:t,base:l(t)}));for(const t of m){const r=n.find(o=>o.base===t);if(r)return r.raw}return n.find(t=>t.base.startsWith("image/"))?.raw??null}a(f,"selectPreferredImageMimeType");function E(e){const n=l(e);return m.some(i=>i===n)}a(E,"isSupportedImageMimeType");async function A(e){const n=await h();if(!n)return null;try{const i=n.PhotonImage.new_from_byteslice(e);try{return i.get_bytes()}finally{i.free()}}catch{return null}}a(A,"convertToPng");async function C(){const e=await s("wl-paste",["--list-types"],{timeoutMs:u});if(e===void 0)return;const n=e.toString("utf-8").split(/\r?\n/).map(r=>r.trim()).filter(Boolean),i=f(n);if(!i)return null;const t=await s("wl-paste",["--type",i,"--no-newline"]);if(t!==void 0)return t.length===0?null:{bytes:t,mimeType:l(i)}}a(C,"readClipboardImageViaWlPaste");async function W(){const e=T(S(),`pi-wsl-clip-${y()}.png`);try{const n=await s("wslpath",["-w",e],{timeoutMs:u});if(n===void 0)return null;const i=n.toString("utf-8").trim();if(!i)return null;const r=["Add-Type -AssemblyName System.Windows.Forms","Add-Type -AssemblyName System.Drawing",`$path = '${i.replaceAll("'","''")}'`,"$img = [System.Windows.Forms.Clipboard]::GetImage()","if ($img) { $img.Save($path, [System.Drawing.Imaging.ImageFormat]::Png); Write-Output 'ok' } else { Write-Output 'empty' }"].join("; "),o=await s("powershell.exe",["-NoProfile","-Command",r],{timeoutMs:M});if(o===void 0||o.toString("utf-8").trim()!=="ok")return null;const p=w(e);return p.length===0?null:{bytes:new Uint8Array(p),mimeType:"image/png"}}catch{return null}finally{try{b(e)}catch{}}}a(W,"readClipboardImageViaPowerShell");async function L(){const e=await s("xclip",["-selection","clipboard","-t","TARGETS","-o"],{timeoutMs:u});let n=[];e!==void 0&&(n=e.toString("utf-8").split(/\r?\n/).map(r=>r.trim()).filter(Boolean));const i=f(n);if(e!==void 0&&!i)return null;const t=new Set(i?[i,...m]:m);for(const r of t){const o=await s("xclip",["-selection","clipboard","-t",r,"-o"]);if(o!==void 0&&o.length>0)return{bytes:o,mimeType:l(r)}}}a(L,"readClipboardImageViaXclip");async function c(){const e=await g()?.getImage();if(e!==void 0)return e?.length?{bytes:e,mimeType:I(e)??"application/octet-stream"}:null}a(c,"readClipboardImageViaNativeClipboard");async function G(e){const n=e?.env??process.env,i=e?.platform??process.platform;if(n.TERMUX_VERSION)return null;let t;if(i==="linux"){const r=P(n);(_(n)||r)&&(t=await C()),t===void 0&&(t=await L()),!t&&r&&(t=await W()??t),t===void 0&&(t=await c())}else t=await c();if(!t)return null;if(!E(t.mimeType)){const r=await A(t.bytes);return r?{bytes:r,mimeType:"image/png"}:null}return t}a(G,"readClipboardImage");export{V as extensionForImageMimeType,_ as isWaylandSession,G as readClipboardImage};
1
+ var d=Object.defineProperty;var a=(e,n)=>d(e,"name",{value:n,configurable:!0});import{getNativeClipboard as g}from"@earendil-works/pi-tui";import{randomUUID as y}from"crypto";import{readFileSync as w,unlinkSync as S}from"fs";import{tmpdir as T}from"os";import{join as b}from"path";import{t as I}from"../dal/i18n.js";import{runClipboardCommand as s}from"./clipboard-command.js";import{detectSupportedImageMimeType as h}from"./mime.js";import{loadPhoton as P}from"./photon.js";import{isWSL as _}from"./wsl.js";const m=["image/png","image/jpeg","image/webp","image/gif"],u=1e3,M=5e3;function C(e=process.env){return!!e.WAYLAND_DISPLAY||e.XDG_SESSION_TYPE==="wayland"}a(C,"isWaylandSession");function l(e){return e.split(";")[0]?.trim().toLowerCase()??e.toLowerCase()}a(l,"baseMimeType");function G(e){switch(l(e)){case"image/png":return"png";case"image/jpeg":return"jpg";case"image/webp":return"webp";case"image/gif":return"gif";default:return null}}a(G,"extensionForImageMimeType");function f(e){const n=e.map(t=>t.trim()).filter(Boolean).map(t=>({raw:t,base:l(t)}));for(const t of m){const r=n.find(o=>o.base===t);if(r)return r.raw}return n.find(t=>t.base.startsWith("image/"))?.raw??null}a(f,"selectPreferredImageMimeType");function E(e){const n=l(e);return m.some(i=>i===n)}a(E,"isSupportedImageMimeType");async function A(e){const n=await P();if(!n)return null;try{const i=n.PhotonImage.new_from_byteslice(e);try{return i.get_bytes()}finally{i.free()}}catch{return null}}a(A,"convertToPng");async function W(){const e=await s("wl-paste",["--list-types"],{timeoutMs:u});if(e===void 0)return;const n=e.toString("utf-8").split(/\r?\n/).map(r=>r.trim()).filter(Boolean),i=f(n);if(!i)return null;const t=await s("wl-paste",["--type",i,"--no-newline"]);if(t!==void 0)return t.length===0?null:{bytes:t,mimeType:l(i)}}a(W,"readClipboardImageViaWlPaste");async function N(){const e=b(T(),`pi-wsl-clip-${y()}.png`);try{const n=await s("wslpath",["-w",e],{timeoutMs:u});if(n===void 0)return null;const i=n.toString("utf-8").trim();if(!i)return null;const r=["Add-Type -AssemblyName System.Windows.Forms","Add-Type -AssemblyName System.Drawing",`$path = '${i.replaceAll("'","''")}'`,"$img = [System.Windows.Forms.Clipboard]::GetImage()","if ($img) { $img.Save($path, [System.Drawing.Imaging.ImageFormat]::Png); Write-Output 'ok' } else { Write-Output 'empty' }"].join("; "),o=await s("powershell.exe",["-NoProfile","-Command",r],{timeoutMs:M});if(o===void 0||o.toString("utf-8").trim()!=="ok")return null;const p=w(e);return p.length===0?null:{bytes:new Uint8Array(p),mimeType:"image/png"}}catch{return null}finally{try{S(e)}catch{}}}a(N,"readClipboardImageViaPowerShell");async function L(){const e=await s("xclip",["-selection","clipboard","-t","TARGETS","-o"],{timeoutMs:u});let n=[];e!==void 0&&(n=e.toString("utf-8").split(/\r?\n/).map(r=>r.trim()).filter(Boolean));const i=f(n);if(e!==void 0&&!i)return null;const t=new Set(i?[i,...m]:m);for(const r of t){const o=await s("xclip",["-selection","clipboard","-t",r,"-o"]);if(o!==void 0&&o.length>0)return{bytes:o,mimeType:l(r)}}}a(L,"readClipboardImageViaXclip");async function c(){const e=await g()?.getImage();if(e!==void 0)return e?.length?{bytes:e,mimeType:h(e)??"application/octet-stream"}:null}a(c,"readClipboardImageViaNativeClipboard");async function H(e){const n=e?.env??process.env,i=e?.platform??process.platform;if(n.TERMUX_VERSION)return null;let t;if(i==="linux"){const r=_(n);(C(n)||r)&&(t=await W()),t===void 0&&(t=await L()),!t&&r&&(t=await N()??t),t===void 0&&(t=await c())}else t=await c();if(!t)return null;if(!E(t.mimeType)){const r=await A(t.bytes);return r?{bytes:r,mimeType:"image/png"}:null}return t}a(H,"readClipboardImage");function k(e=process.env){if(!(!e.SSH_CONNECTION&&!e.SSH_TTY))return I("\u8FDC\u7A0B\u4F1A\u8BDD\u8BFB\u4E0D\u5230\u672C\u673A\u526A\u8D34\u677F\uFF1A\u628A\u56FE\u7247\u62D6\u8FDB\u7F16\u8F91\u5668\u5DE6\u4FA7\u6587\u4EF6\u680F\u4E0A\u4F20\u5230\u670D\u52A1\u5668\uFF0C\u518D\u8F93\u5165 @ \u9009\u4E2D\u5B83")}a(k,"remoteClipboardHint");export{G as extensionForImageMimeType,C as isWaylandSession,H as readClipboardImage,k as remoteClipboardHint};