-
Notifications
You must be signed in to change notification settings - Fork 116
Add persistent agent state and reputation-aware service selection #464
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
d789110
2943659
95add57
4192557
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| import fs from "fs"; | ||
| import path from "path"; | ||
| import { fileURLToPath } from "url"; | ||
|
|
||
| const __filename = fileURLToPath(import.meta.url); | ||
| const __dirname = path.dirname(__filename); | ||
|
|
||
| const STATE_FILE = path.join(__dirname, "agent-state.json"); | ||
|
|
||
| function readState() { | ||
| if (!fs.existsSync(STATE_FILE)) { | ||
| return {}; | ||
| } | ||
|
|
||
| try { | ||
| const raw = fs.readFileSync(STATE_FILE, "utf8"); | ||
| return JSON.parse(raw); | ||
| } catch (err) { | ||
| console.warn("Ignoring corrupt state file:", err.message); | ||
| return {}; | ||
|
Comment on lines
+15
to
+20
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win Recover from schema-invalid state as well as invalid JSON.
Proposed fix+function isRecord(value) {
+ return value !== null && typeof value === "object" && !Array.isArray(value);
+}
+
function readState() {
...
- return JSON.parse(raw);
+ const state = JSON.parse(raw);
+ if (!isRecord(state)) throw new Error("State must be an object");
+ return state;
...
}
export function getAgentState(agentAddress) {
const state = readState();
-
- if (!state[agentAddress]) {
+ const saved = state[agentAddress];
+ if (
+ !isRecord(saved) ||
+ !Array.isArray(saved.scoreHistory) ||
+ !isRecord(saved.providerHistory) ||
+ !Number.isFinite(saved.cumulativeSpend)
+ ) {
state[agentAddress] = {
- scoreHistory: [],
- providerHistory: {},
- cumulativeSpend: 0,
+ scoreHistory: Array.isArray(saved?.scoreHistory) ? saved.scoreHistory : [],
+ providerHistory: isRecord(saved?.providerHistory) ? saved.providerHistory : {},
+ cumulativeSpend: Number.isFinite(saved?.cumulativeSpend) ? saved.cumulativeSpend : 0,
};
writeState(state);
}Also applies to: 35-42 🧰 Tools🪛 ast-grep (0.45.0)[warning] 15-15: Filesystem path is not a string literal; a request-/variable-derived path can enable path traversal. Validate and normalize the path before use. (detect-non-literal-fs-filename) 🤖 Prompt for AI Agents |
||
| } | ||
| } | ||
|
|
||
| function writeState(state) { | ||
| fs.writeFileSync( | ||
| STATE_FILE, | ||
| JSON.stringify(state, null, 2), | ||
| "utf8" | ||
| ); | ||
| } | ||
|
|
||
| export function getAgentState(agentAddress) { | ||
| const state = readState(); | ||
|
|
||
| if (!state[agentAddress]) { | ||
| state[agentAddress] = { | ||
| scoreHistory: [], | ||
| providerHistory: {}, | ||
| cumulativeSpend: 0, | ||
| }; | ||
|
|
||
| writeState(state); | ||
| } | ||
|
|
||
| return state[agentAddress]; | ||
| } | ||
|
|
||
| export function saveAgentState(agentAddress, agentState) { | ||
| const state = readState(); | ||
| state[agentAddress] = agentState; | ||
| writeState(state); | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -77,36 +77,21 @@ function parsePositiveSafeInteger(value) { | |
| // Appends ttl_warning:true when the entry's estimated remaining TTL falls | ||
| // below SERVICE_TTL_WARNING_LEDGERS. Omits the field entirely when currentLedger | ||
| // is unavailable so callers can always treat absence as "no warning data". | ||
| function parseFiniteNumericValue(value) { | ||
| if (typeof value === "number") { | ||
| return Number.isFinite(value) ? value : null; | ||
| } | ||
|
|
||
| if (typeof value !== "string" || value.trim() === "") { | ||
| return null; | ||
| } | ||
|
|
||
| const parsed = Number(value); | ||
| return Number.isFinite(parsed) ? parsed : null; | ||
| } | ||
|
|
||
| function annotateTtlWarning(service, currentLedger) { | ||
| const parsedCurrentLedger = parseFiniteNumericValue(currentLedger); | ||
| const registeredAt = parseFiniteNumericValue(service?.registered_at); | ||
|
|
||
| if (parsedCurrentLedger === null || registeredAt === null) { | ||
| return { ...service }; | ||
| } | ||
|
|
||
| const expiryLedger = registeredAt + SERVICE_MAX_TTL; | ||
| const warningOnset = expiryLedger - SERVICE_TTL_WARNING_LEDGERS; | ||
| if (currentLedger == null) return service; | ||
|
|
||
| return { | ||
| ...service, | ||
| ttl_warning: parsedCurrentLedger >= warningOnset, | ||
| ttl_warning: | ||
| currentLedger >= | ||
| service.registered_at + | ||
| SERVICE_MAX_TTL - | ||
| SERVICE_TTL_WARNING_LEDGERS, | ||
| }; | ||
| } | ||
|
Comment on lines
+77
to
+91
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win Document the inclusive TTL threshold. The predicate uses 🤖 Prompt for AI Agents |
||
|
|
||
| // Appends ttl_warning:true when the entry's estimated remaining TTL falls | ||
| // below SERVICE_TTL_WARNING_LEDGERS. Omits the field entirely when currentLedger | ||
| // is unavailable so callers can always treat absence as "no warning data". | ||
| router.get("/services", async (req, res) => { | ||
| try { | ||
| const { category, q, offset: offsetStr, limit: limitStr } = req.query; | ||
|
|
@@ -190,10 +175,18 @@ router.get("/services/:id", async (req, res) => { | |
|
|
||
| const currentLedger = | ||
| ledgerResult.status === "fulfilled" ? ledgerResult.value : null; | ||
| res.json(annotateTtlWarning(service, currentLedger)); | ||
|
|
||
| const response = annotateTtlWarning(service, currentLedger); | ||
|
|
||
|
|
||
|
|
||
| res.json(response); | ||
| } catch (err) { | ||
| logger.error({ err }, "GET /api/services/:id failed"); | ||
| res.status(500).json({ error: "Failed to fetch service", code: "FETCH_ERROR" }); | ||
| logger.error({ err }, "GET /api/services/:id failed"); | ||
| res.status(500).json({ | ||
| error: "Failed to fetch service", | ||
| code: "FETCH_ERROR", | ||
| }); | ||
| } | ||
| }); | ||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Count settled endpoint-error payments in cumulative spend.
This branch says the payment has settled, but only increments failures. Retrying another provider then leaves
cumulativeSpendlower than the amount actually paid.Proposed fix
history.failures++; agentState.providerHistory[selected.id] = history; + agentState.cumulativeSpend += parseFloat(selected.price_usdc); saveAgentState(AGENT_ADDRESS, agentState);📝 Committable suggestion
🤖 Prompt for AI Agents