@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/propose.js
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Proposal drafts and the human queue.
|
|
3
|
+
*
|
|
4
|
+
* A draft has a cover letter, a technical approach mapped to the RFP's
|
|
5
|
+
* requirements, a pricing SECTION with every number left blank, the required
|
|
6
|
+
* forms checklist and a compliance matrix. It is never sent anywhere. Each
|
|
7
|
+
* draft queues the cards a person must work: price it, sign/certify the forms,
|
|
8
|
+
* register on the buyer's portal if not yet done, and finally review and
|
|
9
|
+
* submit it themselves.
|
|
10
|
+
*/
|
|
11
|
+
import { z } from 'zod';
|
|
12
|
+
import { DRAFT_BANNER } from './safety.js';
|
|
13
|
+
import { PROFILE, fitPrompt } from './fit.js';
|
|
14
|
+
import { latestProposal, queueIntervention, saveProposal, setSolicitation } from './store.js';
|
|
15
|
+
|
|
16
|
+
export const ProposalSchema = z.object({
|
|
17
|
+
cover_letter: z.string(),
|
|
18
|
+
executive_summary: z.string(),
|
|
19
|
+
technical_approach: z.string(),
|
|
20
|
+
management_and_staffing: z.string().default(''),
|
|
21
|
+
schedule: z.string().default(''),
|
|
22
|
+
compliance_matrix: z.array(z.object({ requirement: z.string(), response: z.string(), section: z.string().default('') })).default([]),
|
|
23
|
+
forms_checklist: z.array(z.object({ form: z.string(), action: z.enum(['fill', 'sign', 'notarize', 'certify', 'attach', 'register']).default('fill'), note: z.string().default('') })).default([]),
|
|
24
|
+
pricing_structure: z.array(z.object({ item: z.string(), unit: z.string().default('') })).default([]),
|
|
25
|
+
questions_for_buyer: z.array(z.string()).default([]),
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
const SYSTEM = `You write government proposal DRAFTS for ${PROFILE.company} for a person to review. ${PROFILE.summary}
|
|
29
|
+
Rules:
|
|
30
|
+
- Respond to the buyer's actual requirements; reuse their section names and requirement wording in the compliance matrix.
|
|
31
|
+
- NEVER state a price, rate, discount or total. Pricing is only the structure (line items and units); a person fills in numbers.
|
|
32
|
+
- NEVER claim certifications, past contracts, clearances, insurance or staff that are not given to you. Where the RFP needs them, write [TO CONFIRM: ...].
|
|
33
|
+
- NEVER sign, certify or attest. List every form the buyer requires in forms_checklist with the action a person must take.
|
|
34
|
+
- The due date is when the PROPOSAL is due, not when work is delivered. Never promise a delivery date; schedules are relative to award (\"week 1-4 after award\").
|
|
35
|
+
- Plain, specific language. No marketing filler. No em dashes.
|
|
36
|
+
Answer with JSON only.`;
|
|
37
|
+
|
|
38
|
+
/** Portals a bidder must be registered on to bid, by source and buyer. */
|
|
39
|
+
export function vendorPortals(sol) {
|
|
40
|
+
if (sol.source === 'sam' || sol.level === 'federal') {
|
|
41
|
+
return [{ key: 'sam.gov', name: 'SAM.gov entity registration (UEI)', url: 'https://sam.gov/entity-registration', steps: ['Sign in to SAM.gov with Login.gov.', 'Register the entity (Profullstack, Inc.) to get a Unique Entity ID; choose "all awards".', 'Add NAICS 541511, 541512, 541519, 518210 and the small-business representations.', 'Registration is free; it takes 7-10 business days to activate. Record the UEI and CAGE code here when done.'] }];
|
|
42
|
+
}
|
|
43
|
+
if (sol.source === 'lacounty') {
|
|
44
|
+
return [{ key: 'lacounty', name: 'LA County vendor registration (WebVen)', url: 'https://camisvr.co.la.ca.us/WebVen/', steps: ['Open WebVen and register Profullstack, Inc. as a vendor.', 'Add the commodity codes for software, IT services and computer maintenance.', 'Record the vendor number here when done.'] }];
|
|
45
|
+
}
|
|
46
|
+
if (sol.level === 'state' && sol.region === 'CA') {
|
|
47
|
+
return [{ key: 'caleprocure', name: 'Cal eProcure supplier registration (Supplier ID)', url: 'https://caleprocure.ca.gov/pages/index.aspx', steps: ['Open Cal eProcure and register as a supplier.', 'Optional: apply for Small Business (SB/DVBE) certification; it scores bid preference.', 'Record the Supplier ID here when done.'] }];
|
|
48
|
+
}
|
|
49
|
+
const buyer = sol.agency || 'the buyer';
|
|
50
|
+
return [{ key: `buyer:${buyer.toLowerCase()}`, name: `${buyer} vendor portal`, url: null, steps: [`Find ${buyer}'s procurement page (search "${buyer} bid opportunities").`, 'Register as a vendor there (most cities use PlanetBids, OpenGov, Bonfire or BidNet).', 'Download the solicitation documents and attach them on this card (paste the link in the note).'] }];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const md = (s) => String(s || '').trim();
|
|
54
|
+
|
|
55
|
+
export function toMarkdown(sol, p, { method } = {}) {
|
|
56
|
+
const lines = [
|
|
57
|
+
`> ${DRAFT_BANNER}`,
|
|
58
|
+
'',
|
|
59
|
+
`# Proposal draft: ${sol.title}`,
|
|
60
|
+
'',
|
|
61
|
+
`- Buyer: ${sol.agency || 'n/a'}`,
|
|
62
|
+
`- Solicitation: ${sol.number || 'n/a'}${sol.url ? ` (${sol.url})` : ''}`,
|
|
63
|
+
`- Due: ${sol.due_at || 'n/a'}`,
|
|
64
|
+
`- Prepared by: ${method === 'template' ? 'template (no AI answer)' : method === 'partial' ? 'AI draft, some sections template' : 'AI draft'} for ${PROFILE.company}`,
|
|
65
|
+
'',
|
|
66
|
+
'## Cover letter',
|
|
67
|
+
'',
|
|
68
|
+
md(p.cover_letter),
|
|
69
|
+
'',
|
|
70
|
+
'## Executive summary',
|
|
71
|
+
'',
|
|
72
|
+
md(p.executive_summary),
|
|
73
|
+
'',
|
|
74
|
+
'## Technical approach',
|
|
75
|
+
'',
|
|
76
|
+
md(p.technical_approach),
|
|
77
|
+
];
|
|
78
|
+
if (md(p.management_and_staffing)) lines.push('', '## Management and staffing', '', md(p.management_and_staffing));
|
|
79
|
+
if (md(p.schedule)) lines.push('', '## Schedule', '', md(p.schedule));
|
|
80
|
+
lines.push('', '## Pricing (a person sets every number)', '', '| Item | Unit | Price |', '|---|---|---|');
|
|
81
|
+
for (const r of p.pricing_structure?.length ? p.pricing_structure : [{ item: 'Total firm-fixed price', unit: 'lot' }]) lines.push(`| ${r.item} | ${r.unit || ''} | [SET BY A PERSON] |`);
|
|
82
|
+
lines.push('', '## Required forms checklist', '');
|
|
83
|
+
if (p.forms_checklist?.length) for (const f of p.forms_checklist) lines.push(`- [ ] ${f.form} (${f.action}, by a person)${f.note ? `: ${f.note}` : ''}`);
|
|
84
|
+
else lines.push('- [ ] Open the solicitation documents and list every required form here (none were named in the text the system could read).');
|
|
85
|
+
if (p.compliance_matrix?.length) {
|
|
86
|
+
lines.push('', '## Compliance matrix', '', '| Requirement | Response | Section |', '|---|---|---|');
|
|
87
|
+
for (const r of p.compliance_matrix) lines.push(`| ${r.requirement.replace(/\|/g, '/')} | ${r.response.replace(/\|/g, '/')} | ${r.section || ''} |`);
|
|
88
|
+
}
|
|
89
|
+
if (p.questions_for_buyer?.length) {
|
|
90
|
+
lines.push('', '## Questions for the buyer (for a person to send, if wanted)', '');
|
|
91
|
+
for (const q of p.questions_for_buyer) lines.push(`- ${q}`);
|
|
92
|
+
}
|
|
93
|
+
return lines.join('\n') + '\n';
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** A skeleton when no model answered, so the card still exists and a person can write it. */
|
|
97
|
+
export function templateProposal(sol, fit) {
|
|
98
|
+
return {
|
|
99
|
+
cover_letter: `[TO WRITE] Letter to ${sol.agency || 'the buyer'} for ${sol.number || sol.title}: who we are, why we fit, point of contact.`,
|
|
100
|
+
executive_summary: '[TO WRITE] Two or three sentences: the buyer\'s problem, our approach, why us.',
|
|
101
|
+
technical_approach: '[TO WRITE] Respond to each requirement in the solicitation, in its own order and wording.',
|
|
102
|
+
management_and_staffing: '',
|
|
103
|
+
schedule: '',
|
|
104
|
+
compliance_matrix: (fit?.requirements || []).map((r) => ({ requirement: r, response: '[TO WRITE]', section: '' })),
|
|
105
|
+
forms_checklist: [],
|
|
106
|
+
pricing_structure: [],
|
|
107
|
+
questions_for_buyer: [],
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The draft in three small parts: a 4B model answers each inside its timeout, and a part that fails falls back alone. */
|
|
112
|
+
const PARTS = [
|
|
113
|
+
{
|
|
114
|
+
name: 'letter',
|
|
115
|
+
ask: 'Write cover_letter (to the buyer, under 250 words, signature block left as [NAME, TITLE]) and executive_summary (under 150 words).',
|
|
116
|
+
schema: ProposalSchema.pick({ cover_letter: true, executive_summary: true }),
|
|
117
|
+
maxTokens: 1500,
|
|
118
|
+
},
|
|
119
|
+
{
|
|
120
|
+
name: 'approach',
|
|
121
|
+
ask: 'Write technical_approach (markdown, one subsection per buyer requirement, in their order and wording, under 700 words), management_and_staffing and schedule (each under 150 words; roles not names).',
|
|
122
|
+
schema: ProposalSchema.pick({ technical_approach: true, management_and_staffing: true, schedule: true }),
|
|
123
|
+
maxTokens: 2500,
|
|
124
|
+
},
|
|
125
|
+
{
|
|
126
|
+
name: 'compliance',
|
|
127
|
+
ask: 'Write compliance_matrix (each mandatory requirement and where the proposal answers it), forms_checklist (ONLY forms named in the documents above; none if none are named), pricing_structure (line items and units, NO prices) and questions_for_buyer.',
|
|
128
|
+
schema: ProposalSchema.pick({ compliance_matrix: true, forms_checklist: true, pricing_structure: true, questions_for_buyer: true }),
|
|
129
|
+
maxTokens: 2000,
|
|
130
|
+
},
|
|
131
|
+
];
|
|
132
|
+
|
|
133
|
+
/** Keep a form only if its name (2+ words of it) shows up in what was actually read. Models invent "Form 1..6". */
|
|
134
|
+
export function formsInText(forms, docs) {
|
|
135
|
+
const norm = (t) => ` ${String(t || '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim()} `;
|
|
136
|
+
const text = norm(docs.map((d) => d.text || '').join(' '));
|
|
137
|
+
return forms.filter((f) => {
|
|
138
|
+
const name = norm(String(f.form || f).replace(/^\s*(rfp|rfq|exhibit|attachment|appendix)?[\s-]*(form)?[\s-]*[a-z]?\d+[a-z]?\s*[:.)-]\s*/i, ''));
|
|
139
|
+
return name.trim().length >= 4 && text.includes(name);
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Draft a proposal for a scored solicitation and queue its human cards. */
|
|
144
|
+
export async function draftProposal(sol, docs, { ai, timeoutMs } = {}) {
|
|
145
|
+
const fit = sol.fit || {};
|
|
146
|
+
const base = templateProposal(sol, fit);
|
|
147
|
+
const body = { ...base };
|
|
148
|
+
const used = [];
|
|
149
|
+
if (ai) {
|
|
150
|
+
const context = `${fitPrompt(sol, docs)}\n\nRequirements found: ${JSON.stringify(fit.requirements || []).slice(0, 1500)}`;
|
|
151
|
+
for (const part of PARTS) {
|
|
152
|
+
try {
|
|
153
|
+
const r = await ai.generateObject({
|
|
154
|
+
system: SYSTEM,
|
|
155
|
+
user: `${context}\n\n${part.ask}`,
|
|
156
|
+
schema: part.schema,
|
|
157
|
+
jsonSchema: z.toJSONSchema(part.schema),
|
|
158
|
+
name: `proposal_${part.name}`,
|
|
159
|
+
feature: `gov-contracts:proposal:${part.name}`,
|
|
160
|
+
maxTokens: part.maxTokens,
|
|
161
|
+
temperature: 0.3,
|
|
162
|
+
...(timeoutMs ? { timeoutMs } : {}),
|
|
163
|
+
});
|
|
164
|
+
Object.assign(body, r.object);
|
|
165
|
+
used.push({ part: part.name, provider: r.provider, model: r.model });
|
|
166
|
+
} catch (e) {
|
|
167
|
+
console.error(`proposal ${part.name} failed`, sol.id, String(e?.message || e).slice(0, 200));
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
const method = used.length === PARTS.length ? 'ai' : used.length ? 'partial' : 'template';
|
|
172
|
+
// Forms: only ones named in what we read (the model's and the fit step's), else a reminder to read the documents.
|
|
173
|
+
const named = formsInText([...(body.forms_checklist || []), ...(fit.forms || []).map((f) => ({ form: f, action: 'fill', note: '' }))], docs);
|
|
174
|
+
const seen = new Set();
|
|
175
|
+
body.forms_checklist = named.filter((f) => !seen.has(f.form.toLowerCase()) && seen.add(f.form.toLowerCase()));
|
|
176
|
+
const markdown = toMarkdown(sol, body, { method });
|
|
177
|
+
const provider = [...new Set(used.map((u) => u.provider))].join('+') || null;
|
|
178
|
+
const model = [...new Set(used.map((u) => u.model))].join('+') || null;
|
|
179
|
+
const saved = saveProposal(sol.id, { body: { ...body, method, parts: used }, markdown, provider, model });
|
|
180
|
+
setSolicitation(sol.id, { status: 'drafted' });
|
|
181
|
+
queueCards(sol, { id: saved.id, body, markdown });
|
|
182
|
+
return { ...saved, method, provider, model };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const priorityFor = (sol) => {
|
|
186
|
+
const days = sol.due_at ? (Date.parse(sol.due_at) - Date.now()) / 86400_000 : 60;
|
|
187
|
+
return Math.round(Math.min(100, (sol.fit_score || 0) * 0.7 + Math.max(0, 30 - days)));
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
/** The cards a person works for one draft. Deduped by key, so re-drafting updates them. */
|
|
191
|
+
export function queueCards(sol, proposal) {
|
|
192
|
+
const pri = priorityFor(sol);
|
|
193
|
+
const where = sol.url ? `the solicitation page (${sol.url})` : `${sol.agency}'s procurement page`;
|
|
194
|
+
const portals = vendorPortals(sol);
|
|
195
|
+
for (const p of portals) {
|
|
196
|
+
queueIntervention({
|
|
197
|
+
key: `register_vendor:${p.key}`,
|
|
198
|
+
kind: 'register_vendor',
|
|
199
|
+
solicitation_id: sol.id,
|
|
200
|
+
title: `Register as a vendor: ${p.name}`,
|
|
201
|
+
body: `Bidding on "${sol.title}" (and others from this buyer) needs a vendor account. The system never registers or signs anything itself.\n\n${p.steps.map((s, i) => `${i + 1}. ${s}`).join('\n')}`,
|
|
202
|
+
open_url: p.url,
|
|
203
|
+
priority: pri + 5,
|
|
204
|
+
due_at: sol.due_at,
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
queueIntervention({
|
|
208
|
+
key: `set_price:${sol.id}`,
|
|
209
|
+
kind: 'set_price',
|
|
210
|
+
solicitation_id: sol.id,
|
|
211
|
+
proposal_id: proposal.id,
|
|
212
|
+
title: `Set the price: ${sol.title}`,
|
|
213
|
+
body: `The draft leaves every number blank. Decide the price for each line below and put it in the proposal before submitting.\n\n${(proposal.body.pricing_structure?.length ? proposal.body.pricing_structure : [{ item: 'Total firm-fixed price', unit: 'lot' }]).map((r, i) => `${i + 1}. ${r.item}${r.unit ? ` (${r.unit})` : ''}`).join('\n')}`,
|
|
214
|
+
open_url: sol.url,
|
|
215
|
+
priority: pri,
|
|
216
|
+
due_at: sol.due_at,
|
|
217
|
+
});
|
|
218
|
+
const forms = proposal.body.forms_checklist || [];
|
|
219
|
+
if (forms.length) {
|
|
220
|
+
queueIntervention({
|
|
221
|
+
key: `sign_or_certify:${sol.id}`,
|
|
222
|
+
kind: 'sign_or_certify',
|
|
223
|
+
solicitation_id: sol.id,
|
|
224
|
+
proposal_id: proposal.id,
|
|
225
|
+
title: `Fill, sign or certify ${forms.length} form${forms.length === 1 ? '' : 's'}: ${sol.title}`,
|
|
226
|
+
body: `Only an authorized person at the bidder can complete these.\n\n${forms.map((f, i) => `${i + 1}. ${f.form}: ${f.action}${f.note ? ` (${f.note})` : ''}`).join('\n')}`,
|
|
227
|
+
open_url: sol.url,
|
|
228
|
+
priority: pri,
|
|
229
|
+
due_at: sol.due_at,
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
queueIntervention({
|
|
233
|
+
key: `submit_proposal:${sol.id}`,
|
|
234
|
+
kind: 'submit_proposal',
|
|
235
|
+
solicitation_id: sol.id,
|
|
236
|
+
proposal_id: proposal.id,
|
|
237
|
+
title: `Review and submit (by hand): ${sol.title}`,
|
|
238
|
+
body: `Fit ${sol.fit_score ?? '?'}/100. ${sol.fit?.summary || ''}\n\n1. Read the draft (Copy below, or Proposal).\n2. Fix every [TO CONFIRM] / [TO WRITE], set the prices, complete the forms.\n3. Submit it yourself on ${where} before ${sol.due_at || 'the deadline'}, following the buyer's instructions.\n4. Mark done with the confirmation number. Dismiss if we are not bidding.\n\nThe system never submits, emails the buyer or certifies anything.`,
|
|
239
|
+
open_url: sol.url,
|
|
240
|
+
copy_text: proposal.markdown,
|
|
241
|
+
priority: pri + 10,
|
|
242
|
+
due_at: sol.due_at,
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** A "maybe" fit: a person decides whether it is worth a draft. */
|
|
247
|
+
export function queueDecision(sol) {
|
|
248
|
+
queueIntervention({
|
|
249
|
+
key: `decide_bid:${sol.id}`,
|
|
250
|
+
kind: 'decide_bid',
|
|
251
|
+
solicitation_id: sol.id,
|
|
252
|
+
title: `Worth a bid? ${sol.title}`,
|
|
253
|
+
body: `Fit ${sol.fit_score ?? '?'}/100 (${sol.fit?.verdict || 'maybe'}). ${sol.fit?.summary || ''}\n\nRisks: ${(sol.fit?.risks || []).join('; ') || 'none listed'}\n\n1. Open the solicitation.\n2. "Draft it" queues a proposal draft; Dismiss skips it.`,
|
|
254
|
+
open_url: sol.url,
|
|
255
|
+
priority: Math.round((sol.fit_score || 0) * 0.6),
|
|
256
|
+
due_at: sol.due_at,
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export { latestProposal };
|
package/src/safety.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The hard line. gov-contracts automates everything UP TO the submit button and
|
|
3
|
+
* stops there. Submitting a bid, registering a vendor account, signing or
|
|
4
|
+
* certifying a form, setting a price and writing to an agency are legal and
|
|
5
|
+
* business commitments for the bidder, so they are only ever intervention
|
|
6
|
+
* cards a person works by hand.
|
|
7
|
+
*
|
|
8
|
+
* There is deliberately no code here (or anywhere in this package) that can do
|
|
9
|
+
* any of those things: no mail transport, no form posting to an agency, no
|
|
10
|
+
* portal login. test/safety.test.js scans the source to keep it that way.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Actions the system must never take on its own. Each one maps to a card kind. */
|
|
14
|
+
export const HUMAN_ONLY = Object.freeze({
|
|
15
|
+
submit_proposal: 'Submitting a proposal or bid to a government buyer',
|
|
16
|
+
register_vendor: 'Registering or updating a vendor/supplier account on a procurement portal (SAM.gov UEI, Cal eProcure, PlanetBids, county portals)',
|
|
17
|
+
sign_or_certify: 'Signing, notarizing or certifying any form, representation or affidavit',
|
|
18
|
+
set_price: 'Setting the price, rates or any number the bidder is bound by',
|
|
19
|
+
contact_agency: 'Emailing, calling or messaging an agency, a contracting officer or any third party',
|
|
20
|
+
decide_bid: 'Deciding to bid (a business decision)',
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
/** Hosts the system may READ from. Nothing is ever written to them. */
|
|
24
|
+
export const READ_ONLY_HOSTS = Object.freeze([
|
|
25
|
+
'sam.gov',
|
|
26
|
+
'api.sam.gov',
|
|
27
|
+
'falextracts.s3.amazonaws.com',
|
|
28
|
+
'iae-fbo-attachments.s3.amazonaws.com',
|
|
29
|
+
'camisvr.co.la.ca.us',
|
|
30
|
+
'mcp.profullstack.com',
|
|
31
|
+
'pit.world',
|
|
32
|
+
]);
|
|
33
|
+
|
|
34
|
+
/** Proposal states. `submitted` is only ever set by a person marking a card done. */
|
|
35
|
+
export const PROPOSAL_STATES = ['draft', 'approved', 'submitted_by_human', 'declined'];
|
|
36
|
+
|
|
37
|
+
/** Every drafted proposal carries this banner until a person approves it. */
|
|
38
|
+
export const DRAFT_BANNER =
|
|
39
|
+
'DRAFT prepared by software for human review. Not submitted. Nothing here is a commitment, price or certification until a person at the bidder reviews, completes and submits it themselves.';
|
|
40
|
+
|
|
41
|
+
/** Refuse anything that looks like an attempt to automate a human-only step. */
|
|
42
|
+
export function assertHumanOnly(action) {
|
|
43
|
+
if (Object.hasOwn(HUMAN_ONLY, action)) {
|
|
44
|
+
const e = new Error(`${HUMAN_ONLY[action]} is a human step. gov-contracts queues it as an intervention card and never does it itself.`);
|
|
45
|
+
e.code = 'human_only';
|
|
46
|
+
throw e;
|
|
47
|
+
}
|
|
48
|
+
}
|
package/src/server.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { serve } from '@hono/node-server';
|
|
2
|
+
import { app } from './app.js';
|
|
3
|
+
import { startDaemon, getDaemon } from './pipeline.js';
|
|
4
|
+
|
|
5
|
+
const port = Number(process.env.PORT || 8080);
|
|
6
|
+
const hostname = process.env.HOST || '0.0.0.0';
|
|
7
|
+
|
|
8
|
+
serve({ fetch: app.fetch, port, hostname }, () => {
|
|
9
|
+
console.log(`gov-contracts listening on http://${hostname}:${port}`);
|
|
10
|
+
startDaemon();
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
const stop = () => Promise.resolve(getDaemon()?.stop()).finally(() => process.exit(0));
|
|
14
|
+
process.on('SIGTERM', stop);
|
|
15
|
+
process.on('SIGINT', stop);
|
package/src/service.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** Shared by the HTTP API, pages and MCP. */
|
|
2
|
+
import { draftOne } from './pipeline.js';
|
|
3
|
+
import { getSolicitation, setSolicitation } from './store.js';
|
|
4
|
+
|
|
5
|
+
/** What anyone may see. Fit scores and drafts are the bidder's own business. */
|
|
6
|
+
export function publicSolicitation(s, isOperator = false) {
|
|
7
|
+
if (!s) return null;
|
|
8
|
+
const { fit, fit_score, prefilter, error, ...rest } = s;
|
|
9
|
+
return isOperator ? { ...rest, prefilter, fit_score, fit, error } : rest;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const drafting = new Set();
|
|
13
|
+
|
|
14
|
+
/** Draft in the background (a model can take minutes); the cards appear when it finishes. */
|
|
15
|
+
export function startDraft(id) {
|
|
16
|
+
const s = getSolicitation(id);
|
|
17
|
+
if (!s) throw new Error('not found');
|
|
18
|
+
if (drafting.has(id)) return { id, status: 'already drafting' };
|
|
19
|
+
drafting.add(id);
|
|
20
|
+
setSolicitation(id, { status: s.status === 'skipped' ? 'read' : s.status });
|
|
21
|
+
draftOne(getSolicitation(id))
|
|
22
|
+
.catch((e) => console.error('draft failed', id, String(e?.message || e).slice(0, 200)))
|
|
23
|
+
.finally(() => drafting.delete(id));
|
|
24
|
+
return { id, status: 'drafting', note: 'The proposal and its queue cards appear when the draft finishes (usually 1-3 minutes).' };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export const isDrafting = (id) => drafting.has(id);
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bid digests forwarded by email (MyGovWatch weekly digests and the like).
|
|
3
|
+
* Optional source: an operator POSTs the plain-text body (or the CLI reads a
|
|
4
|
+
* file / stdin) and every listed solicitation is queued. Tracking links in the
|
|
5
|
+
* digest are never stored or opened; the buyer's own page is found by a person.
|
|
6
|
+
*
|
|
7
|
+
* MyGovWatch's layout is parsed deterministically. Any other digest goes to a
|
|
8
|
+
* model with a fixed JSON shape (when one is configured).
|
|
9
|
+
*/
|
|
10
|
+
import { createHash } from 'node:crypto';
|
|
11
|
+
import { z } from 'zod';
|
|
12
|
+
import { prefilter } from '../fit.js';
|
|
13
|
+
|
|
14
|
+
export const ID = 'email.digest';
|
|
15
|
+
|
|
16
|
+
const clean = (s) => String(s || '').replace(/\s+/g, ' ').replace(/^[*\s]+|[*\s]+$/g, '').trim();
|
|
17
|
+
const hash = (s) => createHash('sha256').update(s).digest('hex').slice(0, 20);
|
|
18
|
+
|
|
19
|
+
/** "12/09/2026" -> "2026-12-09" */
|
|
20
|
+
const usDate = (v) => {
|
|
21
|
+
const m = /(\d{1,2})\/(\d{1,2})\/(\d{4})/.exec(String(v || ''));
|
|
22
|
+
return m ? `${m[3]}-${m[1].padStart(2, '0')}-${m[2].padStart(2, '0')}` : null;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** Federal / state / county / city from a buyer line like "Yolo County, CA" or "State of California". */
|
|
26
|
+
export function levelOf(buyer) {
|
|
27
|
+
const b = String(buyer).toLowerCase();
|
|
28
|
+
if (/\b(state of|department of|california state|caltrans|calpers)\b/.test(b) || /^state\b/.test(b)) return 'state';
|
|
29
|
+
if (/\bcounty\b/.test(b)) return 'county';
|
|
30
|
+
if (/\b(federal|u\.s\.|united states|dept of|army|navy|air force)\b/.test(b)) return 'federal';
|
|
31
|
+
return 'city';
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const regionOf = (buyer) => (/\b(CA|California)\b/.test(buyer) ? 'CA' : null);
|
|
35
|
+
|
|
36
|
+
function solicitation(buyer, title, due, extra = {}) {
|
|
37
|
+
const t = clean(title).replace(/^\W+/, '');
|
|
38
|
+
const b = clean(buyer);
|
|
39
|
+
const s = {
|
|
40
|
+
source: 'digest',
|
|
41
|
+
ext_id: hash(`${b.toLowerCase()}|${t.toLowerCase()}`),
|
|
42
|
+
number: /\b(RF[PQIB]|IFB|ITB)[\s-]*[A-Z0-9][\w.-]*\d[\w.-]*/i.exec(t)?.[0] || null,
|
|
43
|
+
title: t,
|
|
44
|
+
agency: b,
|
|
45
|
+
level: levelOf(b),
|
|
46
|
+
region: regionOf(b),
|
|
47
|
+
url: null,
|
|
48
|
+
notice_type: /\bRFI\b/i.test(t) ? 'Request for Information' : /\bRFQ\b/i.test(t) ? 'Request for Quote' : /\bRFP\b/i.test(t) ? 'Request for Proposal' : null,
|
|
49
|
+
posted_at: null,
|
|
50
|
+
due_at: due,
|
|
51
|
+
description: `Listed in a forwarded bid digest${extra.from ? ` (${extra.from})` : ''}. Find the solicitation on the buyer's own procurement page.`,
|
|
52
|
+
...extra.fields,
|
|
53
|
+
};
|
|
54
|
+
s.prefilter = prefilter(s);
|
|
55
|
+
return s;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* MyGovWatch: a buyer line wrapped in asterisks ("* Los Angeles County, CA *"),
|
|
60
|
+
* the title on the following line(s), then "* Due Date: *12/09/2026".
|
|
61
|
+
*/
|
|
62
|
+
export function parseMyGovWatch(text) {
|
|
63
|
+
const lines = String(text).replace(/\r/g, '').split('\n').map((l) => l.trim());
|
|
64
|
+
const out = [];
|
|
65
|
+
for (let i = 0; i < lines.length; i++) {
|
|
66
|
+
const buyer = /^\*\s*([^*]+?)\s*\*$/.exec(lines[i]);
|
|
67
|
+
if (!buyer || /due date|notified/i.test(buyer[1])) continue;
|
|
68
|
+
const titleLines = [];
|
|
69
|
+
let due = null;
|
|
70
|
+
let j = i + 1;
|
|
71
|
+
for (; j < lines.length && j < i + 12; j++) {
|
|
72
|
+
const l = lines[j];
|
|
73
|
+
if (!l) { if (titleLines.length) continue; else continue; }
|
|
74
|
+
const d = /due date:\s*\*?\s*(\d{1,2}\/\d{1,2}\/\d{4})/i.exec(l);
|
|
75
|
+
if (d) { due = usDate(d[1]); break; }
|
|
76
|
+
if (/^\*\s*[^*]+\*$/.test(l) || /^\[image|^<https?:|^https?:/i.test(l)) break;
|
|
77
|
+
titleLines.push(l);
|
|
78
|
+
}
|
|
79
|
+
if (titleLines.length && due) {
|
|
80
|
+
out.push(solicitation(buyer[1], titleLines.join(' '), due, { from: 'MyGovWatch' }));
|
|
81
|
+
i = j;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const DigestSchema = z.object({
|
|
88
|
+
solicitations: z.array(z.object({ buyer: z.string(), title: z.string(), due_date: z.string().nullable().default(null), number: z.string().nullable().default(null) })),
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
/** Parse a forwarded digest. Deterministic first; a model only for unknown layouts. */
|
|
92
|
+
export async function parseDigest(text, { ai } = {}) {
|
|
93
|
+
const body = String(text || '').replace(/https?:\/\/\S+/g, ''); // never keep tracking links
|
|
94
|
+
const mgw = parseMyGovWatch(body);
|
|
95
|
+
if (mgw.length) return { parser: 'mygovwatch', solicitations: mgw };
|
|
96
|
+
if (!ai) return { parser: 'none', solicitations: [] };
|
|
97
|
+
const r = await ai.generateObject({
|
|
98
|
+
system: 'Extract every government solicitation (RFP, RFQ, RFI, bid) listed in this email. Buyer = the agency. due_date as YYYY-MM-DD or null. JSON only.',
|
|
99
|
+
user: body.slice(0, 12000),
|
|
100
|
+
schema: DigestSchema,
|
|
101
|
+
jsonSchema: z.toJSONSchema(DigestSchema),
|
|
102
|
+
name: 'digest',
|
|
103
|
+
feature: 'gov-contracts:digest',
|
|
104
|
+
maxTokens: 2500,
|
|
105
|
+
});
|
|
106
|
+
return {
|
|
107
|
+
parser: 'ai',
|
|
108
|
+
solicitations: r.object.solicitations
|
|
109
|
+
.filter((x) => x.title && x.buyer)
|
|
110
|
+
.map((x) => solicitation(x.buyer, x.title, /^\d{4}-\d{2}-\d{2}$/.test(x.due_date || '') ? x.due_date : usDate(x.due_date), { fields: x.number ? { number: x.number } : {} })),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export async function readDocs(sol) {
|
|
115
|
+
return {
|
|
116
|
+
docs: [{ kind: 'notice', name: 'Digest listing', text: `${sol.title}\nBuyer: ${sol.agency}\nDue: ${sol.due_at}\n${sol.description || ''}` }],
|
|
117
|
+
fields: {},
|
|
118
|
+
};
|
|
119
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sources. WHERE to look is Datamart's contracts registry (the Profullstack
|
|
3
|
+
* connector's `contracts_sources` tool, served at mcp.profullstack.com/contracts);
|
|
4
|
+
* this package adds HOW to read the ones that have a public feed. A registry
|
|
5
|
+
* entry without an adapter stays a link for a person.
|
|
6
|
+
*/
|
|
7
|
+
import { http } from '../http.js';
|
|
8
|
+
import * as digest from './digest.js';
|
|
9
|
+
import * as lacounty from './lacounty.js';
|
|
10
|
+
import * as sam from './sam.js';
|
|
11
|
+
|
|
12
|
+
export const REGISTRY_URL = process.env.CONTRACTS_REGISTRY_URL || 'https://mcp.profullstack.com/contracts';
|
|
13
|
+
|
|
14
|
+
/** Adapters by short source name. `provider` is the Datamart provider id. */
|
|
15
|
+
export const ADAPTERS = {
|
|
16
|
+
sam: { provider: sam.ID, level: 'federal', name: 'SAM.gov contract opportunities', every: '6h', ingest: sam.ingest, readDocs: sam.readDocs, scheduled: true },
|
|
17
|
+
lacounty: { provider: lacounty.ID, level: 'county', name: 'County of Los Angeles open solicitations (LACoBids)', every: '6h', ingest: lacounty.ingest, readDocs: lacounty.readDocs, scheduled: true, officialUrl: lacounty.LIST_URL },
|
|
18
|
+
digest: { provider: digest.ID, level: 'any', name: 'Forwarded bid digests (email)', ingest: null, readDocs: digest.readDocs, scheduled: false },
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export const adapterFor = (source) => ADAPTERS[source] || null;
|
|
22
|
+
|
|
23
|
+
let cache = { at: 0, providers: null };
|
|
24
|
+
|
|
25
|
+
/** Datamart's registry, cached for an hour; the last good copy on error. */
|
|
26
|
+
export async function registry({ fetcher = http() } = {}) {
|
|
27
|
+
if (process.env.GOV_OFFLINE === '1') return cache.providers || [];
|
|
28
|
+
if (cache.providers && Date.now() - cache.at < 3600_000) return cache.providers;
|
|
29
|
+
try {
|
|
30
|
+
const doc = await fetcher.json(REGISTRY_URL);
|
|
31
|
+
cache = { at: Date.now(), providers: Array.isArray(doc?.providers) ? doc.providers : [] };
|
|
32
|
+
} catch {
|
|
33
|
+
cache.at = Date.now() - 3000_000; // retry in ~10 min
|
|
34
|
+
}
|
|
35
|
+
return cache.providers || [];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Registry entries joined with what gov-contracts can read today. */
|
|
39
|
+
export async function listSources(opts) {
|
|
40
|
+
const providers = await registry(opts);
|
|
41
|
+
const byProvider = Object.fromEntries(Object.entries(ADAPTERS).map(([key, a]) => [a.provider, { ...a, key }]));
|
|
42
|
+
const rows = providers.map((p) => ({
|
|
43
|
+
id: p.id,
|
|
44
|
+
name: p.name,
|
|
45
|
+
organization: p.organization,
|
|
46
|
+
level: p.jurisdiction?.level ?? null,
|
|
47
|
+
official_url: p.official_url ?? null,
|
|
48
|
+
datamart_state: p.headline_state ?? null,
|
|
49
|
+
gov_contracts: byProvider[p.id] ? { source: byProvider[p.id].key, ingest: byProvider[p.id].scheduled ? `every ${byProvider[p.id].every}` : 'on demand' } : null,
|
|
50
|
+
}));
|
|
51
|
+
for (const [name, a] of Object.entries(ADAPTERS)) {
|
|
52
|
+
if (!rows.some((r) => r.id === a.provider)) {
|
|
53
|
+
rows.push({ id: a.provider, name: a.name, organization: null, level: a.level, official_url: a.officialUrl ?? null, datamart_state: null, gov_contracts: { source: name, ingest: a.scheduled ? `every ${a.every}` : 'on demand' } });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return rows;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export { digest, lacounty, sam };
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* County of Los Angeles open solicitations (LACoBids). The county publishes a
|
|
3
|
+
* CSV of every open solicitation, linked from its public bid list; one GET per
|
|
4
|
+
* run, every six hours. Bid documents sit behind the county's bid detail page
|
|
5
|
+
* (a session form), so they stay a link for a person to open.
|
|
6
|
+
*/
|
|
7
|
+
import { http } from '../http.js';
|
|
8
|
+
import { prefilter } from '../fit.js';
|
|
9
|
+
|
|
10
|
+
export const ID = 'us.ca.lacounty.bids';
|
|
11
|
+
export const CSV_URL = 'https://camisvr.co.la.ca.us/LACoBids/Download/Rpt_Listing/OpenBidList.csv';
|
|
12
|
+
export const LIST_URL = 'https://camisvr.co.la.ca.us/LACoBids/BidLookUp/OpenBidList';
|
|
13
|
+
|
|
14
|
+
/** RFC 4180 CSV (quoted fields, doubled quotes, newlines inside quotes). */
|
|
15
|
+
export function parseCsv(text) {
|
|
16
|
+
const rows = [];
|
|
17
|
+
let row = [];
|
|
18
|
+
let field = '';
|
|
19
|
+
let quoted = false;
|
|
20
|
+
const s = String(text).replace(/^/, '');
|
|
21
|
+
for (let i = 0; i < s.length; i++) {
|
|
22
|
+
const ch = s[i];
|
|
23
|
+
if (quoted) {
|
|
24
|
+
if (ch === '"') {
|
|
25
|
+
if (s[i + 1] === '"') { field += '"'; i++; } else quoted = false;
|
|
26
|
+
} else field += ch;
|
|
27
|
+
} else if (ch === '"') quoted = true;
|
|
28
|
+
else if (ch === ',') { row.push(field); field = ''; }
|
|
29
|
+
else if (ch === '\n' || ch === '\r') {
|
|
30
|
+
if (ch === '\r' && s[i + 1] === '\n') i++;
|
|
31
|
+
row.push(field); field = '';
|
|
32
|
+
if (row.some((c) => c !== '')) rows.push(row);
|
|
33
|
+
row = [];
|
|
34
|
+
} else field += ch;
|
|
35
|
+
}
|
|
36
|
+
if (field !== '' || row.length) { row.push(field); if (row.some((c) => c !== '')) rows.push(row); }
|
|
37
|
+
return rows;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** "12/09/2026 12:00PM" -> "2026-12-09". */
|
|
41
|
+
export function usDate(v) {
|
|
42
|
+
const m = /(\d{1,2})\/(\d{1,2})\/(\d{4})/.exec(String(v || ''));
|
|
43
|
+
return m ? `${m[3]}-${m[1].padStart(2, '0')}-${m[2].padStart(2, '0')}` : null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function fromCsv(text) {
|
|
47
|
+
const rows = parseCsv(text);
|
|
48
|
+
const head = rows.shift() || [];
|
|
49
|
+
const col = (name) => head.findIndex((h) => h.trim().toLowerCase() === name);
|
|
50
|
+
const c = {
|
|
51
|
+
url: col('bid url'), number: col('bid number'), title: col('bid title'), type: col('bid type'), dept: col('department'),
|
|
52
|
+
desc: col('bid description'), comm: col('commodity description'), open: col('open date'), close: col('closing date'),
|
|
53
|
+
cname: col('contact name'), cphone: col('contact phone'), cemail: col('contact email'),
|
|
54
|
+
};
|
|
55
|
+
if (c.number < 0 || c.title < 0) throw new Error('LA County CSV columns changed');
|
|
56
|
+
const today = new Date().toISOString().slice(0, 10);
|
|
57
|
+
const out = [];
|
|
58
|
+
for (const r of rows) {
|
|
59
|
+
const get = (k) => (c[k] >= 0 ? String(r[c[k]] ?? '').trim() : '');
|
|
60
|
+
const url = get('url');
|
|
61
|
+
const ext = /biddocidi=(\d+)/i.exec(url)?.[1] || get('number');
|
|
62
|
+
const due = usDate(get('close'));
|
|
63
|
+
if (!ext || !get('title') || (due && due < today)) continue;
|
|
64
|
+
const commodity = get('comm');
|
|
65
|
+
const s = {
|
|
66
|
+
source: 'lacounty',
|
|
67
|
+
ext_id: ext,
|
|
68
|
+
number: get('number') || null,
|
|
69
|
+
title: get('title'),
|
|
70
|
+
agency: `County of Los Angeles${get('dept') ? ' / ' + get('dept') : ''}`,
|
|
71
|
+
level: 'county',
|
|
72
|
+
region: 'CA',
|
|
73
|
+
url: url || LIST_URL,
|
|
74
|
+
notice_type: get('type') || null,
|
|
75
|
+
posted_at: usDate(get('open')),
|
|
76
|
+
due_at: due,
|
|
77
|
+
description: [get('desc'), commodity && `Commodity: ${commodity}`, get('close') && `Closes: ${get('close')} (Pacific)`].filter(Boolean).join('\n'),
|
|
78
|
+
contacts: get('cname') || get('cemail') ? [{ name: get('cname'), email: get('cemail'), phone: get('cphone'), role: 'buyer' }] : [],
|
|
79
|
+
};
|
|
80
|
+
s.prefilter = prefilter(s);
|
|
81
|
+
out.push(s);
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export async function ingest({ fetcher = http() } = {}) {
|
|
87
|
+
const r = await fetcher.text(CSV_URL);
|
|
88
|
+
return fromCsv(r.text);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The CSV already carries the description and contact; the documents need a person on the county site. */
|
|
92
|
+
export async function readDocs(sol) {
|
|
93
|
+
return {
|
|
94
|
+
docs: [
|
|
95
|
+
{ kind: 'notice', name: 'County listing', url: sol.url, text: sol.description || '' },
|
|
96
|
+
{ kind: 'link', name: 'Bid documents (LACoBids bid page: attachments open there)', url: sol.url },
|
|
97
|
+
],
|
|
98
|
+
fields: {},
|
|
99
|
+
};
|
|
100
|
+
}
|