@profullstack/gov-contracts 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +9 -0
- package/README.md +63 -2
- package/bin/gov-contracts.js +170 -0
- package/package.json +47 -4
- package/src/ai.js +46 -0
- package/src/app.js +266 -0
- package/src/auth.js +109 -0
- package/src/fit.js +178 -0
- package/src/http.js +86 -0
- package/src/index.js +9 -0
- package/src/mcp.js +117 -0
- package/src/pages.js +325 -0
- package/src/pipeline.js +118 -0
- package/src/propose.js +260 -0
- package/src/safety.js +48 -0
- package/src/server.js +15 -0
- package/src/service.js +27 -0
- package/src/sources/digest.js +119 -0
- package/src/sources/index.js +59 -0
- package/src/sources/lacounty.js +100 -0
- package/src/sources/sam.js +178 -0
- package/src/store.js +352 -0
- package/src/version.js +3 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Profullstack, Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,64 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @profullstack/gov-contracts
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Find government contract opportunities, read the RFP, score the fit, draft the proposal, and queue every step that needs a person. Hosted at **gov.procurement** (Moshpit name; clearnet relay `https://gov.procurement.pit.world`).
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
ingest -> read the RFP -> score the fit -> draft a proposal -> human queue
|
|
7
|
+
(6 h) notice + PDFs c0mpute AI letter, approach, price it, sign forms,
|
|
8
|
+
(OpenAI/Claude compliance, forms, register on the portal,
|
|
9
|
+
fallback) pricing structure review and SUBMIT BY HAND
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## The hard line
|
|
13
|
+
|
|
14
|
+
The system **never** submits a proposal, registers a vendor account, signs or certifies anything, sets a price, or contacts an agency. Those are legal and business commitments, so each one is an intervention card a person works and marks done (with the confirmation number, UEI, vendor number...). There is no mail transport, portal login or form posting in this package, and `test/safety.test.js` keeps it that way. Source adapters only `GET`, from a fixed list of read-only hosts, politely (robots.txt, one request at a time per host, 2 s apart, 429 hold-back).
|
|
15
|
+
|
|
16
|
+
## Sources
|
|
17
|
+
|
|
18
|
+
Where to look comes from Datamart's contracts registry (the Profullstack connector's `contracts_sources`, served at `mcp.profullstack.com/contracts`). gov-contracts reads the ones with a public feed:
|
|
19
|
+
|
|
20
|
+
| Source | Level | How |
|
|
21
|
+
|---|---|---|
|
|
22
|
+
| SAM.gov contract opportunities | federal | Public search every 6 h (7 niche queries); the official Opportunities API instead when `SAM_API_KEY` is set. Full notice, NAICS, set-aside, contacts, up to 3 public PDF attachments read per notice. |
|
|
23
|
+
| County of Los Angeles (LACoBids) | county | The county's open-solicitations CSV every 6 h. |
|
|
24
|
+
| Forwarded bid digests (email) | any | `POST /api/v1/ingest/digest` or `gov-contracts digest < mail.txt`. MyGovWatch parsed exactly; other layouts by a model. Tracking links are dropped, never opened. |
|
|
25
|
+
|
|
26
|
+
Cal eProcure and most city portals block automated reads; their bids arrive through digests, and the queue tells a person where to look.
|
|
27
|
+
|
|
28
|
+
## Fit and drafts
|
|
29
|
+
|
|
30
|
+
A free keyword pre-filter (whole words, title-led, our NAICS codes) keeps the model to the bids that could matter. The model (c0mpute first via `@profullstack/ai-providers`, Anthropic/OpenAI fallback, short c0mpute timeout) returns a 0-100 score, verdict, requirements, forms and registrations. Brand-name license/renewal/maintenance buys are capped at 45 (they need an authorized reseller). 60+ gets a draft in three small parts; 40-59 gets a "worth a bid?" card. Drafts never contain a price, and only list forms whose names appear in what was read.
|
|
31
|
+
|
|
32
|
+
## Surfaces
|
|
33
|
+
|
|
34
|
+
- **Web / PWA**: `/` (stats, best fits), `/solicitations`, `/s/:id`, `/queue` (Sign in with CoinPay; operators by CoinPay `sub` allowlist, never email), `/p/:id` proposal. Installable.
|
|
35
|
+
- **HTTP API**: `/api/v1/solicitations`, `/sources`, `/stats`; operator: `/interventions`, `/proposals/:id`, `/solicitations/:id/draft`, `/ingest/digest`, `/run/:job`. See `/docs`.
|
|
36
|
+
- **MCP**: streamable HTTP at `/mcp`: `search_solicitations`, `get_solicitation`, `list_sources`, `stats`; operator (Bearer key): `list_interventions`, `get_proposal`, `resolve_intervention`, `draft_proposal`, `ingest_digest`.
|
|
37
|
+
- **CLI + TUI**: `npx @profullstack/gov-contracts search software`, `queue`, `card`, `done`, `tui`, `mcp` (stdio bridge), `serve`.
|
|
38
|
+
|
|
39
|
+
Public reads: 60 a minute free, then a $1 USDC day pass (CoinPay / x402). Operators are not metered.
|
|
40
|
+
|
|
41
|
+
## Run your own
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
pnpm install
|
|
45
|
+
DB_PATH=./data/gov.db OPERATOR_API_KEY=... C0MPUTE_API_KEY=... node src/server.js
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
| Env | |
|
|
49
|
+
|---|---|
|
|
50
|
+
| `DB_PATH` | SQLite file (`/data/gov-contracts.db` in the image) |
|
|
51
|
+
| `OPERATOR_API_KEY` | Bearer key for operator API/MCP/CLI |
|
|
52
|
+
| `OPERATOR_SUBS` | CoinPay `sub`s allowed to work the queue (comma-separated) |
|
|
53
|
+
| `COINPAY_OAUTH_CLIENT_ID`, `COINPAY_OAUTH_CLIENT_SECRET` | Sign in with CoinPay |
|
|
54
|
+
| `C0MPUTE_API_KEY`, `C0MPUTE_MODELS`, `C0MPUTE_TIMEOUT_MS` | AI (c0mpute first) |
|
|
55
|
+
| `ANTHROPIC_API_KEY` / `OPENAI_API_KEY` | AI fallback |
|
|
56
|
+
| `SAM_API_KEY` | optional: official SAM.gov API |
|
|
57
|
+
| `COINPAY_X402_KEY`, `CRAWL_PAY_TO` | paid day pass past the free rate |
|
|
58
|
+
| `DRAFT_MIN_FIT` (60), `DECIDE_MIN_FIT` (40) | thresholds |
|
|
59
|
+
|
|
60
|
+
Deploy: `sh deploy/deploy.sh` (c0mpute Apps, state in `/data`).
|
|
61
|
+
|
|
62
|
+
## License
|
|
63
|
+
|
|
64
|
+
MIT, Profullstack, Inc.
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* gov-contracts CLI + TUI. Talks to the hosted API (GOV_CONTRACTS_API, default
|
|
4
|
+
* https://gov.procurement.pit.world). Operator commands need GOV_CONTRACTS_KEY.
|
|
5
|
+
* `serve` runs your own instance (API, MCP, PWA and the scheduled updater).
|
|
6
|
+
* Nothing here submits, registers, signs, prices or emails: `done` only
|
|
7
|
+
* records what a person did.
|
|
8
|
+
*/
|
|
9
|
+
import { createInterface } from 'node:readline/promises';
|
|
10
|
+
import { readFileSync } from 'node:fs';
|
|
11
|
+
|
|
12
|
+
const API = (process.env.GOV_CONTRACTS_API || 'https://gov.procurement.pit.world').replace(/\/$/, '');
|
|
13
|
+
const KEY = process.env.GOV_CONTRACTS_KEY || '';
|
|
14
|
+
const [, , cmd = 'help', ...args] = process.argv;
|
|
15
|
+
|
|
16
|
+
const flags = {};
|
|
17
|
+
const pos = [];
|
|
18
|
+
for (let i = 0; i < args.length; i++) {
|
|
19
|
+
if (args[i].startsWith('--')) {
|
|
20
|
+
const k = args[i].slice(2);
|
|
21
|
+
flags[k] = args[i + 1] && !args[i + 1].startsWith('--') ? args[++i] : true;
|
|
22
|
+
} else pos.push(args[i]);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function call(path, { method = 'GET', body, raw } = {}) {
|
|
26
|
+
const headers = { accept: 'application/json' };
|
|
27
|
+
if (KEY) headers.authorization = `Bearer ${KEY}`;
|
|
28
|
+
if (body !== undefined) headers['content-type'] = 'application/json';
|
|
29
|
+
const r = await fetch(`${API}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
30
|
+
if (raw) return r.text();
|
|
31
|
+
const j = await r.json().catch(() => ({}));
|
|
32
|
+
if (!r.ok) throw new Error(j?.error?.message || j?.error?.code || `HTTP ${r.status}`);
|
|
33
|
+
return j.data ?? j;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const out = (v) => (flags.json ? console.log(JSON.stringify(v, null, 2)) : null);
|
|
37
|
+
const line = (s) => `${s.fit_score != null ? String(s.fit_score).padStart(3) + ' ' : ''}${String(s.due_at || '').slice(0, 10).padEnd(10)} ${s.title.slice(0, 80)}\n${' '.repeat(s.fit_score != null ? 5 : 0)}${' '.repeat(12)}${s.agency || ''} · ${s.id}`;
|
|
38
|
+
const stdin = async () => {
|
|
39
|
+
if (process.stdin.isTTY) return '';
|
|
40
|
+
const chunks = [];
|
|
41
|
+
for await (const c of process.stdin) chunks.push(c);
|
|
42
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const HELP = `gov-contracts: government contract opportunities, read and drafted. Submitting stays human.
|
|
46
|
+
|
|
47
|
+
gov-contracts search [words] [--level federal|state|county|city] [--source sam|lacounty|digest] [--order fit|due|new] [--limit N]
|
|
48
|
+
gov-contracts show <id> one solicitation (e.g. sam:<notice id>, lacounty:50629)
|
|
49
|
+
gov-contracts sources where opportunities come from
|
|
50
|
+
gov-contracts stats
|
|
51
|
+
operator (GOV_CONTRACTS_KEY):
|
|
52
|
+
gov-contracts queue [--status open|done|dismissed|all]
|
|
53
|
+
gov-contracts card <id> one card, with the text to copy
|
|
54
|
+
gov-contracts done <id> [note] record that YOU did it (confirmation number, UEI...)
|
|
55
|
+
gov-contracts dismiss <id> [note]
|
|
56
|
+
gov-contracts proposal <id> markdown of a draft (proposal id or solicitation id)
|
|
57
|
+
gov-contracts draft <solicitation id>
|
|
58
|
+
gov-contracts digest [file] add the bids listed in a forwarded digest (or stdin)
|
|
59
|
+
gov-contracts run ingest-sam|ingest-lacounty|work
|
|
60
|
+
gov-contracts tui work the queue in the terminal
|
|
61
|
+
other:
|
|
62
|
+
gov-contracts mcp stdio MCP bridge to ${API}/mcp
|
|
63
|
+
gov-contracts serve run your own instance (PORT, DB_PATH, ...)
|
|
64
|
+
--json for machine output. GOV_CONTRACTS_API=${API}`;
|
|
65
|
+
|
|
66
|
+
async function tui() {
|
|
67
|
+
if (!KEY) throw new Error('tui needs GOV_CONTRACTS_KEY (the operator key).');
|
|
68
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
69
|
+
try {
|
|
70
|
+
for (;;) {
|
|
71
|
+
const items = await call('/api/v1/interventions?status=open');
|
|
72
|
+
console.log(`\n\x1b[1mgov.procurement queue\x1b[0m ${items.length} open (${API})\n`);
|
|
73
|
+
items.slice(0, 30).forEach((iv, i) => console.log(`${String(i + 1).padStart(2)}. [${iv.kind}] ${iv.title.slice(0, 90)}${iv.due_at ? ` due ${String(iv.due_at).slice(0, 10)}` : ''}`));
|
|
74
|
+
const a = (await rl.question('\nNumber to open, r = refresh, q = quit: ')).trim().toLowerCase();
|
|
75
|
+
if (a === 'q' || a === '') break;
|
|
76
|
+
if (a === 'r') continue;
|
|
77
|
+
const iv = items[Number(a) - 1];
|
|
78
|
+
if (!iv) continue;
|
|
79
|
+
const full = await call(`/api/v1/interventions/${iv.id}`);
|
|
80
|
+
console.log(`\n\x1b[1m${full.title}\x1b[0m\n${full.agency || ''}\n\n${full.body}\n${full.open_url ? `\nOpen: ${full.open_url}` : ''}`);
|
|
81
|
+
if (full.copy_text) console.log(`\n--- text to copy (${full.copy_text.length} chars) ---\n${full.copy_text.slice(0, 3000)}${full.copy_text.length > 3000 ? '\n[...] (gov-contracts card ' + full.id + ' for all of it)' : ''}`);
|
|
82
|
+
const act = (await rl.question('\nd = mark done, x = dismiss, enter = back: ')).trim().toLowerCase();
|
|
83
|
+
if (act === 'd' || act === 'x') {
|
|
84
|
+
const note = await rl.question('Note (confirmation number, UEI, reason): ');
|
|
85
|
+
await call(`/api/v1/interventions/${iv.id}`, { method: 'POST', body: { status: act === 'd' ? 'done' : 'dismissed', note } });
|
|
86
|
+
console.log('Recorded.');
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
} finally {
|
|
90
|
+
rl.close();
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** stdio <-> streamable HTTP: one JSON-RPC message per line. */
|
|
95
|
+
async function mcpBridge() {
|
|
96
|
+
const rl = createInterface({ input: process.stdin });
|
|
97
|
+
for await (const l of rl) {
|
|
98
|
+
if (!l.trim()) continue;
|
|
99
|
+
let msg;
|
|
100
|
+
try { msg = JSON.parse(l); } catch { continue; }
|
|
101
|
+
try {
|
|
102
|
+
const r = await fetch(`${API}/mcp`, {
|
|
103
|
+
method: 'POST',
|
|
104
|
+
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', ...(KEY ? { authorization: `Bearer ${KEY}` } : {}) },
|
|
105
|
+
body: JSON.stringify(msg),
|
|
106
|
+
});
|
|
107
|
+
const t = await r.text();
|
|
108
|
+
if (msg.id === undefined) continue;
|
|
109
|
+
const data = t.startsWith('event:') || t.startsWith('data:') ? t.split('\n').filter((x) => x.startsWith('data:')).map((x) => x.slice(5).trim()).join('') : t;
|
|
110
|
+
process.stdout.write((data || JSON.stringify({ jsonrpc: '2.0', id: msg.id, error: { code: -32000, message: `HTTP ${r.status}` } })) + '\n');
|
|
111
|
+
} catch (e) {
|
|
112
|
+
if (msg.id !== undefined) process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: msg.id, error: { code: -32000, message: String(e.message || e) } }) + '\n');
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const commands = {
|
|
118
|
+
async help() { console.log(HELP); },
|
|
119
|
+
async search() {
|
|
120
|
+
const p = new URLSearchParams();
|
|
121
|
+
if (pos.length) p.set('q', pos.join(' '));
|
|
122
|
+
for (const k of ['level', 'source', 'order', 'limit']) if (flags[k]) p.set(k, flags[k]);
|
|
123
|
+
const rows = await call(`/api/v1/solicitations?${p}`);
|
|
124
|
+
if (flags.json) return out(rows);
|
|
125
|
+
rows.forEach((s) => console.log(line(s)));
|
|
126
|
+
if (!rows.length) console.log('No open solicitations match.');
|
|
127
|
+
},
|
|
128
|
+
async show() {
|
|
129
|
+
const s = await call(`/api/v1/solicitations/${encodeURIComponent(pos[0] || '')}`);
|
|
130
|
+
if (flags.json) return out(s);
|
|
131
|
+
console.log(`${s.title}\n${s.agency || ''}\nNumber: ${s.number || 'n/a'} Due: ${s.due_at || 'n/a'} Level: ${s.level}\n${s.url || ''}\n\n${(s.description || '').slice(0, 2500)}`);
|
|
132
|
+
if (s.fit) console.log(`\nFit ${s.fit_score}/100 (${s.fit.verdict}): ${s.fit.summary}`);
|
|
133
|
+
},
|
|
134
|
+
async sources() {
|
|
135
|
+
const rows = await call('/api/v1/sources');
|
|
136
|
+
if (flags.json) return out(rows);
|
|
137
|
+
rows.forEach((r) => console.log(`${r.gov_contracts ? '●' : '○'} ${r.name} [${r.level || ''}] ${r.gov_contracts ? r.gov_contracts.ingest : 'link only'}\n ${r.official_url || ''}`));
|
|
138
|
+
},
|
|
139
|
+
async stats() { console.log(JSON.stringify(await call('/api/v1/stats'), null, 2)); },
|
|
140
|
+
async queue() {
|
|
141
|
+
const rows = await call(`/api/v1/interventions?status=${flags.status || 'open'}`);
|
|
142
|
+
if (flags.json) return out(rows);
|
|
143
|
+
rows.forEach((iv) => console.log(`${iv.id} [${iv.kind}] ${iv.title.slice(0, 90)}${iv.due_at ? ` due ${String(iv.due_at).slice(0, 10)}` : ''}`));
|
|
144
|
+
if (!rows.length) console.log('Nothing waiting.');
|
|
145
|
+
},
|
|
146
|
+
async card() {
|
|
147
|
+
const iv = await call(`/api/v1/interventions/${pos[0]}`);
|
|
148
|
+
if (flags.json) return out(iv);
|
|
149
|
+
console.log(`${iv.title}\n\n${iv.body}\n${iv.open_url ? `\nOpen: ${iv.open_url}\n` : ''}${iv.copy_text ? `\n${iv.copy_text}` : ''}`);
|
|
150
|
+
},
|
|
151
|
+
async done() { console.log(JSON.stringify(await call(`/api/v1/interventions/${pos[0]}`, { method: 'POST', body: { status: 'done', note: pos.slice(1).join(' ') } }), null, 2)); },
|
|
152
|
+
async dismiss() { console.log(JSON.stringify(await call(`/api/v1/interventions/${pos[0]}`, { method: 'POST', body: { status: 'dismissed', note: pos.slice(1).join(' ') } }), null, 2)); },
|
|
153
|
+
async proposal() { process.stdout.write(await call(`/api/v1/proposals/${encodeURIComponent(pos[0] || '')}?format=md`, { raw: true })); },
|
|
154
|
+
async draft() { console.log(JSON.stringify(await call(`/api/v1/solicitations/${encodeURIComponent(pos[0] || '')}/draft`, { method: 'POST' }), null, 2)); },
|
|
155
|
+
async digest() {
|
|
156
|
+
const text = pos[0] ? readFileSync(pos[0], 'utf8') : await stdin();
|
|
157
|
+
if (!text.trim()) throw new Error('Give a file or pipe the digest text on stdin.');
|
|
158
|
+
console.log(JSON.stringify(await call('/api/v1/ingest/digest', { method: 'POST', body: { text } }), null, 2));
|
|
159
|
+
},
|
|
160
|
+
async run() { console.log(JSON.stringify(await call(`/api/v1/run/${pos[0] || 'work'}`, { method: 'POST' }), null, 2)); },
|
|
161
|
+
tui,
|
|
162
|
+
mcp: mcpBridge,
|
|
163
|
+
async serve() { await import('../src/server.js'); },
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
const fn = commands[cmd] || commands.help;
|
|
167
|
+
fn().catch((e) => {
|
|
168
|
+
console.error(`gov-contracts: ${e.message || e}`);
|
|
169
|
+
process.exit(1);
|
|
170
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@profullstack/gov-contracts",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Find government contract opportunities (SAM.gov, LA County, forwarded bid digests), read the RFP, score the fit, draft a proposal and queue every human step. Never submits anything on its own. API, CLI, MCP, TUI and PWA.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "Profullstack, Inc.",
|
|
8
|
+
"homepage": "https://gov.procurement.pit.world",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/profullstack/gov-contracts.git"
|
|
12
|
+
},
|
|
13
|
+
"keywords": ["government contracts", "rfp", "procurement", "sam.gov", "proposals", "mcp", "bids"],
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=24"
|
|
16
|
+
},
|
|
17
|
+
"packageManager": "pnpm@10.34.6",
|
|
18
|
+
"bin": {
|
|
19
|
+
"gov-contracts": "bin/gov-contracts.js"
|
|
20
|
+
},
|
|
21
|
+
"exports": {
|
|
22
|
+
".": "./src/index.js",
|
|
23
|
+
"./sources": "./src/sources/index.js",
|
|
24
|
+
"./digest": "./src/sources/digest.js",
|
|
25
|
+
"./fit": "./src/fit.js",
|
|
26
|
+
"./safety": "./src/safety.js",
|
|
27
|
+
"./server": "./src/app.js"
|
|
28
|
+
},
|
|
29
|
+
"files": ["bin", "src", "public", "README.md", "LICENSE"],
|
|
30
|
+
"scripts": {
|
|
31
|
+
"start": "node src/server.js",
|
|
32
|
+
"dev": "node --watch src/server.js",
|
|
33
|
+
"test": "DB_PATH=:memory: GOV_OFFLINE=1 node --test test/*.test.js"
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@hono/node-server": "^2.1.11",
|
|
37
|
+
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
38
|
+
"@profullstack/ai-providers": "0.3.3",
|
|
39
|
+
"@profullstack/coinpay-onboard": "0.5.1",
|
|
40
|
+
"@profullstack/footer": "0.7.3",
|
|
41
|
+
"@profullstack/scraper-daemon": "0.4.0",
|
|
42
|
+
"@profullstack/stack": "0.6.2",
|
|
43
|
+
"@profullstack/throttle": "0.5.2",
|
|
44
|
+
"@profullstack/x402-gateway": "0.20.0",
|
|
45
|
+
"hono": "^4.13.23",
|
|
46
|
+
"unpdf": "2.2.3",
|
|
47
|
+
"zod": "^4.6.7"
|
|
48
|
+
}
|
|
49
|
+
}
|
package/src/ai.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI: c0mpute first through @profullstack/ai-providers, then OpenAI/Anthropic
|
|
3
|
+
* (alternating) when c0mpute fails or times out. House rule.
|
|
4
|
+
*
|
|
5
|
+
* A fresh router per call: the shared one parks c0mpute for 30 s after one
|
|
6
|
+
* dropped job, which would push every following call to a paid provider.
|
|
7
|
+
* The c0mpute timeout is kept short (C0MPUTE_TIMEOUT_MS, default 120 s) so a
|
|
8
|
+
* stuck job falls back instead of holding the pipeline.
|
|
9
|
+
*/
|
|
10
|
+
import { createAiProviders } from '@profullstack/ai-providers';
|
|
11
|
+
|
|
12
|
+
export const DEFAULT_MODELS = 'huihui_ai/qwen3.5-abliterated:4b,qwen3:4b';
|
|
13
|
+
|
|
14
|
+
export function aiConfigured(env = process.env) {
|
|
15
|
+
return !!(env.C0MPUTE_API_KEY || env.INFERNET_API_KEY || env.OPENAI_API_KEY || env.ANTHROPIC_API_KEY);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function makeAi(env = process.env) {
|
|
19
|
+
if (env.AI_DISABLED === '1' || !aiConfigured(env)) return null;
|
|
20
|
+
const router = createAiProviders({
|
|
21
|
+
env: { C0MPUTE_MODELS: DEFAULT_MODELS, ...env },
|
|
22
|
+
c0mpute: {
|
|
23
|
+
timeoutMs: Number(env.C0MPUTE_TIMEOUT_MS || 120_000),
|
|
24
|
+
stallMs: Number(env.C0MPUTE_STALL_MS || 60_000),
|
|
25
|
+
},
|
|
26
|
+
openai: { timeoutMs: 90_000 },
|
|
27
|
+
anthropic: { timeoutMs: 90_000 },
|
|
28
|
+
router: {
|
|
29
|
+
onAttempt: (e) => {
|
|
30
|
+
if (!e.ok) console.error(`ai ${e.feature || ''} ${e.provider} failed after ${e.ms} ms: ${e.kind || ''} ${String(e.error || '').slice(0, 160)}`);
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
});
|
|
34
|
+
return router;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Which providers are configured (never the keys). */
|
|
38
|
+
export function aiStatus(env = process.env) {
|
|
39
|
+
return {
|
|
40
|
+
c0mpute: !!(env.C0MPUTE_API_KEY || env.INFERNET_API_KEY),
|
|
41
|
+
openai: !!env.OPENAI_API_KEY,
|
|
42
|
+
anthropic: !!env.ANTHROPIC_API_KEY,
|
|
43
|
+
models: (env.C0MPUTE_MODELS || DEFAULT_MODELS).split(','),
|
|
44
|
+
c0mpute_timeout_ms: Number(env.C0MPUTE_TIMEOUT_MS || 120_000),
|
|
45
|
+
};
|
|
46
|
+
}
|
package/src/app.js
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import { Hono } from 'hono';
|
|
2
|
+
import { descriptor } from '@profullstack/footer';
|
|
3
|
+
import { throttle } from '@profullstack/throttle/hono';
|
|
4
|
+
import { createGateway } from '@profullstack/x402-gateway';
|
|
5
|
+
import { SITE, me, mountAuth, operator } from './auth.js';
|
|
6
|
+
import { aiStatus } from './ai.js';
|
|
7
|
+
import { handleMcp, TOOL_NAMES } from './mcp.js';
|
|
8
|
+
import {
|
|
9
|
+
ICON, MANIFEST, SW, docsPage, homePage, messagePage, proposalPage, queuePage, solicitationPage, solicitationsPage,
|
|
10
|
+
} from './pages.js';
|
|
11
|
+
import { getDaemon, ingestDigest, ingestSource, workTick } from './pipeline.js';
|
|
12
|
+
import { publicSolicitation, startDraft } from './service.js';
|
|
13
|
+
import { listSources } from './sources/index.js';
|
|
14
|
+
import {
|
|
15
|
+
documentsFor, getIntervention, getProposal, getSolicitation, latestProposal, listInterventions, openDb, resolveIntervention, searchSolicitations, stats,
|
|
16
|
+
} from './store.js';
|
|
17
|
+
import { HUMAN_ONLY } from './safety.js';
|
|
18
|
+
import { VERSION } from './version.js';
|
|
19
|
+
|
|
20
|
+
openDb();
|
|
21
|
+
export const app = new Hono();
|
|
22
|
+
|
|
23
|
+
/** The caller behind the pit.world relay and the c0mpute gateway: first X-Forwarded-For hop. */
|
|
24
|
+
function identify(request) {
|
|
25
|
+
const first = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim();
|
|
26
|
+
return first || 'local';
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** $1 USDC day pass (CoinPay / x402) once a caller passes the free rate. Off until the CoinPay keys are set. */
|
|
30
|
+
function paywall(env = process.env) {
|
|
31
|
+
if (!env.COINPAY_X402_KEY || !env.CRAWL_PAY_TO) return null;
|
|
32
|
+
return createGateway({
|
|
33
|
+
siteUrl: SITE.replace(/\/$/, ''),
|
|
34
|
+
coinpay: { apiKey: env.COINPAY_X402_KEY },
|
|
35
|
+
payTo: env.CRAWL_PAY_TO,
|
|
36
|
+
priceCents: Number(env.PASS_PRICE_CENTS || 100),
|
|
37
|
+
passMinutes: 1440,
|
|
38
|
+
contact: 'mailto:hello@profullstack.com',
|
|
39
|
+
appPaths: ['/health', '/docs', '/llms.txt'],
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const gateway = paywall();
|
|
44
|
+
const limiter = throttle({
|
|
45
|
+
gateway: gateway || undefined,
|
|
46
|
+
limit: Number(process.env.RATE_LIMIT_PER_MIN || 60),
|
|
47
|
+
headroom: 1,
|
|
48
|
+
identify,
|
|
49
|
+
rules: [
|
|
50
|
+
{ path: '/health', open: true },
|
|
51
|
+
{ path: '/robots.txt', open: true },
|
|
52
|
+
{ path: '/llms.txt', open: true },
|
|
53
|
+
{ path: '/hooks/', open: true },
|
|
54
|
+
{ path: '/auth/', open: true },
|
|
55
|
+
{ path: '/sw.js', open: true },
|
|
56
|
+
{ path: '/icon.svg', open: true },
|
|
57
|
+
{ path: '/manifest.webmanifest', open: true },
|
|
58
|
+
],
|
|
59
|
+
});
|
|
60
|
+
// Operators are never metered.
|
|
61
|
+
app.use('*', (c, next) => (operator(c) ? next() : limiter(c, next)));
|
|
62
|
+
|
|
63
|
+
app.use('*', async (c, next) => {
|
|
64
|
+
await next();
|
|
65
|
+
c.header('x-content-type-options', 'nosniff');
|
|
66
|
+
c.header('referrer-policy', 'strict-origin-when-cross-origin');
|
|
67
|
+
if (c.req.path.startsWith('/api/') || c.req.path === '/mcp') {
|
|
68
|
+
c.header('access-control-allow-origin', '*');
|
|
69
|
+
c.header('access-control-allow-headers', 'content-type, authorization, mcp-session-id, mcp-protocol-version');
|
|
70
|
+
c.header('access-control-allow-methods', 'GET, POST, OPTIONS');
|
|
71
|
+
c.header('access-control-expose-headers', 'mcp-session-id');
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
app.options('/api/*', (c) => c.body(null, 204));
|
|
75
|
+
app.options('/mcp', (c) => c.body(null, 204));
|
|
76
|
+
|
|
77
|
+
mountAuth(app);
|
|
78
|
+
|
|
79
|
+
const html = async (c, p, status = 200) => {
|
|
80
|
+
c.header('cache-control', 'no-store');
|
|
81
|
+
return c.html(await p, status);
|
|
82
|
+
};
|
|
83
|
+
const needOperatorPage = async (c) => {
|
|
84
|
+
if (!me(c)) return c.redirect(`/signin?next=${encodeURIComponent(c.req.path)}`, 302);
|
|
85
|
+
const m = await messagePage({ title: 'Operators only', message: 'You are signed in with CoinPay, but this queue belongs to the bidder\'s operators. Ask an operator to add your CoinPay account.', signedIn: me(c), status: 403 });
|
|
86
|
+
return c.html(m.html, 403);
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
/* ------------------------------------------------------------------- pages -- */
|
|
90
|
+
|
|
91
|
+
app.get('/', (c) => {
|
|
92
|
+
const isOp = !!operator(c);
|
|
93
|
+
const top = searchSolicitations({ order: isOp ? 'fit' : 'new', limit: 12 }).map((s) => publicSolicitation(s, isOp));
|
|
94
|
+
return html(c, homePage({ stats: stats(), top, signedIn: me(c), isOperator: isOp, error: c.req.query('signin_error') }));
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
app.get('/solicitations', (c) => {
|
|
98
|
+
const isOp = !!operator(c);
|
|
99
|
+
const { q, level, source } = c.req.query();
|
|
100
|
+
const rows = searchSolicitations({ q, level, source, order: isOp ? 'fit' : 'due', limit: 200 }).map((s) => publicSolicitation(s, isOp));
|
|
101
|
+
return html(c, solicitationsPage({ rows, q, level, source, signedIn: me(c), isOperator: isOp }));
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
app.get('/s/:id', async (c) => {
|
|
105
|
+
const s = getSolicitation(c.req.param('id'));
|
|
106
|
+
if (!s) { const m = await messagePage({ title: 'Not found', message: 'No such solicitation.', status: 404 }); return c.html(m.html, 404); }
|
|
107
|
+
const isOp = !!operator(c);
|
|
108
|
+
return html(c, solicitationPage({ s: publicSolicitation(s, isOp), docs: documentsFor(s.id, { withText: false }), proposal: isOp ? latestProposal(s.id) : null, isOperator: isOp, signedIn: me(c) }));
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
app.post('/s/:id/draft', async (c) => {
|
|
112
|
+
if (!operator(c)) return needOperatorPage(c);
|
|
113
|
+
try { startDraft(c.req.param('id')); } catch { return c.redirect('/queue', 303); }
|
|
114
|
+
return c.redirect(`/s/${encodeURIComponent(c.req.param('id'))}?drafting=1`, 303);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
app.get('/queue', (c) => {
|
|
118
|
+
const op = operator(c);
|
|
119
|
+
if (!op) return needOperatorPage(c);
|
|
120
|
+
const status = ['open', 'done', 'dismissed', 'all'].includes(c.req.query('status')) ? c.req.query('status') : 'open';
|
|
121
|
+
const all = listInterventions({ status: 'all', limit: 500 });
|
|
122
|
+
const counts = { open: 0, done: 0, dismissed: 0, all: all.length };
|
|
123
|
+
for (const i of all) counts[i.status]++;
|
|
124
|
+
return html(c, queuePage({ items: status === 'all' ? all : all.filter((i) => i.status === status), status, counts, account: op }));
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
app.post('/queue/:id', async (c) => {
|
|
128
|
+
const op = operator(c);
|
|
129
|
+
if (!op) return needOperatorPage(c);
|
|
130
|
+
const form = await c.req.parseBody();
|
|
131
|
+
const r = resolveIntervention(c.req.param('id'), { status: String(form.status || ''), note: String(form.note || ''), by: op.coinpay_sub || op.id });
|
|
132
|
+
if (!r) return c.redirect('/queue', 303);
|
|
133
|
+
return c.redirect(`/queue#iv-${r.id}`, 303);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
app.get('/p/:id', async (c) => {
|
|
137
|
+
const op = operator(c);
|
|
138
|
+
if (!op) return needOperatorPage(c);
|
|
139
|
+
const raw = c.req.param('id');
|
|
140
|
+
const md = raw.endsWith('.md');
|
|
141
|
+
const p = getProposal(md ? raw.slice(0, -3) : raw);
|
|
142
|
+
if (!p) { const m = await messagePage({ title: 'Not found', message: 'No such proposal.', status: 404 }); return c.html(m.html, 404); }
|
|
143
|
+
if (md) {
|
|
144
|
+
c.header('content-type', 'text/markdown; charset=utf-8');
|
|
145
|
+
c.header('content-disposition', `attachment; filename="proposal-${p.id}-v${p.version}.md"`);
|
|
146
|
+
return c.body(p.markdown);
|
|
147
|
+
}
|
|
148
|
+
return html(c, proposalPage({ p, s: getSolicitation(p.solicitation_id), account: op }));
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
app.get('/docs', (c) => html(c, docsPage({ signedIn: me(c) })));
|
|
152
|
+
|
|
153
|
+
/* --------------------------------------------------------------------- API -- */
|
|
154
|
+
|
|
155
|
+
const json = (c, data, status = 200) => c.json(data, status);
|
|
156
|
+
const needOp = (c) => json(c, { error: { code: 'operator_only', message: 'Send Authorization: Bearer <operator key>, or sign in as an operator.' } }, 401);
|
|
157
|
+
|
|
158
|
+
app.get('/api/v1/solicitations', (c) => {
|
|
159
|
+
const isOp = !!operator(c);
|
|
160
|
+
const { q, level, source, order, limit, offset, status, min_fit } = c.req.query();
|
|
161
|
+
const rows = searchSolicitations({ q, level, source, order: order || (isOp ? 'fit' : 'due'), limit, offset, status: isOp ? status : undefined, minFit: isOp && min_fit ? Number(min_fit) : null });
|
|
162
|
+
return json(c, { data: rows.map((s) => publicSolicitation(s, isOp)), meta: { count: rows.length, version: VERSION } });
|
|
163
|
+
});
|
|
164
|
+
app.get('/api/v1/solicitations/:id', (c) => {
|
|
165
|
+
const isOp = !!operator(c);
|
|
166
|
+
const s = getSolicitation(c.req.param('id'));
|
|
167
|
+
if (!s) return json(c, { error: { code: 'not_found' } }, 404);
|
|
168
|
+
const p = isOp ? latestProposal(s.id) : null;
|
|
169
|
+
return json(c, { data: { ...publicSolicitation(s, isOp), documents: documentsFor(s.id, { withText: false }), ...(p ? { proposal: { id: p.id, version: p.version, status: p.status } } : {}) } });
|
|
170
|
+
});
|
|
171
|
+
app.get('/api/v1/sources', async (c) => json(c, { data: await listSources() }));
|
|
172
|
+
app.get('/api/v1/stats', (c) => json(c, { data: stats() }));
|
|
173
|
+
app.get('/api/v1/rules', (c) => json(c, { data: { human_only: HUMAN_ONLY } }));
|
|
174
|
+
|
|
175
|
+
app.get('/api/v1/interventions', (c) => {
|
|
176
|
+
if (!operator(c)) return needOp(c);
|
|
177
|
+
return json(c, { data: listInterventions({ status: c.req.query('status') || 'open', kind: c.req.query('kind') }) });
|
|
178
|
+
});
|
|
179
|
+
app.get('/api/v1/interventions/:id', (c) => {
|
|
180
|
+
if (!operator(c)) return needOp(c);
|
|
181
|
+
const iv = getIntervention(c.req.param('id'));
|
|
182
|
+
return iv ? json(c, { data: iv }) : json(c, { error: { code: 'not_found' } }, 404);
|
|
183
|
+
});
|
|
184
|
+
app.post('/api/v1/interventions/:id', async (c) => {
|
|
185
|
+
const op = operator(c);
|
|
186
|
+
if (!op) return needOp(c);
|
|
187
|
+
const body = await c.req.json().catch(() => ({}));
|
|
188
|
+
try {
|
|
189
|
+
const r = resolveIntervention(c.req.param('id'), { status: body.status, note: body.note, by: op.coinpay_sub || op.id });
|
|
190
|
+
return r ? json(c, { data: r }) : json(c, { error: { code: 'not_found' } }, 404);
|
|
191
|
+
} catch (e) {
|
|
192
|
+
return json(c, { error: { code: 'bad_request', message: e.message } }, 400);
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
app.get('/api/v1/proposals/:id', (c) => {
|
|
196
|
+
if (!operator(c)) return needOp(c);
|
|
197
|
+
const p = getProposal(c.req.param('id')) || latestProposal(c.req.param('id'));
|
|
198
|
+
if (!p) return json(c, { error: { code: 'not_found' } }, 404);
|
|
199
|
+
if (c.req.query('format') === 'md') return c.body(p.markdown, 200, { 'content-type': 'text/markdown; charset=utf-8' });
|
|
200
|
+
return json(c, { data: p });
|
|
201
|
+
});
|
|
202
|
+
app.post('/api/v1/solicitations/:id/draft', (c) => {
|
|
203
|
+
if (!operator(c)) return needOp(c);
|
|
204
|
+
try { return json(c, { data: startDraft(c.req.param('id')) }, 202); } catch { return json(c, { error: { code: 'not_found' } }, 404); }
|
|
205
|
+
});
|
|
206
|
+
app.post('/api/v1/ingest/digest', async (c) => {
|
|
207
|
+
if (!operator(c)) return needOp(c);
|
|
208
|
+
const ct = c.req.header('content-type') || '';
|
|
209
|
+
const text = ct.includes('json') ? (await c.req.json().catch(() => ({}))).text : await c.req.text();
|
|
210
|
+
if (!text || String(text).length > 200_000) return json(c, { error: { code: 'bad_request', message: 'Send the digest body as {"text": "..."} or text/plain (max 200 KB).' } }, 400);
|
|
211
|
+
return json(c, { data: await ingestDigest(String(text)) });
|
|
212
|
+
});
|
|
213
|
+
app.post('/api/v1/run/:job', async (c) => {
|
|
214
|
+
if (!operator(c)) return needOp(c);
|
|
215
|
+
const job = c.req.param('job');
|
|
216
|
+
try {
|
|
217
|
+
if (job === 'work') return json(c, { data: await workTick() });
|
|
218
|
+
const m = /^ingest-(\w+)$/.exec(job);
|
|
219
|
+
if (m) return json(c, { data: await ingestSource(m[1]) });
|
|
220
|
+
return json(c, { error: { code: 'not_found', message: 'jobs: ingest-sam, ingest-lacounty, work' } }, 404);
|
|
221
|
+
} catch (e) {
|
|
222
|
+
return json(c, { error: { code: 'job_failed', message: String(e?.message || e).slice(0, 300) } }, 502);
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
app.get('/api/v1/daemon', async (c) => {
|
|
226
|
+
if (!operator(c)) return needOp(c);
|
|
227
|
+
const d = getDaemon();
|
|
228
|
+
return json(c, { data: d ? await d.status() : null, ai: aiStatus() });
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
app.all('/mcp', (c) => handleMcp(c.req.raw));
|
|
232
|
+
|
|
233
|
+
// CoinPay business webhook (payments are settled by the x402 gateway; this only acknowledges).
|
|
234
|
+
app.post('/hooks/coinpay', (c) => c.body(null, 204));
|
|
235
|
+
|
|
236
|
+
app.all('/api/*', (c) => json(c, { error: { code: 'not_found', message: 'See /docs#api' } }, 404));
|
|
237
|
+
|
|
238
|
+
/* ---------------------------------------------------------------- plumbing -- */
|
|
239
|
+
|
|
240
|
+
app.get('/health', (c) => c.json({ ok: true, version: VERSION }));
|
|
241
|
+
app.get('/manifest.webmanifest', (c) => c.body(JSON.stringify(MANIFEST), 200, { 'content-type': 'application/manifest+json' }));
|
|
242
|
+
app.get('/sw.js', (c) => c.body(SW, 200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-cache' }));
|
|
243
|
+
app.get('/icon.svg', (c) => c.body(ICON, 200, { 'content-type': 'image/svg+xml', 'cache-control': 'public, max-age=86400' }));
|
|
244
|
+
app.get('/robots.txt', (c) => c.text('User-agent: *\nAllow: /\nDisallow: /api/\nDisallow: /queue\nDisallow: /p/\n'));
|
|
245
|
+
app.get('/.well-known/openwebring.json', (c) => c.json(descriptor({ site: SITE, name: 'gov.procurement', madeBy: 'both' })));
|
|
246
|
+
app.get('/llms.txt', (c) => c.text(`# gov.procurement
|
|
247
|
+
|
|
248
|
+
> Government contract opportunities (SAM.gov, County of Los Angeles, forwarded bid digests), read and scored for fit, with proposal drafts. Every submission, registration, signature, price and agency contact is a human step; the system never does them.
|
|
249
|
+
|
|
250
|
+
- API: ${SITE}api/v1/solicitations, ${SITE}api/v1/sources, ${SITE}api/v1/stats
|
|
251
|
+
- MCP: ${SITE}mcp (tools: ${TOOL_NAMES.join(', ')})
|
|
252
|
+
- CLI: npx @profullstack/gov-contracts
|
|
253
|
+
- Docs: ${SITE}docs
|
|
254
|
+
`));
|
|
255
|
+
app.get('/install.sh', (c) => c.body(`#!/bin/sh
|
|
256
|
+
# gov-contracts CLI + TUI. Needs Node 24+.
|
|
257
|
+
set -eu
|
|
258
|
+
if ! command -v node >/dev/null 2>&1; then echo "gov-contracts needs Node.js 24 or newer: https://nodejs.org" >&2; exit 1; fi
|
|
259
|
+
npm install -g @profullstack/gov-contracts@latest
|
|
260
|
+
echo "Installed. Try: gov-contracts search software"
|
|
261
|
+
`, 200, { 'content-type': 'text/x-shellscript; charset=utf-8' }));
|
|
262
|
+
|
|
263
|
+
app.notFound(async (c) => {
|
|
264
|
+
const m = await messagePage({ title: 'Not found', message: 'Nothing here. <a href="/">Home</a>', status: 404 });
|
|
265
|
+
return c.html(m.html, 404);
|
|
266
|
+
});
|