Compare commits

...
5 Commits
17 changed files with 934 additions and 422 deletions
+134 -134
View File
@@ -1,16 +1,16 @@
{
"name": "learnharness",
"version": "0.3.3",
"version": "0.3.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "learnharness",
"version": "0.3.3",
"version": "0.3.4",
"license": "AGPL-3.0-only",
"dependencies": {
"@earendil-works/pi-agent-core": "1.0.2",
"@earendil-works/pi-ai": "1.0.2",
"@earendil-works/pi-agent-core": "1.4.0",
"@earendil-works/pi-ai": "1.4.0",
"@mozilla/readability": "^0.6.0",
"@radix-ui/react-use-controllable-state": "^1.2.6",
"@resvg/resvg-js": "^2.6.2",
@@ -31,7 +31,7 @@
"dagre-d3-es": "7.0.14",
"electron-updater": "^6.8.9",
"embla-carousel-react": "^8.6.0",
"katex": "^0.16.47",
"katex": "0.18.2",
"linkedom": "^0.18.13",
"lucide-react": "^1.33.0",
"media-chrome": "^4.19.2",
@@ -145,16 +145,16 @@
}
},
"node_modules/@aws-sdk/core": {
"version": "3.978.1",
"resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.978.1.tgz",
"integrity": "sha512-LbY9aGsEiznDWmUc30Nwv3aIX/+dbwTx8KfS0yOC3NPYMO+O91e6jkT1azf34FwjOndq8/Q+RcVVZz5xnerwdg==",
"version": "3.978.5",
"resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.978.5.tgz",
"integrity": "sha512-ruI0AWqcrfL20XDS6SwZIJFPOBZ6N0ADa9nLzWlBhxk1aoUjbUX3JkTR9vEmk7o35XpAHi68ahZ4T6RE2U9XyA==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/types": "^3.974.6",
"@aws-sdk/types": "^3.975.0",
"@aws-sdk/xml-builder": "^3.972.41",
"@aws/lambda-invoke-store": "^0.3.0",
"@smithy/core": "^3.35.0",
"@smithy/signature-v4": "^5.7.3",
"@smithy/core": "^3.36.1",
"@smithy/signature-v4": "^5.7.4",
"@smithy/types": "^4.19.0",
"bowser": "^2.11.0",
"tslib": "^2.6.2"
@@ -164,14 +164,14 @@
}
},
"node_modules/@aws-sdk/credential-provider-env": {
"version": "3.972.72",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.72.tgz",
"integrity": "sha512-xTKO/FWJPozTIXbozVnVGoNBhaGba8TBcx+KyUjRVeOlXE+dUc7GTR1cLvu0uTdIdmemzaFbqqCshXeZA1fZew==",
"version": "3.972.76",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.76.tgz",
"integrity": "sha512-YxmL1Ar7bV9ZkJvtv+lj+MF6le76NnZnbmgySyZuxpZaCv0/1lZ3KxKy6RIj1h9ui2hWnVjZxbmTMeO0y/NrQA==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/core": "^3.978.1",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@aws-sdk/core": "^3.978.5",
"@aws-sdk/types": "^3.975.0",
"@smithy/core": "^3.36.1",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
@@ -180,14 +180,14 @@
}
},
"node_modules/@aws-sdk/credential-provider-http": {
"version": "3.972.74",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.74.tgz",
"integrity": "sha512-u91E/hT8f4d1xy0Jl7VG4nVKJ3lxbrZkoBTeSVoJdWBiSEUMwMS/9+e0H/aJVQV//Lt5wuzP+E69v4aRSsNTmw==",
"version": "3.972.78",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.78.tgz",
"integrity": "sha512-3VHknDRngoebsaqyT1iR75b5cBT2zfEtODK6yYmYltljkK1HEAQLs2FEd1IpWqAeOYdMGaG9wikngWLTufY7RA==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/core": "^3.978.1",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@aws-sdk/core": "^3.978.5",
"@aws-sdk/types": "^3.975.0",
"@smithy/core": "^3.36.1",
"@smithy/fetch-http-handler": "^5.8.0",
"@smithy/node-http-handler": "^4.12.1",
"@smithy/types": "^4.19.0",
@@ -198,21 +198,21 @@
}
},
"node_modules/@aws-sdk/credential-provider-ini": {
"version": "3.973.17",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.973.17.tgz",
"integrity": "sha512-ged4KXdBkvIC81bLvNHHuQKdKak/VXhQTR1NWYTTqW0474nlmsxy9O/vlgTIohDDWH3xpBdtVMZRyjb+DnocDA==",
"version": "3.973.21",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.973.21.tgz",
"integrity": "sha512-aLx9hbCX6mGAyv4ZZd8UagJ4RASHVJw6BFDSIyuKmLkqNL6H47EjBPK6qaJ4B5TDV6mc+vMa0SJFYyo4mkvVQg==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/core": "^3.978.1",
"@aws-sdk/credential-provider-env": "^3.972.72",
"@aws-sdk/credential-provider-http": "^3.972.74",
"@aws-sdk/credential-provider-login": "^3.972.79",
"@aws-sdk/credential-provider-process": "^3.972.72",
"@aws-sdk/credential-provider-sso": "^3.973.16",
"@aws-sdk/credential-provider-web-identity": "^3.972.78",
"@aws-sdk/nested-clients": "^3.997.46",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@aws-sdk/core": "^3.978.5",
"@aws-sdk/credential-provider-env": "^3.972.76",
"@aws-sdk/credential-provider-http": "^3.972.78",
"@aws-sdk/credential-provider-login": "^3.972.83",
"@aws-sdk/credential-provider-process": "^3.972.76",
"@aws-sdk/credential-provider-sso": "^3.973.20",
"@aws-sdk/credential-provider-web-identity": "^3.972.82",
"@aws-sdk/nested-clients": "^3.997.50",
"@aws-sdk/types": "^3.975.0",
"@smithy/core": "^3.36.1",
"@smithy/credential-provider-imds": "^4.5.2",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
@@ -222,15 +222,15 @@
}
},
"node_modules/@aws-sdk/credential-provider-login": {
"version": "3.972.79",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.79.tgz",
"integrity": "sha512-L+Z85anONJd8MaiuraO4wRxATCdEejBZ3K3eymzWI5JPXa9sOS9CkIm72PBKqXKX+Z9p9NGMX5AIMXm0LEflgw==",
"version": "3.972.83",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.83.tgz",
"integrity": "sha512-9bJU6FjRacF4FK/QHf8Dyxhur7B1grRj8C1Yh4IkpoFW2exQflPdCv0VrbemLW9ZctLNle+AE7TETs9KNvuLYg==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/core": "^3.978.1",
"@aws-sdk/nested-clients": "^3.997.46",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@aws-sdk/core": "^3.978.5",
"@aws-sdk/nested-clients": "^3.997.50",
"@aws-sdk/types": "^3.975.0",
"@smithy/core": "^3.36.1",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
@@ -239,19 +239,19 @@
}
},
"node_modules/@aws-sdk/credential-provider-node": {
"version": "3.972.84",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.84.tgz",
"integrity": "sha512-oHt854odINVwzwsh+c5x69j0ajm4DbqqqVJ+O1ECsCIZeMDAbzFpXItaqP7UZstJj/ATdTk/KFSH0LaNAgV+kA==",
"version": "3.972.88",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.88.tgz",
"integrity": "sha512-AG0KID5qhQPzrFkh5b0Cws1Amytvzo0L0Xj6hMgJXEwD6ZXAqninDhSNAWJiN5zU4YVVZnuidnqwPwYJ04IamA==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/credential-provider-env": "^3.972.72",
"@aws-sdk/credential-provider-http": "^3.972.74",
"@aws-sdk/credential-provider-ini": "^3.973.17",
"@aws-sdk/credential-provider-process": "^3.972.72",
"@aws-sdk/credential-provider-sso": "^3.973.16",
"@aws-sdk/credential-provider-web-identity": "^3.972.78",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@aws-sdk/credential-provider-env": "^3.972.76",
"@aws-sdk/credential-provider-http": "^3.972.78",
"@aws-sdk/credential-provider-ini": "^3.973.21",
"@aws-sdk/credential-provider-process": "^3.972.76",
"@aws-sdk/credential-provider-sso": "^3.973.20",
"@aws-sdk/credential-provider-web-identity": "^3.972.82",
"@aws-sdk/types": "^3.975.0",
"@smithy/core": "^3.36.1",
"@smithy/credential-provider-imds": "^4.5.2",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
@@ -261,14 +261,14 @@
}
},
"node_modules/@aws-sdk/credential-provider-process": {
"version": "3.972.72",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.72.tgz",
"integrity": "sha512-rLIp2xbMjX/k9/od7APpqq1ZgXXnV0pOL1Th3ZsL8Wu0TRtBsDTVS8iPqcfRFcHakFxPvR04OSTv2ka2qOb/2A==",
"version": "3.972.76",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.76.tgz",
"integrity": "sha512-pdhKFTXv1zPYhh92MTlp0jVbLWvUEV9v+rziuEkoskGGQ2iJskxHTO38nA8UAbT/N4IM3n8OZJ9rIY5IBO15/A==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/core": "^3.978.1",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@aws-sdk/core": "^3.978.5",
"@aws-sdk/types": "^3.975.0",
"@smithy/core": "^3.36.1",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
@@ -277,16 +277,16 @@
}
},
"node_modules/@aws-sdk/credential-provider-sso": {
"version": "3.973.16",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.973.16.tgz",
"integrity": "sha512-IGihaJfFZYacJJr/odqILCoK7W/mvrZ7cuK7ECn3sAu4vLC6u0V8bS7mCGbdugJ8Aum2tnvqmx0F2MRFp2rn9g==",
"version": "3.973.20",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.973.20.tgz",
"integrity": "sha512-DlxrAB3MnjNLx/da7b89W+3DyJQYso/q7Ns15MsST2IV2nkAYQOYTUCaffNSjgrpMP99Dm2mV2jxzcbyF94ZfA==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/core": "^3.978.1",
"@aws-sdk/nested-clients": "^3.997.46",
"@aws-sdk/token-providers": "3.1138.0",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@aws-sdk/core": "^3.978.5",
"@aws-sdk/nested-clients": "^3.997.50",
"@aws-sdk/token-providers": "3.1155.0",
"@aws-sdk/types": "^3.975.0",
"@smithy/core": "^3.36.1",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
@@ -295,15 +295,15 @@
}
},
"node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers": {
"version": "3.1138.0",
"resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1138.0.tgz",
"integrity": "sha512-GpyAr0DD63YOEmYFM6Df+gJuIgC92MMTiBK4FTKfxii5MJ9ge20epR7LyroulscYlG89J+ZB2ivFDPjvfQhzdw==",
"version": "3.1155.0",
"resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1155.0.tgz",
"integrity": "sha512-iIcQnYLhWuq9qOLQbIWFrxF3PF0svVeZvHnUS4DUnO4zUFmFHIyGyjqrntXG+e/5PUgfavV0pYfDIKHxTzN2LA==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/core": "^3.978.1",
"@aws-sdk/nested-clients": "^3.997.46",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@aws-sdk/core": "^3.978.5",
"@aws-sdk/nested-clients": "^3.997.50",
"@aws-sdk/types": "^3.975.0",
"@smithy/core": "^3.36.1",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
@@ -312,15 +312,15 @@
}
},
"node_modules/@aws-sdk/credential-provider-web-identity": {
"version": "3.972.78",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.78.tgz",
"integrity": "sha512-/y9WvNtlcPBGLR0qc1a+9J/xtYZfVczvLUOuXaVWylzttH7ewsxwHtjmiJSolNrVSDorIxHGHMU61CbonRkmwA==",
"version": "3.972.82",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.82.tgz",
"integrity": "sha512-LUo46IqPTJ4xKBsrLuoaxiv/D2GTBCcFDMD1y3jKIqPR/p7Rw14RJFZ0iRWftqZtyLPQX9JMGnSi3mBu4y/pNA==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/core": "^3.978.1",
"@aws-sdk/nested-clients": "^3.997.46",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@aws-sdk/core": "^3.978.5",
"@aws-sdk/nested-clients": "^3.997.50",
"@aws-sdk/types": "^3.975.0",
"@smithy/core": "^3.36.1",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
@@ -329,13 +329,13 @@
}
},
"node_modules/@aws-sdk/eventstream-handler-node": {
"version": "3.972.35",
"resolved": "https://registry.npmjs.org/@aws-sdk/eventstream-handler-node/-/eventstream-handler-node-3.972.35.tgz",
"integrity": "sha512-a8xilRoRaalvSPZdfrs0VY3/BPc0uYhXW56Z/k6nmZ5Vk430LHeowf9APIPq8utM3tMJSNGSSuJMlB9YrPsN+A==",
"version": "3.972.38",
"resolved": "https://registry.npmjs.org/@aws-sdk/eventstream-handler-node/-/eventstream-handler-node-3.972.38.tgz",
"integrity": "sha512-K7vPKNstDlavHFZgbmcFdJOFIyowsevjddycRziRBbtXH/D9z+i9juCnH17liwSX9T8fJiDQzlEYkRtxkR+1vA==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@aws-sdk/types": "^3.975.0",
"@smithy/core": "^3.36.1",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
@@ -344,13 +344,13 @@
}
},
"node_modules/@aws-sdk/middleware-eventstream": {
"version": "3.972.30",
"resolved": "https://registry.npmjs.org/@aws-sdk/middleware-eventstream/-/middleware-eventstream-3.972.30.tgz",
"integrity": "sha512-B6gvZlcnRBNWraKgyEjKsbhv+VjtbyHmpU7hmtTHzXpDSxHPpCJnYLpglEOOsF+SFne20DbZC5IVC1aNr2Pb4A==",
"version": "3.972.33",
"resolved": "https://registry.npmjs.org/@aws-sdk/middleware-eventstream/-/middleware-eventstream-3.972.33.tgz",
"integrity": "sha512-8QUt39D/dk5tdV7rLvIfMMI/ilQff4zth7mkMKpVOLM+M5AQ9W3nPxFVuHQANevmVWi4T5MlxqfKV4Q2drYeBA==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@aws-sdk/types": "^3.975.0",
"@smithy/core": "^3.36.1",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
@@ -359,16 +359,16 @@
}
},
"node_modules/@aws-sdk/middleware-websocket": {
"version": "3.972.54",
"resolved": "https://registry.npmjs.org/@aws-sdk/middleware-websocket/-/middleware-websocket-3.972.54.tgz",
"integrity": "sha512-bhESdru8u8KosziH8jcVta/NM/dNreeRz2+2aU86si5bfBYOiJ6IiqD+9U4URUcU5WJO3Yw+jO3GLDIHlscXMQ==",
"version": "3.972.58",
"resolved": "https://registry.npmjs.org/@aws-sdk/middleware-websocket/-/middleware-websocket-3.972.58.tgz",
"integrity": "sha512-/BvocdloKozx/zFr4benH+9J1ywB/2dYFHPWNUdo0CBCe00gTm0HPflOq8MH6cuCTbnywSrscGq0/LheN59teQ==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/core": "^3.978.1",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@aws-sdk/core": "^3.978.5",
"@aws-sdk/types": "^3.975.0",
"@smithy/core": "^3.36.1",
"@smithy/fetch-http-handler": "^5.8.0",
"@smithy/signature-v4": "^5.7.3",
"@smithy/signature-v4": "^5.7.4",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
@@ -377,15 +377,15 @@
}
},
"node_modules/@aws-sdk/nested-clients": {
"version": "3.997.46",
"resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.46.tgz",
"integrity": "sha512-oRxtBcka/JGHGs9l9p9IVajGoTP8vTPmoAzdHGy4Qcy9P5vPnDf6nhIeM/COQNY9k/OahImTRaLkHftoXvfcmQ==",
"version": "3.997.50",
"resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.50.tgz",
"integrity": "sha512-nKb8qu4QsnpZTq/6JIXc72mzuzfh7BK4sUQkpQznPec2z4W7Ob2xYkcM4i5e1yGTBnbJVeFv/0sf3jcz85hclA==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/core": "^3.978.1",
"@aws-sdk/signature-v4-multi-region": "^3.996.47",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@aws-sdk/core": "^3.978.5",
"@aws-sdk/signature-v4-multi-region": "^3.996.49",
"@aws-sdk/types": "^3.975.0",
"@smithy/core": "^3.36.1",
"@smithy/fetch-http-handler": "^5.8.0",
"@smithy/node-http-handler": "^4.12.1",
"@smithy/types": "^4.19.0",
@@ -396,13 +396,13 @@
}
},
"node_modules/@aws-sdk/signature-v4-multi-region": {
"version": "3.996.47",
"resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.47.tgz",
"integrity": "sha512-Zk08macMvQTHzQJCLJVkOlviVoqwYMrpXv4lmLN7b7sAbiMoOK7Go0NYdR5UeF+MW8LIbRmwrNy9u/5VvX1U5g==",
"version": "3.996.49",
"resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.49.tgz",
"integrity": "sha512-nvuAZNRrRRVCiARRKsYlQ0VnXiEQiq7vXPH+UA+LSo+kN3Djl9eo/V2r0udkw85PnsNshmv2Em1clld5M3j67w==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/types": "^3.974.6",
"@smithy/signature-v4": "^5.7.3",
"@aws-sdk/types": "^3.975.0",
"@smithy/signature-v4": "^5.7.4",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
@@ -428,9 +428,9 @@
}
},
"node_modules/@aws-sdk/types": {
"version": "3.974.6",
"resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.974.6.tgz",
"integrity": "sha512-v/clNZzZnDxGyvpHMOGpJKVXFAExJzUNAAjaWGdcx8QAcXLGwTaOkw33p5SHAi0YAioK32xB3hWwOekRVfmfKg==",
"version": "3.975.0",
"resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.975.0.tgz",
"integrity": "sha512-WQlhs6juByzWOzj5fwxOx0mPJaEqMcG/sDpl3Id61B3XhKE63xY+0QWcnG+sWR/sCfprmreyUo1lM7IKZmHMzw==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/types": "^4.19.0",
@@ -463,9 +463,9 @@
}
},
"node_modules/@babel/runtime": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz",
"integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",
"version": "7.29.10",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.10.tgz",
"integrity": "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
@@ -484,12 +484,12 @@
"license": "Apache-2.0"
},
"node_modules/@earendil-works/pi-agent-core": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@earendil-works/pi-agent-core/-/pi-agent-core-1.0.2.tgz",
"integrity": "sha512-VRfewY1R5mbedJzlm01PxdCmqU8QrSXjXXhV50bp6rvVuT8YYQv1inTXRY4YzssmGAYpkC2rXipJKP5BpBFXew==",
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@earendil-works/pi-agent-core/-/pi-agent-core-1.4.0.tgz",
"integrity": "sha512-PoKY84SKUwnt7S5QBZaGUqfNO1kjP3KHpHUA9QpFTj4cOjaVWMYIcBPJ6FDRCdE8Zen9OSECQUd0uUfVgtSmgA==",
"license": "MIT",
"dependencies": {
"@earendil-works/pi-ai": "^1.0.2",
"@earendil-works/pi-ai": "1.4.0",
"typebox": "1.3.27"
},
"engines": {
@@ -497,14 +497,14 @@
}
},
"node_modules/@earendil-works/pi-ai": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@earendil-works/pi-ai/-/pi-ai-1.0.2.tgz",
"integrity": "sha512-JP59xGlSAQ/HhQ6EHN5qmneBlWfDyu6FPPryAvAaSo8A38ubAsEpS9YisCM5Jbbns0srrDffLZonE0OXorHI5A==",
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@earendil-works/pi-ai/-/pi-ai-1.4.0.tgz",
"integrity": "sha512-hQM/C4+1w8rHYACzDDf+0vQMnEnpzIop1tptIERVgR3ZeT/hHSzBNG8PaWPgxWQjqSeKCyBZSyp8uTT6eKK1pQ==",
"license": "MIT",
"dependencies": {
"@anthropic-ai/sdk": "0.129.0",
"@aws-sdk/client-bedrock-runtime": "3.1127.0",
"@earendil-works/pi-telemetry": "^1.0.2",
"@earendil-works/pi-telemetry": "1.4.0",
"@google/genai": "2.21.0",
"@smithy/node-http-handler": "4.12.1",
"http-proxy-agent": "9.1.0",
@@ -558,9 +558,9 @@
}
},
"node_modules/@earendil-works/pi-telemetry": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@earendil-works/pi-telemetry/-/pi-telemetry-1.0.2.tgz",
"integrity": "sha512-Ev5h9TE8nEXHCfRKhWj0qpUFhQgVqNteS95vsM2KNGRGm533vOO2ruDPaEwImBKPMBKXy4omz3D6V2cm41gLOQ==",
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@earendil-works/pi-telemetry/-/pi-telemetry-1.4.0.tgz",
"integrity": "sha512-MLIfowwUYIY65jSjMX82paZOrX/NTvLk6D08h+3Jq42a99RzUOewzuCR0zOlPul3D6UBfddat76VT6LvsHEs1w==",
"license": "MIT",
"engines": {
"node": ">=22.19.0"
@@ -4727,9 +4727,9 @@
}
},
"node_modules/@smithy/core": {
"version": "3.35.1",
"resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.35.1.tgz",
"integrity": "sha512-i4YPS4B6ts7bjn7UwLnGjiZdprOvHvgGobFZsYK3GIY3E5hIqtj0rReU69BcTpGp+fvtraSNXeG1l+jtJvF55w==",
"version": "3.36.2",
"resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.36.2.tgz",
"integrity": "sha512-oRw0rB9QSUiCZfEs23G5F4Af+b2rQt1lItIICWu5IejFNd+uPM8SWqiKLMpQ6bX1Q7slsLbjuoE2niErFtkVPQ==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/types": "^4.19.0",
@@ -11775,9 +11775,9 @@
}
},
"node_modules/katex": {
"version": "0.16.47",
"resolved": "https://registry.npmjs.org/katex/-/katex-0.16.47.tgz",
"integrity": "sha512-Eeo8Ys1doU1z+x8AZsPpQu+p/QcZBI5PeOo7QGQdy2x2m0MU/hYagBbGOmXwr5KVbEfVuWv9LpnQWeehogurjg==",
"version": "0.18.2",
"resolved": "https://registry.npmjs.org/katex/-/katex-0.18.2.tgz",
"integrity": "sha512-3snve4y0SXTMequLim1FMiPvLGElySam0blN5xQZBqEY3lOJz1TnuaaiugnBZBqHzlSAGmFTYL7MCQkORuLKCA==",
"funding": [
"https://opencollective.com/katex",
"https://github.com/sponsors/katex"
+7 -4
View File
@@ -1,6 +1,6 @@
{
"name": "learnharness",
"version": "0.3.3",
"version": "0.3.4",
"license": "AGPL-3.0-only",
"author": {
"name": "Amos Blomqvist",
@@ -24,8 +24,8 @@
"desktop:dist": "rm -rf dist .next/standalone && next build && node scripts/build-server.mjs && node scripts/smoke-server.mjs && DEVELOPER_DIR=${DEVELOPER_DIR:-/Applications/Xcode.app/Contents/Developer} APPLE_KEYCHAIN_PROFILE=LH_NOTARY APPLE_TEAM_ID=JS6XN22HY6 electron-builder --mac --arm64"
},
"dependencies": {
"@earendil-works/pi-agent-core": "1.0.2",
"@earendil-works/pi-ai": "1.0.2",
"@earendil-works/pi-agent-core": "1.4.0",
"@earendil-works/pi-ai": "1.4.0",
"@mozilla/readability": "^0.6.0",
"@radix-ui/react-use-controllable-state": "^1.2.6",
"@resvg/resvg-js": "^2.6.2",
@@ -46,7 +46,7 @@
"dagre-d3-es": "7.0.14",
"electron-updater": "^6.8.9",
"embla-carousel-react": "^8.6.0",
"katex": "^0.16.47",
"katex": "0.18.2",
"linkedom": "^0.18.13",
"lucide-react": "^1.33.0",
"media-chrome": "^4.19.2",
@@ -70,6 +70,9 @@
"use-stick-to-bottom": "^1.1.6",
"zod": "^4.4.3"
},
"overrides": {
"katex": "$katex"
},
"devDependencies": {
"@next/eslint-plugin-next": "^16.3.3",
"@tailwindcss/postcss": "^4.3.3",
+9 -1
View File
@@ -11,6 +11,14 @@ import { builtinProviders } from "@earendil-works/pi-ai/providers/all";
import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
import { type ModelRole } from "../../config.ts";
import { DEFAULT_THINKING_ORDER } from "../core/settings.ts";
import packageMetadata from "../../package.json" with { type: "json" };
/** App identity is immutable and shared by Models and every native Agent.
* Agent's default Pi attribution otherwise overrides the Models identity. */
export const APP_IDENTITY = Object.freeze({
userAgent: Object.freeze({ custom: `learnharness/${packageMetadata.version}` }),
attribution: Object.freeze({ name: packageMetadata.name, url: packageMetadata.homepage }),
});
/**
* The one engine factory every agent's model comes from (the pi-ai swap,
@@ -47,7 +55,7 @@ let collection: ReturnType<typeof createModels> | undefined;
* keyPresent. */
export function piModels() {
if (!collection) {
collection = createModels();
collection = createModels({ identity: APP_IDENTITY });
for (const provider of builtinProviders()) collection.setProvider(provider);
}
return collection;
+5
View File
@@ -1,3 +1,4 @@
import { randomUUID } from "node:crypto";
import type { AssistantMessage, Message, ToolResultMessage, Usage, Tool } from "@earendil-works/pi-ai";
import { normalizeContext } from "@earendil-works/pi-ai";
import { Type } from "typebox";
@@ -183,6 +184,7 @@ export async function runPdfReaderAgent(
// BYOK (owner, 2026-09-22): the level rides the injected engine — no
// factory pin to consult (engine.level is the resolved/clamped value).
const reasoning = engine.level;
const sessionId = randomUUID();
const prompt = [
`PDF path: ${pdfPath}`,
`Question (what the teacher needs from this document): ${input.question || "(no question — give a structural overview)"}`,
@@ -207,6 +209,7 @@ export async function runPdfReaderAgent(
INSTRUCTIONS,
messages,
toolDeclarations,
sessionId,
reasoning,
opts.abortSignal,
opts.chatId ? providerEventObserver(opts.chatId, "job:pdfReader") : undefined,
@@ -395,6 +398,7 @@ async function streamOnce(
systemPrompt: string,
messages: Message[],
tools: Tool[],
sessionId: string,
reasoning: ThinkingLevel | undefined,
abortSignal?: AbortSignal,
onProviderStreamEvent?: ProviderEventObserver,
@@ -403,6 +407,7 @@ async function streamOnce(
// and tool declarations fold into a leading system message.
// normalizeContext is the library's only Context→TranscriptContext entry.
const stream = engine.streamFn(engine.model, normalizeContext({ systemPrompt, messages, tools }), {
sessionId,
reasoning: reasoning && reasoning !== "off" ? reasoning : undefined,
signal: abortSignal,
onProviderStreamEvent: onProviderStreamEvent as never,
+5 -1
View File
@@ -1,6 +1,7 @@
import { Agent, type AgentEvent, type AgentMessage, type AgentTool } from "@earendil-works/pi-agent-core";
import type { AssistantMessage, ToolResultMessage, Usage } from "@earendil-works/pi-ai";
import { piEngineFor, type PiEngine } from "../models.ts";
import { randomUUID } from "node:crypto";
import { APP_IDENTITY, piEngineFor, type PiEngine } from "../models.ts";
import { providerEventObserver } from "../provider-events.ts";
import type { ModelRole } from "../../../config.ts";
@@ -64,6 +65,9 @@ export async function runSubagent(tools: AgentTool<any, any>[], opts: SubagentRu
// Debug recorder (owner, 2026-10-04): raw provider events per job run.
const providerEvents = opts.chatId ? providerEventObserver(opts.chatId, `job:${opts.role}`) : undefined;
const agent = new Agent({
identity: APP_IDENTITY,
// One unsaved conversation per invocation, stable through every turn.
sessionId: randomUUID(),
initialState: {
systemPrompt: opts.systemPrompt,
model: engine.model,
+5
View File
@@ -1,3 +1,4 @@
import { randomUUID } from "node:crypto";
import type { AssistantMessage, Message, Tool, ToolResultMessage, Usage } from "@earendil-works/pi-ai";
import { normalizeContext } from "@earendil-works/pi-ai";
import { Type } from "typebox";
@@ -142,6 +143,7 @@ export async function runVisualMaker(input: VisualMakerInput, opts: VisualMakerO
// BYOK (owner, 2026-09-22): the level rides the injected engine — no
// factory pin to consult (engine.level is the resolved/clamped value).
const reasoning = engine.level;
const sessionId = randomUUID();
const prompt = [
"Brief for ONE precise figure (from the teacher, verbatim — it is everything you know):",
brief,
@@ -164,6 +166,7 @@ export async function runVisualMaker(input: VisualMakerInput, opts: VisualMakerO
INSTRUCTIONS,
messages,
toolDeclarations,
sessionId,
reasoning,
opts.abortSignal,
opts.chatId ? providerEventObserver(opts.chatId, "job:visualMaker") : undefined,
@@ -317,6 +320,7 @@ async function streamOnce(
systemPrompt: string,
messages: Message[],
tools: Tool[],
sessionId: string,
reasoning: ThinkingLevel | undefined,
abortSignal?: AbortSignal,
onProviderStreamEvent?: ProviderEventObserver,
@@ -325,6 +329,7 @@ async function streamOnce(
// and tool declarations fold into a leading system message.
// normalizeContext is the library's only Context→TranscriptContext entry.
const stream = engine.streamFn(engine.model, normalizeContext({ systemPrompt, messages, tools }), {
sessionId,
reasoning: reasoning && reasoning !== "off" ? reasoning : undefined,
signal: abortSignal,
onProviderStreamEvent: onProviderStreamEvent as never,
+6 -2
View File
@@ -4,7 +4,7 @@ import { invalidInputResult, questionResult } from "./tool-execute.ts";
import { providerEventObserver } from "./provider-events.ts";
import type { Usage } from "@earendil-works/pi-ai";
import { PATHS } from "../../config.ts";
import { piEngineFor, type PiEngine } from "./models.ts";
import { APP_IDENTITY, piEngineFor, type PiEngine } from "./models.ts";
import { effectivePromptSegments } from "./prompt-segments.ts";
import {
askUserQuestionTool,
@@ -116,7 +116,9 @@ export interface AgentBuildOptions {
* fresh per turn, honoring enabled overrides (switch on + file
* exists); absent → the cached pure-source composition. */
promptSwitches?: Record<string, boolean>;
/** Debug: when set AND LH_PROVIDER_EVENTS=1, raw provider stream events
/** Native conversation identity: the existing persisted chat id, reused
* across reconstructed prober, teacher, and practice Agents.
* Debug: when set AND LH_PROVIDER_EVENTS=1, raw provider stream events
* (pre-normalization) append to data/debug/provider-events/
* <chatId>.jsonl via providerEventObserver — the GLM-truncation /
* DeepSeek-id incident layer. Absent or env-off → no observer. */
@@ -177,6 +179,8 @@ function baseAgentOptions(kind: AgentKind, opts: AgentBuildOptions, tools: Agent
// the normal no-observer path (tests, env-off).
const providerEvents = opts.chatId ? providerEventObserver(opts.chatId, kind) : undefined;
const agent = new Agent({
identity: APP_IDENTITY,
sessionId: opts.chatId,
initialState: {
systemPrompt,
model: engine.model,
+1 -1
View File
@@ -77,7 +77,7 @@ export interface AuthProviderInfo {
*
* EXCLUDED by owner spec — providers whose auth is not a plain key this
* wave: github-copilot (OAuth), amazon-bedrock (AWS creds), google-vertex
* (ADC), azure-openai-responses (needs a base URL), the cloudflare
* (ADC), azure (needs a base URL), the cloudflare
* account-scoped pair. Anthropic keeps ANTHROPIC_API_KEY only — its
* AUTH_TOKEN/OAUTH_TOKEN alternates stay env-only. openai-codex exposes
* no env-key (naturally absent). Providers sharing one env var (moonshotai
+318 -256
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -13,7 +13,7 @@
* ALL the env vars a provider reads as API keys.
*
* Owner-spec exclusions (asserted ABSENT): github-copilot (OAuth),
* amazon-bedrock (AWS creds), google-vertex (ADC), azure-openai-responses
* amazon-bedrock (AWS creds), google-vertex (ADC), azure
* (needs base URL), the cloudflare account-scoped pair; anthropic keeps
* ANTHROPIC_API_KEY only (AUTH_TOKEN/OAUTH_TOKEN stay env-only).
*/
@@ -32,7 +32,7 @@ const EXCLUDED_PROVIDERS = new Set([
"github-copilot",
"amazon-bedrock",
"google-vertex",
"azure-openai-responses",
"azure",
"cloudflare-workers-ai",
"cloudflare-ai-gateway",
]);
+23 -6
View File
@@ -25,7 +25,7 @@ import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import * as fs from "node:fs";
import { after, describe, it } from "node:test";
import { createFauxCore, fauxAssistantMessage, fauxToolCall, type FauxResponseStep, type ToolCall } from "@earendil-works/pi-ai";
import { createFauxCore, fauxAssistantMessage, fauxToolCall, type FauxResponseStep, type ToolCall, type Usage } from "@earendil-works/pi-ai";
import type { PiEngine } from "../src/agent/models.ts";
import type { LhMessage } from "../src/core/native-messages.ts";
import { newPlanBlockMessage } from "../src/core/native-messages.ts";
@@ -873,21 +873,30 @@ describe("the extraction pipeline (extractor → auditor → merger)", () => {
const verdict: AuditVerdicts = {
links: [{ id: FINDINGS.propositions[0]!.id, linkTo: existingId }],
};
const nativeUsage: Record<"extractor" | "auditor", Usage[]> = { extractor: [], auditor: [] };
const recordUsage = (stage: "extractor" | "auditor", engine: PiEngine): PiEngine => ({
...engine,
streamFn: (model, context, options) => {
const stream = engine.streamFn(model, context, options);
void stream.result().then((message) => nativeUsage[stage].push(message.usage));
return stream;
},
});
const pipeline = createExtractionPipeline({
chatStore,
graphStore: ledgers,
// During the auditor's generate, the registry must already carry
// the extractor's fully accumulated live usage (2 steps × 10/5).
extractor: submitModel("submit_findings", FINDINGS),
auditor: submitModel("submit_review", verdict, () =>
extractor: recordUsage("extractor", submitModel("submit_findings", FINDINGS)),
auditor: recordUsage("auditor", submitModel("submit_review", verdict, () =>
usageSeen.push(extractionStatuses().find((r) => r.chatId === chatId)?.usage.extractor?.steps.at(-1)?.inputTokens),
),
)),
});
await pipeline.runExtraction(chatId);
// Live: mid-audit the extractor's usage was fully accumulated (faux
// estimates tokens from the prompt/response text — deterministic,
// positive, no cache).
// positive, with native first-conversation cache writes in 1.4).
assert.equal(usageSeen.length, 1);
assert.ok(typeof usageSeen[0] === "number" && usageSeen[0]! > 0, "the extractor's step billed input tokens");
@@ -903,8 +912,16 @@ describe("the extraction pipeline (extractor → auditor → merger)", () => {
const step = run.stages.extractor.steps[0]!;
assert.ok(step.inputTokens! > 0 && step.outputTokens! > 0, "estimated usage captured");
assert.equal(step.cacheReadTokens, 0);
assert.equal(step.cacheWriteTokens, 0);
assert.equal(nativeUsage.extractor.length, 1);
assert.ok(nativeUsage.extractor[0]!.cacheWrite > 0, "fresh native conversation writes its cached prefix");
assert.equal(step.cacheReadTokens, nativeUsage.extractor[0]!.cacheRead);
assert.equal(step.cacheWriteTokens, nativeUsage.extractor[0]!.cacheWrite);
assert.equal(step.reasoningTokens, 0);
assert.equal(nativeUsage.auditor.length, 1);
assert.equal(run.stages.auditor.steps[0]!.cacheReadTokens, 0, "auditor owns a fresh conversation too");
assert.ok(nativeUsage.auditor[0]!.cacheWrite > 0);
assert.equal(run.stages.auditor.steps[0]!.cacheReadTokens, nativeUsage.auditor[0]!.cacheRead);
assert.equal(run.stages.auditor.steps[0]!.cacheWriteTokens, nativeUsage.auditor[0]!.cacheWrite);
assert.equal(run.stages.auditor.steps.length, 1);
assert.ok(!Number.isNaN(Date.parse(run.at)));
});
+83
View File
@@ -0,0 +1,83 @@
/** GHSA-238p-pmpm-9mq7: inherited properties must not become KaTeX authority.
* Output is inspected as inert strings/LinkeDOM; no resource or script is run.
* node:test runs files in separate processes. Within this file all prototype
* mutations are synchronous, non-concurrent, and restored even on failure.
*/
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import React from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { parseHTML } from "linkedom";
import katex from "katex";
import { MessageResponse } from "../components/ai-elements/message.tsx";
(globalThis as Record<string, unknown>).React = React;
const blocked = String.raw`\href{https://katex-security.invalid/blocked}{blocked}`;
function withoutAuthority(html: string) {
const { document } = parseHTML(html);
assert.equal(document.querySelectorAll("[href], [src], a, img, script, iframe").length, 0, "inherited authority must not emit active HTML or URL attributes");
assert.ok(html.includes("blocked"), "the formula was actually processed");
}
function withPrototype(key: string, value: unknown, run: () => void) {
const previous = Object.getOwnPropertyDescriptor(Object.prototype, key);
try {
Object.defineProperty(Object.prototype, key, { value, configurable: true, writable: true });
run();
} finally {
if (previous) Object.defineProperty(Object.prototype, key, previous);
else Reflect.deleteProperty(Object.prototype, key);
}
}
function markdown() {
return renderToStaticMarkup(React.createElement(MessageResponse, { mode: "static" }, `$${blocked}$`));
}
describe("KaTeX prototype read-side security", { concurrency: false }, () => {
it("ignores Object.prototype.trust in direct and app markdown rendering", () => {
withPrototype("trust", true, () => {
withoutAuthority(katex.renderToString(blocked, { strict: false }));
withoutAuthority(markdown());
});
});
it("ignores trust inherited from a custom options prototype", () => {
const options = Object.assign(Object.create({ trust: true }), { strict: false });
withoutAuthority(katex.renderToString(blocked, options));
});
it("ignores inherited schema defaults in direct and app markdown rendering", () => {
withPrototype("default", true, () => {
withoutAuthority(katex.renderToString(blocked, { strict: false }));
withoutAuthority(markdown());
});
});
it("ignores inherited schema processors, including for own trust:false", () => {
withPrototype("processor", (value: unknown) => value === false ? true : value, () => {
withoutAuthority(katex.renderToString(blocked, { strict: false, trust: false }));
withoutAuthority(markdown());
});
});
it("keeps own trust:false and own restricted callbacks restrictive", () => {
withPrototype("trust", true, () => {
withoutAuthority(katex.renderToString(blocked, { strict: false, trust: false }));
const commands: string[] = [];
withoutAuthority(katex.renderToString(blocked, {
strict: false,
trust: (context) => { commands.push(context.command); return context.command === "\\url"; },
}));
assert.deepEqual(commands, ["\\href"]);
});
});
it("ignores inherited builtin namespace entries", () => {
withPrototype("\\securityInherited", "INHERITED", () => {
// The parser may reject it as an unknown function rather than an
// undefined command; either way the inherited macro must not expand.
assert.throws(() => katex.renderToString(String.raw`\securityInherited`), /KaTeX parse error/);
});
});
it("does not restore an inherited macro as an own definition after a group", () => {
const macros = Object.create({ "\\securityRestore": "INHERITED" });
const html = katex.renderToString(String.raw`{\def\securityRestore{L}\securityRestore}`, { macros });
assert.ok(parseHTML(html).document.querySelector(".katex-html")?.textContent?.includes("L"));
assert.equal(Object.hasOwn(macros, "\\securityRestore"), false, "group restoration must delete, not promote an inherited value");
assert.throws(() => katex.renderToString(String.raw`\securityRestore`, { macros }), /Undefined control sequence/);
});
});
+58
View File
@@ -0,0 +1,58 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { normalizeContext } from "@earendil-works/pi-ai";
import { Type } from "typebox";
import { piEngineForSpec, piModels } from "../src/agent/models.ts";
import { modelCatalog, validateChatSettings, validateModelsSettings } from "../src/server/model-catalog.ts";
import { callCost } from "../src/core/prices.ts";
const specimens = [
{ id: "recursive/flint-v1.0:free", input: ["text"] },
{ id: "xingchen-agi/xing4.0-29b-a4b:free", input: ["text"] },
{ id: "nvidia/nemotron-3.5-super-vl:free", input: ["text", "image"] },
{ id: "openrouter/free", input: ["text", "image"] },
];
describe("native 1.4 OpenRouter free catalog (offline, no live discovery)", { concurrency: false }, () => {
for (const { id, input } of specimens) {
it(`${id}: shared listing, validation, tool-capable engine, native modality, and zero cost`, async () => {
const before = process.env;
const originalFetch = globalThis.fetch;
process.env = { NODE_ENV: "test", HOME: "/nonexistent/free-catalog", OPENROUTER_API_KEY: "dummy-free-catalog" };
try {
const catalog = modelCatalog();
const listed = catalog.models.find((m) => m.provider === "openrouter" && m.id === id);
assert.ok(listed);
assert.deepEqual(listed.input, input);
assert.deepEqual(listed.cost, { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
const model = { provider: "openrouter", id };
assert.deepEqual(validateChatSettings({ model }), { ok: true });
assert.deepEqual(validateModelsSettings({ strong: { model }, cheap: { model } }), { ok: true });
assert.equal(validateModelsSettings({ vision: { model } }).ok, true, "server catalog validation stays provider/model based; vision filtering belongs to the picker");
assert.equal(catalog.models.filter((m) => m.input.includes("image")).some((m) => m.provider === "openrouter" && m.id === id), input.includes("image"));
const engine = piEngineForSpec(model);
assert.equal(engine.model, piModels().getModel("openrouter", id));
assert.equal(engine.model.api, "openai-completions");
assert.deepEqual(engine.model.input, input);
assert.equal(callCost({ inputTokens: 1_000_000, outputTokens: 500_000, cacheReadTokens: 100_000, cacheWriteTokens: 50_000 }, `openrouter:${id}`), 0);
let payload: Record<string, unknown> | undefined;
globalThis.fetch = async (input, init) => {
const request = new Request(input, init);
assert.equal(new URL(request.url).origin, "https://openrouter.ai");
assert.equal(request.headers.get("authorization"), "Bearer dummy-free-catalog");
payload = JSON.parse(await request.text());
return new Response("{}", { status: 400, headers: { "content-type": "application/json" } });
};
await engine.streamFn(engine.model, normalizeContext({ messages: [{ role: "user", content: "offline", timestamp: 1 }], tools: [{ name: "offline_tool", description: "offline", parameters: Type.Object({}) }] }), { sessionId: "chat_free_offline" }).result();
assert.equal(payload?.model, id);
assert.match(JSON.stringify(payload?.tools), /offline_tool/);
delete process.env.OPENROUTER_API_KEY;
assert.ok(!modelCatalog().models.some((m) => m.provider === "openrouter"), "even free models retain the provider key gate");
} finally { process.env = before; globalThis.fetch = originalFetch; }
});
}
it("removed/unknown native models remain unpriced and unresolvable, never aliased to a paid fallback", () => {
assert.equal(callCost({ inputTokens: 1, outputTokens: 1 }, "openrouter:removed/no-such-model"), null);
assert.throws(() => piEngineForSpec({ provider: "openrouter", id: "removed/no-such-model" }), /catalog has no model/);
});
});
+35 -12
View File
@@ -14,7 +14,7 @@ import {
type JsonObject, type TranscriptContext, type Usage,
} from "@earendil-works/pi-ai";
import { builtinProviders } from "@earendil-works/pi-ai/providers/all";
import { piEngineForSpec, type PiEngine } from "../src/agent/models.ts";
import { APP_IDENTITY, piEngineForSpec, type PiEngine } from "../src/agent/models.ts";
import { runVisualMaker } from "../src/agent/subagents/visual-maker.ts";
import { runPdfReaderAgent } from "../src/agent/subagents/pdf-reader.ts";
import type { HeadlessApi } from "../src/agent/subagents/headless.ts";
@@ -35,6 +35,10 @@ interface Transport {
origin: string; path: string; authHeader: string;
}
const TRANSPORTS: Transport[] = [
{ provider: "opencode-go", id: "claude-haiku-5-5", envVar: "OPENCODE_API_KEY", api: "anthropic-messages", origin: "https://opencode.ai", path: "/inference/go/v1/messages", authHeader: "x-api-key" },
{ provider: "opencode-go", id: "gemini-4-argon-contributor", envVar: "OPENCODE_API_KEY", api: "google-generative-ai", origin: "https://opencode.ai", path: "/inference/go/v1/models/gemini-4-argon-contributor:streamGenerateContent", authHeader: "x-goog-api-key" },
{ provider: "opencode-go", id: "glm-5.3", envVar: "OPENCODE_API_KEY", api: "openai-completions", origin: "https://opencode.ai", path: "/inference/go/v1/chat/completions", authHeader: "authorization" },
{ provider: "opencode-go", id: "gpt-6-luna", envVar: "OPENCODE_API_KEY", api: "openai-responses", origin: "https://opencode.ai", path: "/inference/go/v1/responses", authHeader: "authorization" },
{ provider: "openrouter", id: "openai/gpt-4o-mini", envVar: "OPENROUTER_API_KEY", api: "openai-completions", origin: "https://openrouter.ai", path: "/api/v1/chat/completions", authHeader: "authorization" },
{ provider: "openai", id: "gpt-4o-mini", envVar: "OPENAI_API_KEY", api: "openai-responses", origin: "https://api.openai.com", path: "/v1/responses", authHeader: "authorization" },
{ provider: "anthropic", id: "claude-haiku-4-5", envVar: "ANTHROPIC_API_KEY", api: "anthropic-messages", origin: "https://api.anthropic.com", path: "/v1/messages", authHeader: "x-api-key" },
@@ -131,7 +135,7 @@ describe("provider-neutral raw agent loops", { concurrency: false }, () => {
it(`${loop}: every actual stream request has NO credential override (recording faux engine)`, async () => {
await isolated({ OPENROUTER_API_KEY: OR_KEY, LH_PROVIDER_EVENTS: "1" }, async () => {
const faux = createFauxCore({ tokenSize: { min: 64, max: 64 } });
faux.setResponses([0, 1, 2].map((round) => {
faux.setResponses([0, 1, 2, 0, 1, 2].map((round) => {
const calls = callsFor(loop, round);
return fauxAssistantMessage(calls.length
? calls.map((c, i) => fauxToolCall(c.name, c.args, { id: `call_${round}_${i}` }))
@@ -149,7 +153,11 @@ describe("provider-neutral raw agent loops", { concurrency: false }, () => {
const run = await runLoop(loop, engine, signal);
assertSuccess(loop, run);
assert.equal(requests.length, 3);
const sessionId = requests[0]!.options.sessionId;
assert.match(String(sessionId), /^[0-9a-f-]{36}$/);
assert.notEqual(sessionId, "provider-neutral-offline");
for (const { options } of requests) {
assert.equal(options.sessionId, sessionId);
for (const key of ["apiKey", "getApiKey", "auth", "headers"]) {
assert.ok(!Object.hasOwn(options, key), `${loop} stream must not supply ${key}`);
}
@@ -159,6 +167,12 @@ describe("provider-neutral raw agent loops", { concurrency: false }, () => {
}
assert.match(JSON.stringify(requests[2]!.context), /image\/png/);
assert.match(JSON.stringify(requests[2]!.context), /toolResult/);
const second = await runLoop(loop, engine, signal);
assertSuccess(loop, second);
assert.equal(requests.length, 6);
const secondId = requests[3]!.options.sessionId;
assert.notEqual(secondId, sessionId, "a separate unsaved operation must not reuse a conversation");
for (const request of requests.slice(3)) assert.equal(request.options.sessionId, secondId);
});
});
@@ -189,6 +203,12 @@ describe("provider-neutral raw agent loops", { concurrency: false }, () => {
assertSuccess(loop, run);
assert.equal(requests.length, 3);
for (const [round, request] of requests.entries()) {
assert.equal(request.headers.get("user-agent"), APP_IDENTITY.userAgent.custom);
if (transport.provider === "opencode-go") {
assert.match(request.headers.get("x-opencode-session") ?? "", /^[0-9a-f-]{36}$/);
assert.equal(request.headers.get("x-opencode-session"), requests[0]!.headers.get("x-opencode-session"));
assert.equal(request.headers.get("x-opencode-client"), "learnharness");
}
const url = new URL(request.url);
assert.equal(url.origin, transport.origin);
assert.equal(url.pathname, transport.path);
@@ -263,29 +283,32 @@ function closedFetch(transport: Transport, loop: Loop, requests: RecordedRequest
}
function assertPayload(transport: Transport, loop: Loop, round: number, body: Record<string, unknown>) {
if (transport.provider !== "google") assert.equal(body.model, transport.id);
const tools = JSON.stringify(body.tools);
if (transport.api !== "google-generative-ai") assert.equal(body.model, transport.id);
// Native Responses models may declare tools in additional_tools input
// items rather than top-level tools; assert the SDK's complete payload.
const tools = JSON.stringify(body);
assert.match(tools, new RegExp(loop === "visual" ? "write_svg" : "pdf_extract"));
assert.match(tools, new RegExp(loop === "visual" ? "render_svg" : "pdf_render"));
if (transport.provider === "google") assert.ok(Array.isArray(body.contents));
else if (transport.provider === "openai") assert.ok(Array.isArray(body.input));
if (transport.api === "google-generative-ai") assert.ok(Array.isArray(body.contents));
else if (transport.api === "openai-responses") assert.ok(Array.isArray(body.input));
else assert.ok(Array.isArray(body.messages));
const json = JSON.stringify(body);
assert.match(json, new RegExp(loop === "visual" ? "white square" : "Read page 1"));
if (round === 2) {
assert.ok(json.includes(PNG.toString("base64")), "the actual rendered image must reach the selected provider");
assert.match(json, new RegExp(transport.provider === "google" ? "functionResponse" : transport.provider === "openai" ? "function_call_output" : transport.provider === "anthropic" ? "tool_result" : '"role":"tool"'));
const supportsImages = piEngineForSpec({ provider: transport.provider, id: transport.id }).model.input.includes("image");
assert.equal(json.includes(PNG.toString("base64")), supportsImages, "native modality filtering: only vision models receive rendered images");
assert.match(json, new RegExp(transport.api === "google-generative-ai" ? "functionResponse" : transport.api === "openai-responses" ? "function_call_output" : transport.api === "anthropic-messages" ? "tool_result" : '"role":"tool"'));
assert.match(json, new RegExp(loop === "visual" ? "Rendered" : "Page 1"));
}
}
function sseResponse(transport: Transport, calls: Call[], round: number): Response {
const events: Record<string, unknown>[] = [];
if (transport.provider === "openrouter") {
if (transport.api === "openai-completions") {
events.push({ id: `chatcmpl_offline_${round}`, object: "chat.completion.chunk", created: 1, model: transport.id,
choices: [{ index: 0, delta: calls.length ? { role: "assistant", tool_calls: calls.map((c, i) => ({ index: i, id: `call_${round}_${i}`, type: "function", function: { name: c.name, arguments: JSON.stringify(c.args) } })) } : { role: "assistant", content: FINAL }, finish_reason: null }] });
events.push({ choices: [{ index: 0, delta: {}, finish_reason: calls.length ? "tool_calls" : "stop" }], usage: { prompt_tokens: 20, completion_tokens: 10, total_tokens: 30 } });
} else if (transport.provider === "openai") {
} else if (transport.api === "openai-responses") {
const output = calls.length ? calls.map((c, i) => ({ type: "function_call", id: `fc_${round}_${i}`, call_id: `call_${round}_${i}`, name: c.name, arguments: JSON.stringify(c.args), status: "completed" }))
: [{ type: "message", id: `msg_${round}`, role: "assistant", status: "completed", content: [{ type: "output_text", text: FINAL, annotations: [] }] }];
events.push({ type: "response.created", response: { id: `resp_offline_${round}`, status: "in_progress" } });
@@ -297,7 +320,7 @@ function sseResponse(transport: Transport, calls: Call[], round: number): Respon
events.push({ type: "response.output_item.done", output_index: index, item });
}
events.push({ type: "response.completed", response: { id: `resp_offline_${round}`, status: "completed", output, usage: { input_tokens: 20, output_tokens: 10, total_tokens: 30 } } });
} else if (transport.provider === "anthropic") {
} else if (transport.api === "anthropic-messages") {
events.push({ type: "message_start", message: { id: `msg_offline_${round}`, type: "message", role: "assistant", model: transport.id, content: [], stop_reason: null, usage: { input_tokens: 20, output_tokens: 0 } } });
const blocks = calls.length ? calls.map((c, i) => ({ type: "tool_use", id: `call_${round}_${i}`, name: c.name, input: {} })) : [{ type: "text", text: "" }];
for (const [index, block] of blocks.entries()) {
@@ -310,6 +333,6 @@ function sseResponse(transport: Transport, calls: Call[], round: number): Respon
} else {
events.push({ responseId: `google_offline_${round}`, candidates: [{ index: 0, content: { role: "model", parts: calls.length ? calls.map((c, i) => ({ functionCall: { id: `call_${round}_${i}`, name: c.name, args: c.args } })) : [{ text: FINAL }] }, finishReason: "STOP" }], usageMetadata: { promptTokenCount: 20, candidatesTokenCount: 10, totalTokenCount: 30 } });
}
const data = events.map((event) => `${typeof event.type === "string" ? `event: ${event.type}\n` : ""}data: ${JSON.stringify(event)}\n\n`).join("") + (transport.provider === "openrouter" ? "data: [DONE]\n\n" : "");
const data = events.map((event) => `${typeof event.type === "string" ? `event: ${event.type}\n` : ""}data: ${JSON.stringify(event)}\n\n`).join("") + (transport.api === "openai-completions" ? "data: [DONE]\n\n" : "");
return new Response(data, { status: 200, headers: { "content-type": "text/event-stream" } });
}
+48
View File
@@ -9,6 +9,8 @@ import { parseHTML } from "linkedom";
import { validateToolArguments } from "@earendil-works/pi-ai";
import { problemInputObject } from "../src/agent/tools/practice.ts";
import { PracticeDock } from "../components/practice-dock.tsx";
import { QuestionDock } from "../components/question-dock.tsx";
import { LatexGlyph } from "../components/latex-glyph.tsx";
import { ProblemCard, ConcludeCard } from "../components/practice-cards.tsx";
import { MessageResponse } from "../components/ai-elements/message.tsx";
import {
@@ -77,6 +79,52 @@ describe("repairMathForDisplay — the existing composition, unchanged", () => {
});
});
describe("upgraded KaTeX rendering on real question and practice surfaces", () => {
for (const [name, formula, glyphs] of [
["fraction and root", String.raw`\frac{1}{\sqrt{x}}`, ["1", "x"]],
["accents", String.raw`\hat{x}+\bar{y}`, ["x", "y"]],
["sum", String.raw`\sum_{i=1}^{n}i`, ["∑", "i", "n"]],
["matrix rows", String.raw`\begin{pmatrix}1&2\\3&4\end{pmatrix}`, ["1", "2", "3", "4"]],
["aligned rows", String.raw`\begin{aligned}a&=b\\ c&=d\end{aligned}`, ["a", "b", "c", "d", "="]],
] as const) {
it(`${name}: dollar and legacy delimiters preserve glyphs and copied TeX`, () => {
for (const raw of [`$${formula}$`, `\\(${formula}\\)`, `$$\n${formula}\n$$`, `\\[\n${formula}\n\\]`]) {
for (const element of [
<MessageResponse mode="static">{raw}</MessageResponse>,
<QuestionDock toolName="ask_user_question" toolCallId="security_question" input={{ question: raw }} expanded onExpand={() => {}} onSubmit={() => {}} />,
dock({ statement: raw }),
]) {
const html = renderToStaticMarkup(element);
assertMath(html, [formula], [...glyphs]);
const { document } = parseHTML(html);
assert.ok(document.querySelector(".katex-base .katex-strut"), "matching 0.18 internal layout classes");
if (name === "fraction and root") assert.ok(document.querySelector(".mfrac .sqrt"));
if (name === "accents") assert.ok(document.querySelectorAll(".katex-accent").length >= 2);
if (name.endsWith("rows")) assert.ok(document.querySelectorAll(".mtable .mtr").length >= 2 || document.querySelectorAll(".mtable .vlist > span").length >= 2, "two real rows, not repaired-away slashes");
}
}
});
}
it("preserves escaped currency and code on both dock surfaces", () => {
const raw = "Costs \\$5 and \\$10. `" + clean + "`\n\n```text\n" + doubled + "\n```";
for (const element of [dock({ statement: raw }), <QuestionDock toolName="ask_user_question" toolCallId="security_code" input={{ question: raw }} expanded onExpand={() => {}} onSubmit={() => {}} />]) {
const html = renderToStaticMarkup(element);
assert.deepEqual(math(html).annotations, []);
assert.ok(parseHTML(html).document.firstElementChild?.textContent?.includes("$5 and $10"));
assert.ok(parseHTML(html).document.querySelector("code")?.textContent?.includes(clean));
}
});
it("renders direct LatexGlyph connectors through the upgraded root", () => {
for (const [command, glyph] of [[String.raw`\Rightarrow`, "⇒"], [String.raw`\land`, "∧"], [String.raw`\neg`, "¬"]]) {
const html = renderToStaticMarkup(<LatexGlyph cmd={command!} />);
const { document } = parseHTML(html);
assert.equal(document.querySelectorAll(".katex-error").length, 0);
assert.ok(document.querySelector(".katex-base .katex-strut"));
assert.ok(document.querySelector(".katex-html")?.textContent?.includes(glyph!));
}
});
});
describe("practice display surfaces", () => {
for (const [name, raw, expected, glyphs] of [
["two command slashes", doubled, tex, ["∇", "∈", "×"]],
+192
View File
@@ -0,0 +1,192 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { Type } from "typebox";
import { createFauxCore, fauxAssistantMessage, fauxText, fauxToolCall, normalizeContext, type Model, type SimpleStreamOptions } from "@earendil-works/pi-ai";
import { streamSimple as streamCodex } from "@earendil-works/pi-ai/api/openai-codex-responses";
import { APP_IDENTITY, piEngineForSpec, type PiEngine } from "../src/agent/models.ts";
import { createProberAgent, createTeacherAgent, createPracticeAgent, type AgentBuildOptions } from "../src/agent/teacher-agent.ts";
import { runSubagent } from "../src/agent/subagents/pi-run.ts";
import { healToolRecord } from "../src/agent/tools/heal.ts";
import metadata from "../package.json" with { type: "json" };
const factories = [
(opts: AgentBuildOptions) => createProberAgent({ chatId: opts.chatId, searchAvailable: () => false } as never, opts),
(opts: AgentBuildOptions) => createTeacherAgent(undefined, opts),
(opts: AgentBuildOptions) => createPracticeAgent({} as never, opts),
];
function recordingEngine() {
const faux = createFauxCore({});
faux.setResponses([fauxAssistantMessage([fauxToolCall("again", {}, { id: "call_0" })], { stopReason: "toolUse" }), { ...fauxAssistantMessage([fauxText("done")]), durationMs: 42 }]);
const requests: SimpleStreamOptions[] = [];
const engine: PiEngine = { model: faux.getModel(), streamFn: (model, context, options) => {
requests.push(options ?? {});
return faux.streamSimple(model, context, options);
} };
return { engine, requests };
}
const again = { name: "again", label: "again", description: "Continue", parameters: Type.Object({}), execute: async () => ({ content: [{ type: "text" as const, text: "ok" }], details: {} }) };
// Whole-process replacement isolates native auth/profile discovery; fetch never
// delegates. No real credentials, .env, OAuth accounts, or model inference.
async function closed<T>(run: () => Promise<T>): Promise<T> {
const env = process.env;
const fetch = globalThis.fetch;
process.env = { NODE_ENV: "test", HOME: "/nonexistent/session-identity", OPENROUTER_API_KEY: "dummy-router", OPENCODE_API_KEY: "dummy-go", OPENAI_API_KEY: "dummy-openai" };
globalThis.fetch = async () => { throw new Error("CLOSED: unexpected fetch"); };
try { return await run(); } finally { process.env = env; globalThis.fetch = fetch; }
}
describe("native app and conversation identity", { concurrency: false }, () => {
it("shares one deeply frozen metadata-derived identity, without mutable conversation state", () => {
assert.deepEqual(APP_IDENTITY, { userAgent: { custom: `learnharness/${metadata.version}` }, attribution: { name: metadata.name, url: metadata.homepage } });
for (const value of [APP_IDENTITY, APP_IDENTITY.userAgent, APP_IDENTITY.attribution]) assert.ok(Object.isFrozen(value));
assert.ok(!Object.hasOwn(APP_IDENTITY, "sessionId"));
});
it("reconstructed prober/teacher/practice Agents reuse the exact chat id across tool rounds", async () => {
for (const chatId of ["chat_exact_native_123", "chat_independent_456"]) {
for (const factory of factories) {
const { engine, requests } = recordingEngine();
const agent = factory({ engine, chatId, tools: { again } });
assert.equal(agent.identity, APP_IDENTITY);
assert.equal(agent.sessionId, chatId);
await agent.prompt("offline");
assert.equal(requests.length, 2);
for (const options of requests) {
assert.equal(options.sessionId, chatId);
assert.deepEqual(options.identity, APP_IDENTITY);
assert.ok(options.signal instanceof AbortSignal);
assert.equal(options.apiKey, undefined);
}
}
}
});
it("separate extractor/auditor/compaction invocations own distinct stable unsaved conversations", async () => {
const ids = new Set<unknown>();
// Compaction uses the shared runner with the researcher role.
for (const role of ["extractor", "auditor", "researcher"] as const) {
const { engine, requests } = recordingEngine();
let usage = 0;
const result = await runSubagent([again], { role, engine, chatId: "chat_shared_debug_only", systemPrompt: "offline", prompt: "offline", maxTurns: 3, onUsage: () => usage++ });
assert.equal(requests.length, 2);
assert.equal(usage, 2);
const id = requests[0]!.sessionId;
assert.match(id ?? "", /^[0-9a-f-]{36}$/);
assert.notEqual(id, "chat_shared_debug_only");
assert.ok(!ids.has(id));
ids.add(id);
for (const options of requests) { assert.equal(options.sessionId, id); assert.deepEqual(options.identity, APP_IDENTITY); }
assert.ok(result.newMessages.some((m) => m.role === "toolResult" && typeof m.durationMs === "number"), "new native tool duration fields are preserved");
assert.ok(result.newMessages.some((m) => m.role === "assistant" && typeof m.durationMs === "number"), "new native assistant duration fields are preserved");
}
});
for (const [provider, id, endpoint] of [
["opencode-go", "claude-haiku-5-5", "/inference/go/v1/messages"],
["opencode-go", "gemini-4-argon-contributor", "/inference/go/v1/models/gemini-4-argon-contributor:streamGenerateContent"],
["opencode-go", "glm-5.3", "/inference/go/v1/chat/completions"],
["opencode-go", "gpt-6-luna", "/inference/go/v1/responses"],
["openrouter", "openrouter/free", "/api/v1/chat/completions"],
] as const) {
it(`complete native ${provider}/${id} foreground serialization carries app identity and exact sessions`, async () => closed(async () => {
const engine = piEngineForSpec({ provider, id, thinkingLevel: "off" });
const requests: Request[] = [];
globalThis.fetch = async (input, init) => { const request = new Request(input, init); requests.push(request); await request.text(); return new Response('{"error":{"message":"closed fixture"}}', { status: 400, headers: { "content-type": "application/json" } }); };
for (const factory of factories) await factory({ engine, chatId: "chat_wire_exact", tools: {} }).prompt("offline");
assert.equal(requests.length, 3);
for (const request of requests) {
assert.equal(new URL(request.url).pathname, endpoint);
assert.equal(request.headers.get("user-agent"), `learnharness/${metadata.version}`);
if (provider === "opencode-go") {
assert.equal(new URL(request.url).origin, "https://opencode.ai");
assert.equal(request.headers.get("x-opencode-client"), metadata.name);
assert.equal(request.headers.get("x-opencode-session"), "chat_wire_exact");
assert.ok(!JSON.stringify(Object.fromEntries(request.headers)).includes("dummy-router"));
} else {
assert.equal(new URL(request.url).origin, "https://openrouter.ai");
assert.equal(request.headers.get("x-openrouter-title"), metadata.name);
assert.equal(request.headers.get("http-referer"), metadata.homepage);
assert.equal(request.headers.get("x-session-id"), "chat_wire_exact");
}
}
}));
}
it("native OpenAI cache keys clamp to 64 characters while affinity retains exact session", async () => closed(async () => {
const engine = piEngineForSpec({ provider: "openai", id: "gpt-4o-mini", thinkingLevel: "off" });
const sessionId = "chat_" + "a".repeat(70);
let body: Record<string, unknown> = {};
let headers = new Headers();
globalThis.fetch = async (input, init) => { const request = new Request(input, init); headers = request.headers; body = JSON.parse(await request.text()); return new Response("{}", { status: 400, headers: { "content-type": "application/json" } }); };
await createTeacherAgent(undefined, { engine, chatId: sessionId, tools: {} }).prompt("offline");
assert.equal(body.prompt_cache_key, Array.from(sessionId).slice(0, 64).join(""));
assert.equal(headers.get("session_id"), sessionId);
}));
it("native OpenAI cache-key clamp counts Unicode code points, not UTF-16 units", async () => closed(async () => {
const engine = piEngineForSpec({ provider: "openai", id: "gpt-4o-mini", thinkingLevel: "off" });
const sessionId = "chat_" + "😀".repeat(70);
let payload: unknown;
// HTTP affinity headers cannot encode emoji. Observe native payload
// serialization before transport, then stop deliberately (no accounts).
await engine.streamFn(engine.model, normalizeContext({ messages: [{ role: "user", content: "offline", timestamp: 1 }] }), {
sessionId,
onPayload: (value) => { payload = value; throw new Error("CLOSED: payload captured"); },
}).result();
assert.equal((payload as { prompt_cache_key: string }).prompt_cache_key, Array.from(sessionId).slice(0, 64).join(""));
}));
it("native Codex serialization shares the 64-code-point clamp without an account or OAuth flow", async () => closed(async () => {
const engine = piEngineForSpec({ provider: "openai-codex", id: "gpt-6-luna", thinkingLevel: "off" });
// Synthetic, unsigned fixture token solely satisfies native local claim
// decoding. Stop at payload capture: no account, OAuth, or fetch.
const claims = { "https://api.openai.com/auth": { chatgpt_account_id: "offline-fixture" } };
const apiKey = `dummy.${Buffer.from(JSON.stringify(claims)).toString("base64url")}.dummy`;
for (const sessionId of ["chat_" + "a".repeat(70), "chat_" + "😀".repeat(70)]) {
let payload: unknown;
// The app intentionally has no Codex auth row: exercise the native
// serializer directly rather than adding an OAuth configuration path.
assert.equal(engine.model.api, "openai-codex-responses");
const result = await streamCodex(engine.model as Model<"openai-codex-responses">, normalizeContext({ messages: [{ role: "user", content: "offline", timestamp: 1 }] }), {
apiKey, sessionId, identity: APP_IDENTITY,
onPayload: (value) => { payload = value; throw new Error("CLOSED: payload captured"); },
}).result();
assert.ok(payload, result.errorMessage);
assert.equal((payload as { prompt_cache_key: string }).prompt_cache_key, Array.from(sessionId).slice(0, 64).join(""));
}
}));
it("SDK native header precedence and cache-off behavior remain untouched", async () => closed(async () => {
const engine = piEngineForSpec({ provider: "opencode-go", id: "gpt-6-luna", thinkingLevel: "off" });
let headers = new Headers();
let body: Record<string, unknown> = {};
globalThis.fetch = async (input, init) => { const request = new Request(input, init); headers = request.headers; body = JSON.parse(await request.text()); return new Response("{}", { status: 400, headers: { "content-type": "application/json" } }); };
await engine.streamFn(engine.model, normalizeContext({ messages: [{ role: "user", content: "offline", timestamp: 1 }] }), { sessionId: "chat_cache_off", cacheRetention: "none", headers: { "user-agent": "explicit-sdk-override", "x-opencode-client": null } }).result();
assert.equal(headers.get("user-agent"), "explicit-sdk-override");
assert.equal(headers.get("x-opencode-client"), null);
// Native OpenCode routing identity remains even with cache retention off.
assert.equal(headers.get("x-opencode-session"), "chat_cache_off");
assert.equal(body.prompt_cache_key, undefined);
}));
it("completed malformed native JSON stays rejected despite app prepareArguments healing", async () => closed(async () => {
const engine = piEngineForSpec({ provider: "openrouter", id: "openai/gpt-4o-mini", thinkingLevel: "off" });
const malformed = '{"value":';
globalThis.fetch = async () => new Response(`data: ${JSON.stringify({ id: "offline", choices: [{ index: 0, delta: { tool_calls: [{ index: 0, id: "call_bad", type: "function", function: { name: "check", arguments: malformed } }] }, finish_reason: null }] })}\n\ndata: ${JSON.stringify({ choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] })}\n\ndata: [DONE]\n\n`, { headers: { "content-type": "text/event-stream" } });
let executed = 0;
let prepared = 0;
const tools = healToolRecord({ check: { name: "check", label: "check", description: "check", parameters: Type.Object({ value: Type.Optional(Type.String()) }), execute: async () => { executed++; return { content: [], details: {} }; } } });
const heal = tools.check!.prepareArguments!;
tools.check!.prepareArguments = (args) => { prepared++; return heal(args); };
const result = await runSubagent(Object.values(tools), { role: "extractor", engine, systemPrompt: "offline", prompt: "offline", maxTurns: 1 });
const assistant = result.newMessages.find((m) => m.role === "assistant");
assert.ok(assistant?.role === "assistant");
const call = assistant.content.find((c) => c.type === "toolCall");
assert.ok(call?.type === "toolCall" && call.argumentsError);
assert.equal(executed, 0);
assert.equal(prepared, 1, "SDK prepares arguments but preserves argumentsError for native validation");
assert.ok(result.newMessages.some((m) => m.role === "toolResult" && m.isError));
}));
});
+3 -3
View File
@@ -51,11 +51,11 @@ test("callCost: glm-5.3-flash math — fresh input, cached read, output", () =>
test("callCost: cache writes bill at the cacheWrite rate", () => {
const cost = callCost(
call({ inputTokens: 1_000_000, outputTokens: 0, cacheWriteTokens: 500_000 }),
"openrouter:qwen/qwen3.8-max-0902",
"anthropic:claude-haiku-4-5",
);
assert.ok(cost !== null);
// fresh 1M @ $2/M + cache write 500k @ $2.5/M
assert.ok(Math.abs(cost! - (2 + 1.25)) < 1e-9);
// Native 1.4 catalog: fresh 1M @ $1/M + cache write 500k @ $1.25/M.
assert.ok(Math.abs(cost! - (1 + 0.625)) < 1e-9);
});
test("callCost: unknown model and absent fields are null, never zero", () => {