@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/src/auth.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sign in with CoinPay (OAuth 2.1, PKCE). Login = signup. Accounts bind to the
|
|
3
|
+
* CoinPay `sub` only, never the email (CoinPay never verifies it). Who may work
|
|
4
|
+
* the intervention queue is an allowlist of CoinPay subs (OPERATOR_SUBS), and
|
|
5
|
+
* scripts/CLI/MCP use the operator API key (OPERATOR_API_KEY) as a Bearer.
|
|
6
|
+
*/
|
|
7
|
+
import { createHash, timingSafeEqual } from 'node:crypto';
|
|
8
|
+
import { deleteCookie, getCookie, setCookie } from 'hono/cookie';
|
|
9
|
+
import {
|
|
10
|
+
exchangeCoinPayCode, fetchCoinPayUserinfo, generateCoinPayPkcePair, generateCoinPayState, getCoinPayAuthorizeUrl, validateCoinPayState,
|
|
11
|
+
} from '@profullstack/stack/coinpay';
|
|
12
|
+
import { accountBySession, accountBySub, createAccount, createSession, deleteSession } from './store.js';
|
|
13
|
+
|
|
14
|
+
export const SITE = (process.env.SITE_URL || 'https://gov.procurement.pit.world').replace(/\/$/, '') + '/';
|
|
15
|
+
const COOKIE = 'gc_session';
|
|
16
|
+
const STATE_COOKIE = 'gc_oauth';
|
|
17
|
+
|
|
18
|
+
const oauthReady = () => !!(process.env.COINPAY_OAUTH_CLIENT_ID && process.env.COINPAY_OAUTH_CLIENT_SECRET);
|
|
19
|
+
const issuer = () => (process.env.COINPAY_OAUTH_ISSUER || 'https://coinpayportal.com').replace(/\/$/, '');
|
|
20
|
+
const redirectUri = () => `${SITE}auth/coinpay/callback`;
|
|
21
|
+
const operatorSubs = () => new Set(String(process.env.OPERATOR_SUBS || '').split(',').map((s) => s.trim()).filter(Boolean));
|
|
22
|
+
/** Same-site paths only, so `next` can never send someone off-site. */
|
|
23
|
+
export const safeNext = (n) => (typeof n === 'string' && /^\/(?!\/)[^\s\\]*$/.test(n) ? n : '/queue');
|
|
24
|
+
const withParam = (path, k, v) => `${path}${path.includes('?') ? '&' : '?'}${k}=${encodeURIComponent(v)}`;
|
|
25
|
+
|
|
26
|
+
const sameKey = (a, b) => {
|
|
27
|
+
const x = createHash('sha256').update(String(a)).digest();
|
|
28
|
+
const y = createHash('sha256').update(String(b)).digest();
|
|
29
|
+
return timingSafeEqual(x, y);
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** The signed-in person (session cookie), or null. */
|
|
33
|
+
export function me(c) {
|
|
34
|
+
return accountBySession(getCookie(c, COOKIE));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Operator = the API key as Bearer, or a signed-in CoinPay sub on the allowlist. */
|
|
38
|
+
export function operator(c) {
|
|
39
|
+
const key = process.env.OPERATOR_API_KEY;
|
|
40
|
+
const m = /^Bearer\s+(\S+)$/i.exec(c.req.header('authorization') || '');
|
|
41
|
+
if (key && m && sameKey(m[1], key)) return { id: 'api-key', name: 'operator key', via: 'key' };
|
|
42
|
+
const a = me(c);
|
|
43
|
+
if (a && operatorSubs().has(a.coinpay_sub)) return { ...a, via: 'coinpay' };
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function bearerIsOperator(authHeader) {
|
|
48
|
+
const key = process.env.OPERATOR_API_KEY;
|
|
49
|
+
const m = /^Bearer\s+(\S+)$/i.exec(authHeader || '');
|
|
50
|
+
return !!(key && m && sameKey(m[1], key));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function mountAuth(app, { fetch: fetchImpl } = {}) {
|
|
54
|
+
app.get('/signin', (c) => c.redirect(`/auth/coinpay?next=${encodeURIComponent(safeNext(c.req.query('next')))}`, 302));
|
|
55
|
+
|
|
56
|
+
app.get('/auth/coinpay', (c) => {
|
|
57
|
+
const next = safeNext(c.req.query('next'));
|
|
58
|
+
if (!oauthReady()) return c.redirect(withParam('/', 'signin_error', 'Sign-in with CoinPay is not set up yet.'), 302);
|
|
59
|
+
const state = generateCoinPayState();
|
|
60
|
+
const { codeVerifier, codeChallenge } = generateCoinPayPkcePair();
|
|
61
|
+
setCookie(c, STATE_COOKIE, Buffer.from(JSON.stringify({ state, codeVerifier, next })).toString('base64url'), {
|
|
62
|
+
path: '/auth/coinpay', httpOnly: true, secure: SITE.startsWith('https:'), sameSite: 'Lax', maxAge: 600,
|
|
63
|
+
});
|
|
64
|
+
c.header('cache-control', 'no-store');
|
|
65
|
+
return c.redirect(getCoinPayAuthorizeUrl({
|
|
66
|
+
clientId: process.env.COINPAY_OAUTH_CLIENT_ID, redirectUri: redirectUri(), state, codeChallenge, issuer: issuer(), scopes: ['openid', 'profile'],
|
|
67
|
+
}), 302);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
app.get('/auth/coinpay/callback', async (c) => {
|
|
71
|
+
let saved = {};
|
|
72
|
+
try { saved = JSON.parse(Buffer.from(getCookie(c, STATE_COOKIE) || '', 'base64url').toString()); } catch { saved = {}; }
|
|
73
|
+
deleteCookie(c, STATE_COOKIE, { path: '/auth/coinpay' });
|
|
74
|
+
c.header('cache-control', 'no-store');
|
|
75
|
+
const next = safeNext(saved.next);
|
|
76
|
+
const fail = (msg) => c.redirect(withParam('/', 'signin_error', msg), 302);
|
|
77
|
+
if (!oauthReady()) return fail('Sign-in with CoinPay is not set up yet.');
|
|
78
|
+
if (c.req.query('error')) return fail('CoinPay sign-in was cancelled.');
|
|
79
|
+
const code = c.req.query('code');
|
|
80
|
+
if (!code || !validateCoinPayState(c.req.query('state'), saved.state)) return fail('That sign-in link expired. Please try again.');
|
|
81
|
+
let claims;
|
|
82
|
+
try {
|
|
83
|
+
const tokens = await exchangeCoinPayCode({
|
|
84
|
+
code, redirectUri: redirectUri(), clientId: process.env.COINPAY_OAUTH_CLIENT_ID, clientSecret: process.env.COINPAY_OAUTH_CLIENT_SECRET,
|
|
85
|
+
codeVerifier: saved.codeVerifier, issuer: issuer(), ...(fetchImpl ? { fetch: fetchImpl } : {}),
|
|
86
|
+
});
|
|
87
|
+
claims = await fetchCoinPayUserinfo({ accessToken: tokens.access_token, issuer: issuer(), ...(fetchImpl ? { fetch: fetchImpl } : {}) });
|
|
88
|
+
} catch (e) {
|
|
89
|
+
console.error('coinpay sign-in failed', String(e?.message || e).slice(0, 200));
|
|
90
|
+
return fail('CoinPay sign-in did not finish. Please try again.');
|
|
91
|
+
}
|
|
92
|
+
const sub = String(claims?.sub || '');
|
|
93
|
+
if (!sub) return fail('CoinPay did not say who you are. Please try again.');
|
|
94
|
+
// Bind by sub only; the email is never looked at.
|
|
95
|
+
const account = accountBySub(sub) || createAccount(sub, String(claims.name || '').replace(/[\u0000-\u001f]/g, '').trim().slice(0, 60) || 'CoinPay user');
|
|
96
|
+
deleteSession(getCookie(c, COOKIE));
|
|
97
|
+
setCookie(c, COOKIE, createSession(account.id), { path: '/', httpOnly: true, secure: SITE.startsWith('https:'), sameSite: 'Lax', maxAge: 90 * 86400 });
|
|
98
|
+
return c.redirect(next, 302);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
const signout = (c) => {
|
|
102
|
+
deleteSession(getCookie(c, COOKIE));
|
|
103
|
+
deleteCookie(c, COOKIE, { path: '/' });
|
|
104
|
+
c.header('cache-control', 'no-store');
|
|
105
|
+
return c.req.method === 'GET' ? c.redirect('/', 302) : c.json({ ok: true });
|
|
106
|
+
};
|
|
107
|
+
app.get('/signout', signout);
|
|
108
|
+
app.post('/signout', signout);
|
|
109
|
+
}
|
package/src/fit.js
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fit: how well a solicitation matches what the bidder actually does.
|
|
3
|
+
*
|
|
4
|
+
* Two passes. `prefilter` is a free keyword pass over the title and summary so
|
|
5
|
+
* a county's 200 gift-card and janitorial bids never reach a model. Anything
|
|
6
|
+
* that passes goes to `scoreFit`, where the model reads the notice and the RFP
|
|
7
|
+
* documents and answers in a fixed JSON shape; without a model the keyword
|
|
8
|
+
* score stands in, marked as such.
|
|
9
|
+
*/
|
|
10
|
+
import { z } from 'zod';
|
|
11
|
+
|
|
12
|
+
/** Profullstack's capabilities (niche focus: software, security, automation, hardware rental). */
|
|
13
|
+
export const PROFILE = {
|
|
14
|
+
company: 'Profullstack, Inc.',
|
|
15
|
+
summary:
|
|
16
|
+
'Profullstack builds and operates custom software, web/mobile apps, APIs and AI agents; runs security work (vulnerability scanning, pentest support, threat monitoring via ThreatCrush); automates business processes (workflow and agentic automation, data pipelines, integrations); and rents compute (GPU and server capacity on the c0mpute network). Small business, California based, remote delivery.',
|
|
17
|
+
capabilities: [
|
|
18
|
+
'Custom software development (web, mobile, PWA, desktop), API and integration work',
|
|
19
|
+
'Case management, permitting, CRM and workflow systems: build, configure, integrate, migrate',
|
|
20
|
+
'Cybersecurity: vulnerability assessment, application security review, monitoring, incident response support',
|
|
21
|
+
'Automation: business process automation, AI agents, data pipelines, document processing',
|
|
22
|
+
'Cloud and hosting operations, DevOps, software maintenance and support',
|
|
23
|
+
'Hardware and compute rental: GPU and server capacity, on-demand',
|
|
24
|
+
],
|
|
25
|
+
naics: ['541511', '541512', '541513', '541519', '518210', '541690', '541715', '532420'],
|
|
26
|
+
not_a_fit: [
|
|
27
|
+
'construction, facilities, janitorial, landscaping, food, vehicles, medical or clinical services',
|
|
28
|
+
'physical goods resale that requires an authorized manufacturer reseller agreement the bidder does not hold',
|
|
29
|
+
'staffing-only contracts requiring on-site cleared personnel',
|
|
30
|
+
],
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const STRONG = [
|
|
34
|
+
'software', 'saas', 'application development', 'app development', 'web application', 'mobile app', 'mobile application', 'apis?', 'system integration', 'integrations?',
|
|
35
|
+
'cybersecurity', 'cyber security', 'information security', 'penetration test(ing)?', 'pentest', 'vulnerability', 'security assessment', 'web application firewall', 'siem',
|
|
36
|
+
'automation', 'artificial intelligence', 'ai', 'machine learning', 'data analytics', 'data platform', 'chatbot',
|
|
37
|
+
'case management', 'permit(ting)? (management|system|software)', 'crm', 'licensing system', 'workflow',
|
|
38
|
+
'it services', 'information technology', 'it modernization', 'systems integrator', 'solutions integrator', 'devops', 'cloud', 'hosting', 'website', 'web portal',
|
|
39
|
+
'gpu', 'high performance computing', 'hpc', 'servicenow', 'erp', 'it support',
|
|
40
|
+
];
|
|
41
|
+
const WEAK = ['computer', 'servers?', 'storage', 'network(ing)?', 'license', 'subscription', 'digital', 'database', 'technology', 'it'];
|
|
42
|
+
const NEGATIVE = [
|
|
43
|
+
'construction', 'janitorial', 'custodial', 'landscap\\w*', 'roofing', 'paving', 'hvac', 'plumbing', 'electrical contractor', 'food', 'catering',
|
|
44
|
+
'vehicles?', 'tires', 'fuel', 'uniforms?', 'medical supplies', 'pharmacy', 'gift cards?', 'furniture', 'printing', 'asphalt', 'concrete',
|
|
45
|
+
'valves?', 'gaskets?', 'ammunition', 'aircraft parts', 'nsn', 'repair parts', 'dredging', 'demolition', 'mowing', 'towing', 'airplane', 'aircraft maintenance',
|
|
46
|
+
'transportation services', 'bus', 'housing', 'polygraph', 'psychiatric', 'psychological', 'sewing', 'water well', 'architectural', 'engineering services',
|
|
47
|
+
];
|
|
48
|
+
const rx = (words) => words.map((w) => new RegExp(`\\b${w}\\b`, 'i'));
|
|
49
|
+
const STRONG_RX = rx(STRONG);
|
|
50
|
+
const WEAK_RX = rx(WEAK);
|
|
51
|
+
const NEGATIVE_RX = rx(NEGATIVE);
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 0 = skip, higher = more likely a fit. Cheap and deterministic, whole words only.
|
|
55
|
+
* Nothing passes without a strong keyword or one of our NAICS codes.
|
|
56
|
+
*/
|
|
57
|
+
export function prefilter({ title = '', description = '', naics = '' } = {}) {
|
|
58
|
+
const head = String(title);
|
|
59
|
+
const body = String(description).slice(0, 1500);
|
|
60
|
+
const n = String(naics || '');
|
|
61
|
+
const naicsHit = PROFILE.naics.some((c) => n.includes(c)) ? 4 : /^54151|^5182/.test(n) ? 3 : 0;
|
|
62
|
+
const strongTitle = STRONG_RX.filter((r) => r.test(head)).length;
|
|
63
|
+
const weakTitle = WEAK_RX.filter((r) => r.test(head)).length;
|
|
64
|
+
const strongBody = STRONG_RX.filter((r) => !r.test(head) && r.test(body)).length;
|
|
65
|
+
// Long notices carry boilerplate ("cloud", "workflow"): the body only counts when the title is about tech too.
|
|
66
|
+
if (!strongTitle && !naicsHit && !(strongBody && weakTitle)) return 0;
|
|
67
|
+
let score = strongTitle * 4 + strongBody * 2 + weakTitle + naicsHit;
|
|
68
|
+
score -= NEGATIVE_RX.filter((r) => r.test(head)).length * 5;
|
|
69
|
+
return Math.max(0, Math.min(score, 30));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export const FitSchema = z.object({
|
|
73
|
+
score: z.number().min(0).max(100),
|
|
74
|
+
verdict: z.enum(['bid', 'maybe', 'no_bid']),
|
|
75
|
+
summary: z.string(),
|
|
76
|
+
why: z.array(z.string()).default([]),
|
|
77
|
+
risks: z.array(z.string()).default([]),
|
|
78
|
+
requirements: z.array(z.string()).default([]),
|
|
79
|
+
forms: z.array(z.string()).default([]),
|
|
80
|
+
vendor_registration: z.array(z.string()).default([]),
|
|
81
|
+
set_aside_ok: z.boolean().nullable().default(null),
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
const SYSTEM = `You are a capture manager deciding whether a small company should bid on a government solicitation.
|
|
85
|
+
Company profile:
|
|
86
|
+
${PROFILE.summary}
|
|
87
|
+
Capabilities:
|
|
88
|
+
- ${PROFILE.capabilities.join('\n- ')}
|
|
89
|
+
Not a fit: ${PROFILE.not_a_fit.join('; ')}.
|
|
90
|
+
Read the solicitation and documents. Be strict. Renewing or reselling a named product's licenses or maintenance needs an authorized reseller: score those under 40. Score 70+ only when the work is clearly something the company does and it can legally bid (set-asides, reseller authorizations, clearances, on-site requirements).
|
|
91
|
+
List the mandatory requirements, every form or certification the buyer requires (ONLY names written in the text; never invent form names or numbers), and any vendor registration needed to bid (for example SAM.gov UEI, Cal eProcure supplier ID, the county's own vendor portal).
|
|
92
|
+
Answer with JSON only.`;
|
|
93
|
+
|
|
94
|
+
const clip = (s, n) => (s && s.length > n ? `${s.slice(0, n)}\n[...truncated]` : s || '');
|
|
95
|
+
|
|
96
|
+
export function fitPrompt(sol, docs = []) {
|
|
97
|
+
const docText = docs
|
|
98
|
+
.filter((d) => d.text)
|
|
99
|
+
.map((d) => `--- ${d.kind === 'notice' ? 'Notice' : 'Document'}: ${d.name || d.url}\n${clip(d.text, 3000)}`)
|
|
100
|
+
.join('\n\n');
|
|
101
|
+
return clip(
|
|
102
|
+
`Solicitation: ${sol.title}
|
|
103
|
+
Number: ${sol.number || 'n/a'}
|
|
104
|
+
Buyer: ${sol.agency || 'n/a'} (${sol.level || 'n/a'}${sol.region ? ', ' + sol.region : ''})
|
|
105
|
+
Type: ${sol.notice_type || 'n/a'}
|
|
106
|
+
Due: ${sol.due_at || 'n/a'}
|
|
107
|
+
NAICS: ${sol.naics || 'n/a'} Set-aside: ${sol.set_aside || 'none stated'}
|
|
108
|
+
Link: ${sol.url || 'n/a'}
|
|
109
|
+
|
|
110
|
+
${clip(sol.description, 2500)}
|
|
111
|
+
|
|
112
|
+
${docText}`,
|
|
113
|
+
7000,
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const RESALE = /\b(renewal|subscriptions?|maintenance|licens(e|es|ing)|brand[ -](only|specific|name)|support renewal|accelerators?)\b/i;
|
|
118
|
+
const SERVICE_WORK = /\b(develop\w*|implement\w*|integrat\w*|moderniz\w*|replacement|solution|configuration|enhancement|services? (rfp|request)|case management|on-call it|consult\w*|sustainment|operations)\b/i;
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Buying a named product's licenses, renewal or maintenance needs an authorized
|
|
122
|
+
* reseller, which the bidder is not by default: cap the score and say why.
|
|
123
|
+
* Small models rate these as "software, so a fit" every time.
|
|
124
|
+
*/
|
|
125
|
+
export function capResale(sol, fit) {
|
|
126
|
+
const t = String(sol.title || '');
|
|
127
|
+
if (!RESALE.test(t) || SERVICE_WORK.test(t)) return fit;
|
|
128
|
+
if (fit.score <= 45) return fit;
|
|
129
|
+
return {
|
|
130
|
+
...fit,
|
|
131
|
+
score: 45,
|
|
132
|
+
verdict: fit.verdict === 'bid' ? 'maybe' : fit.verdict,
|
|
133
|
+
risks: [...(fit.risks || []), 'Looks like a license/renewal/maintenance buy of a named product: usually needs an authorized reseller agreement. Capped at 45.'],
|
|
134
|
+
capped: 'resale',
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Keyword-only fit, used when no model answered. */
|
|
139
|
+
export function keywordFit(sol) {
|
|
140
|
+
const p = sol.prefilter ?? prefilter(sol);
|
|
141
|
+
const score = Math.min(60, p * 4);
|
|
142
|
+
return {
|
|
143
|
+
score,
|
|
144
|
+
verdict: score >= 40 ? 'maybe' : 'no_bid',
|
|
145
|
+
summary: 'Keyword match only (no AI read yet). Read the solicitation before deciding.',
|
|
146
|
+
why: [],
|
|
147
|
+
risks: ['Not read by a model; score is keyword based.'],
|
|
148
|
+
requirements: [],
|
|
149
|
+
forms: [],
|
|
150
|
+
vendor_registration: [],
|
|
151
|
+
set_aside_ok: null,
|
|
152
|
+
method: 'keywords',
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Score one solicitation. `ai` is an object with generateObject (an AiRouter or
|
|
158
|
+
* the module); without it, or when every provider fails, the keyword fit is used.
|
|
159
|
+
*/
|
|
160
|
+
export async function scoreFit(sol, docs, { ai, timeoutMs } = {}) {
|
|
161
|
+
if (!ai) return keywordFit(sol);
|
|
162
|
+
try {
|
|
163
|
+
const r = await ai.generateObject({
|
|
164
|
+
system: SYSTEM,
|
|
165
|
+
user: fitPrompt(sol, docs),
|
|
166
|
+
schema: FitSchema,
|
|
167
|
+
jsonSchema: z.toJSONSchema(FitSchema),
|
|
168
|
+
name: 'fit',
|
|
169
|
+
feature: 'gov-contracts:fit',
|
|
170
|
+
maxTokens: 1800,
|
|
171
|
+
temperature: 0.2,
|
|
172
|
+
...(timeoutMs ? { timeoutMs } : {}),
|
|
173
|
+
});
|
|
174
|
+
return capResale(sol, { ...r.object, score: Math.round(r.object.score), method: 'ai', provider: r.provider, model: r.model });
|
|
175
|
+
} catch (e) {
|
|
176
|
+
return { ...keywordFit(sol), ai_error: String(e?.message || e).slice(0, 300) };
|
|
177
|
+
}
|
|
178
|
+
}
|
package/src/http.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Polite, read-only fetching. Page and JSON reads go through
|
|
3
|
+
* @profullstack/scraper-daemon's fetcher (robots.txt, one request at a time per
|
|
4
|
+
* host with a delay, 429 hold-back, public addresses only, size and time caps).
|
|
5
|
+
* Binary RFP files (PDFs) need bytes, which that fetcher does not return, so
|
|
6
|
+
* `fetchBytes` reads them under the same rules, from READ_ONLY_HOSTS only.
|
|
7
|
+
*/
|
|
8
|
+
import { createFetcher, hostGate, isPublicAddress } from '@profullstack/scraper-daemon';
|
|
9
|
+
import { lookup } from 'node:dns/promises';
|
|
10
|
+
import { READ_ONLY_HOSTS } from './safety.js';
|
|
11
|
+
import { VERSION } from './version.js';
|
|
12
|
+
|
|
13
|
+
export const USER_AGENT = `gov-contracts/${VERSION} (+https://gov.procurement.pit.world; read-only)`;
|
|
14
|
+
|
|
15
|
+
const gate = hostGate({ delayMs: Number(process.env.FETCH_DELAY_MS || 2000) });
|
|
16
|
+
let fetcher;
|
|
17
|
+
export function http() {
|
|
18
|
+
fetcher ??= createFetcher({ userAgent: USER_AGENT, gate, timeoutMs: 30_000, maxBytes: 4_000_000 });
|
|
19
|
+
return fetcher;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const allowedHost = (host) => READ_ONLY_HOSTS.some((h) => host === h || host.endsWith(`.${h}`));
|
|
23
|
+
|
|
24
|
+
/** GET a file's bytes. Follows redirects (re-checking each hop), 4 MB and 45 s caps. */
|
|
25
|
+
export async function fetchBytes(url, { maxBytes = 4_000_000, timeoutMs = 45_000 } = {}) {
|
|
26
|
+
const deadline = AbortSignal.timeout(timeoutMs);
|
|
27
|
+
let at = url;
|
|
28
|
+
for (let hop = 0; hop < 5; hop++) {
|
|
29
|
+
const u = new URL(at);
|
|
30
|
+
if (u.protocol !== 'https:' || !allowedHost(u.hostname)) throw new Error(`not a read-only source host: ${u.hostname}`);
|
|
31
|
+
const addrs = await lookup(u.hostname, { all: true });
|
|
32
|
+
if (!addrs.length || !addrs.every((a) => isPublicAddress(a.address))) throw new Error(`refusing non-public address for ${u.hostname}`);
|
|
33
|
+
const res = await gate.run(u.host, () => fetch(u, { redirect: 'manual', signal: deadline, headers: { 'user-agent': USER_AGENT } }));
|
|
34
|
+
if (res.status >= 300 && res.status < 400 && res.headers.get('location')) {
|
|
35
|
+
res.body?.cancel().catch(() => {});
|
|
36
|
+
at = new URL(res.headers.get('location'), u).toString();
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
if (!res.ok) {
|
|
40
|
+
res.body?.cancel().catch(() => {});
|
|
41
|
+
throw new Error(`${res.status} from ${u.hostname}`);
|
|
42
|
+
}
|
|
43
|
+
const len = Number(res.headers.get('content-length') || 0);
|
|
44
|
+
if (len > maxBytes) {
|
|
45
|
+
res.body?.cancel().catch(() => {});
|
|
46
|
+
throw new Error(`file too large (${len} bytes)`);
|
|
47
|
+
}
|
|
48
|
+
const chunks = [];
|
|
49
|
+
let total = 0;
|
|
50
|
+
for await (const chunk of res.body) {
|
|
51
|
+
total += chunk.length;
|
|
52
|
+
if (total > maxBytes) throw new Error('file too large');
|
|
53
|
+
chunks.push(chunk);
|
|
54
|
+
}
|
|
55
|
+
return { bytes: Buffer.concat(chunks), type: res.headers.get('content-type') || '', url: at };
|
|
56
|
+
}
|
|
57
|
+
throw new Error('too many redirects');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Plain text from HTML: drop scripts/styles/tags, decode the common entities, squeeze whitespace. */
|
|
61
|
+
export function htmlToText(html) {
|
|
62
|
+
return String(html || '')
|
|
63
|
+
.replace(/<(script|style)[\s\S]*?<\/\1>/gi, ' ')
|
|
64
|
+
.replace(/<br\s*\/?>|<\/p>|<\/li>|<\/h\d>/gi, '\n')
|
|
65
|
+
.replace(/<[^>]+>/g, ' ')
|
|
66
|
+
.replace(/ /g, ' ')
|
|
67
|
+
.replace(/&/g, '&')
|
|
68
|
+
.replace(/</g, '<')
|
|
69
|
+
.replace(/>/g, '>')
|
|
70
|
+
.replace(/"/g, '"')
|
|
71
|
+
.replace(/'|’|‘/g, "'")
|
|
72
|
+
.replace(/“|”/g, '"')
|
|
73
|
+
.replace(/–|—/g, '-')
|
|
74
|
+
.replace(/&#(\d+);/g, (_, n) => String.fromCharCode(Number(n)))
|
|
75
|
+
.replace(/[ \t\f\v]+/g, ' ')
|
|
76
|
+
.replace(/\s*\n\s*/g, '\n')
|
|
77
|
+
.trim();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Text from a PDF (unpdf, pure JS). Returns '' for scanned PDFs with no text layer. */
|
|
81
|
+
export async function pdfText(bytes, maxChars = 60_000) {
|
|
82
|
+
const { extractText, getDocumentProxy } = await import('unpdf');
|
|
83
|
+
const pdf = await getDocumentProxy(new Uint8Array(bytes));
|
|
84
|
+
const { text } = await extractText(pdf, { mergePages: true });
|
|
85
|
+
return String(text || '').replace(/[ \t]+/g, ' ').slice(0, maxChars);
|
|
86
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** @profullstack/gov-contracts: library entry. The hosted app is ./server (src/app.js). */
|
|
2
|
+
export { HUMAN_ONLY, READ_ONLY_HOSTS, DRAFT_BANNER, assertHumanOnly } from './safety.js';
|
|
3
|
+
export { PROFILE, prefilter, scoreFit, keywordFit, FitSchema } from './fit.js';
|
|
4
|
+
export { ADAPTERS, listSources, registry, sam, lacounty, digest } from './sources/index.js';
|
|
5
|
+
export { parseDigest, parseMyGovWatch } from './sources/digest.js';
|
|
6
|
+
export { draftProposal, toMarkdown, vendorPortals, ProposalSchema } from './propose.js';
|
|
7
|
+
export { ingestSource, ingestDigest, workTick, startDaemon } from './pipeline.js';
|
|
8
|
+
export { makeAi, aiStatus } from './ai.js';
|
|
9
|
+
export { VERSION } from './version.js';
|
package/src/mcp.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP server (streamable HTTP, stateless). Public tools read solicitations and
|
|
3
|
+
* sources; operator tools (Bearer OPERATOR_API_KEY on the connection) work the
|
|
4
|
+
* queue. There is no tool that submits, registers, signs, prices or emails:
|
|
5
|
+
* resolve_intervention only RECORDS what a person did.
|
|
6
|
+
*/
|
|
7
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
8
|
+
import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
|
|
9
|
+
import { z } from 'zod';
|
|
10
|
+
import { bearerIsOperator } from './auth.js';
|
|
11
|
+
import { listSources } from './sources/index.js';
|
|
12
|
+
import { publicSolicitation, startDraft } from './service.js';
|
|
13
|
+
import { ingestDigest } from './pipeline.js';
|
|
14
|
+
import {
|
|
15
|
+
documentsFor, getProposal, getSolicitation, latestProposal, listInterventions, resolveIntervention, searchSolicitations, stats,
|
|
16
|
+
} from './store.js';
|
|
17
|
+
import { VERSION } from './version.js';
|
|
18
|
+
|
|
19
|
+
const text = (v) => ({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v, null, 2) }] });
|
|
20
|
+
const fail = (msg) => ({ isError: true, content: [{ type: 'text', text: msg }] });
|
|
21
|
+
const NEED_KEY = 'Operator tool: send the gov-contracts operator key as "Authorization: Bearer <key>" on the MCP connection.';
|
|
22
|
+
|
|
23
|
+
export const TOOL_NAMES = [
|
|
24
|
+
'search_solicitations', 'get_solicitation', 'list_sources', 'stats',
|
|
25
|
+
'list_interventions', 'get_proposal', 'resolve_intervention', 'draft_proposal', 'ingest_digest',
|
|
26
|
+
];
|
|
27
|
+
|
|
28
|
+
export function buildMcpServer({ isOperator = false } = {}) {
|
|
29
|
+
const server = new McpServer(
|
|
30
|
+
{ name: 'gov.procurement', version: VERSION },
|
|
31
|
+
{
|
|
32
|
+
instructions:
|
|
33
|
+
'gov.procurement finds government contract opportunities (SAM.gov, LA County, forwarded bid digests), reads the RFP, scores fit for Profullstack and drafts proposals. ' +
|
|
34
|
+
'It never submits a bid, registers a vendor account, signs or certifies, sets a price or contacts an agency: those are intervention cards a person works. ' +
|
|
35
|
+
'Typical loop: search_solicitations -> get_solicitation -> (operator) list_interventions -> get_proposal -> a person submits -> resolve_intervention to record it.',
|
|
36
|
+
},
|
|
37
|
+
);
|
|
38
|
+
const op = (fn) => async (args) => {
|
|
39
|
+
if (!isOperator) return fail(NEED_KEY);
|
|
40
|
+
try { return text(await fn(args)); } catch (e) { return fail(String(e?.message || e)); }
|
|
41
|
+
};
|
|
42
|
+
const pub = (fn) => async (args) => {
|
|
43
|
+
try { return text(await fn(args)); } catch (e) { return fail(String(e?.message || e)); }
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
server.registerTool('search_solicitations', {
|
|
47
|
+
description: 'Open government solicitations. Filter by keyword, level (federal|state|county|city) and source (sam|lacounty|digest). Ordered by fit (operators) or due date.',
|
|
48
|
+
inputSchema: {
|
|
49
|
+
q: z.string().optional(), level: z.enum(['federal', 'state', 'county', 'city']).optional(), source: z.enum(['sam', 'lacounty', 'digest']).optional(),
|
|
50
|
+
order: z.enum(['fit', 'due', 'new']).optional(), limit: z.number().int().min(1).max(100).optional(),
|
|
51
|
+
},
|
|
52
|
+
annotations: { readOnlyHint: true },
|
|
53
|
+
}, pub(({ q, level, source, order, limit }) => searchSolicitations({ q, level, source, order: order || (isOperator ? 'fit' : 'due'), limit: limit || 25 }).map((s) => publicSolicitation(s, isOperator))));
|
|
54
|
+
|
|
55
|
+
server.registerTool('get_solicitation', {
|
|
56
|
+
description: 'One solicitation by id (e.g. "sam:<notice id>", "lacounty:50629"), with the documents read for it.',
|
|
57
|
+
inputSchema: { id: z.string() },
|
|
58
|
+
annotations: { readOnlyHint: true },
|
|
59
|
+
}, pub(({ id }) => {
|
|
60
|
+
const s = getSolicitation(id);
|
|
61
|
+
if (!s) throw new Error('not found');
|
|
62
|
+
const p = isOperator ? latestProposal(id) : null;
|
|
63
|
+
return { ...publicSolicitation(s, isOperator), documents: documentsFor(id, { withText: false }), ...(p ? { proposal: { id: p.id, version: p.version, status: p.status } } : {}) };
|
|
64
|
+
}));
|
|
65
|
+
|
|
66
|
+
server.registerTool('list_sources', {
|
|
67
|
+
description: "Where contract opportunities come from: Datamart's contracts registry joined with the sources gov-contracts reads.",
|
|
68
|
+
inputSchema: {},
|
|
69
|
+
annotations: { readOnlyHint: true },
|
|
70
|
+
}, pub(() => listSources()));
|
|
71
|
+
|
|
72
|
+
server.registerTool('stats', { description: 'Counts by status, source and level, and the last run of each job.', inputSchema: {}, annotations: { readOnlyHint: true } }, pub(() => stats()));
|
|
73
|
+
|
|
74
|
+
server.registerTool('list_interventions', {
|
|
75
|
+
description: 'Operator: the human intervention queue (cards a person must work).',
|
|
76
|
+
inputSchema: { status: z.enum(['open', 'done', 'dismissed', 'all']).optional(), kind: z.string().optional() },
|
|
77
|
+
annotations: { readOnlyHint: true },
|
|
78
|
+
}, op(({ status, kind }) => listInterventions({ status: status || 'open', kind }).map(({ copy_text, ...iv }) => ({ ...iv, has_copy_text: !!copy_text }))));
|
|
79
|
+
|
|
80
|
+
server.registerTool('get_proposal', {
|
|
81
|
+
description: 'Operator: a proposal draft (markdown) by proposal id, or the latest for a solicitation id.',
|
|
82
|
+
inputSchema: { id: z.string() },
|
|
83
|
+
annotations: { readOnlyHint: true },
|
|
84
|
+
}, op(({ id }) => {
|
|
85
|
+
const p = getProposal(id) || latestProposal(id);
|
|
86
|
+
if (!p) throw new Error('not found');
|
|
87
|
+
return { id: p.id, solicitation_id: p.solicitation_id, version: p.version, status: p.status, markdown: p.markdown };
|
|
88
|
+
}));
|
|
89
|
+
|
|
90
|
+
server.registerTool('resolve_intervention', {
|
|
91
|
+
description: 'Operator: record that a PERSON did (done) or skipped (dismissed) a card, with a note (confirmation number, UEI, reason). Does not perform the action.',
|
|
92
|
+
inputSchema: { id: z.string(), status: z.enum(['done', 'dismissed', 'open']), note: z.string().max(2000).optional() },
|
|
93
|
+
}, op(({ id, status, note }) => {
|
|
94
|
+
const r = resolveIntervention(id, { status, note, by: 'mcp operator key' });
|
|
95
|
+
if (!r) throw new Error('not found');
|
|
96
|
+
return r;
|
|
97
|
+
}));
|
|
98
|
+
|
|
99
|
+
server.registerTool('draft_proposal', {
|
|
100
|
+
description: 'Operator: (re)draft a proposal for a solicitation in the background; its cards appear in the queue when done.',
|
|
101
|
+
inputSchema: { id: z.string() },
|
|
102
|
+
}, op(({ id }) => startDraft(id)));
|
|
103
|
+
|
|
104
|
+
server.registerTool('ingest_digest', {
|
|
105
|
+
description: 'Operator: add every solicitation listed in a forwarded bid digest (plain text). Links in it are ignored.',
|
|
106
|
+
inputSchema: { text: z.string().max(200_000) },
|
|
107
|
+
}, op(({ text: body }) => ingestDigest(body)));
|
|
108
|
+
|
|
109
|
+
return server;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export async function handleMcp(request) {
|
|
113
|
+
const server = buildMcpServer({ isOperator: bearerIsOperator(request.headers.get('authorization')) });
|
|
114
|
+
const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
|
|
115
|
+
await server.connect(transport);
|
|
116
|
+
return transport.handleRequest(request);
|
|
117
|
+
}
|