loopengine 0.5.6 → 0.5.8

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.
@@ -14,3 +14,12 @@ export declare function decidePath(pendingId: string, kind: DecisionKind): strin
14
14
  * no base URL to build them against. */
15
15
  export type DecideLinkMaker = (pendingId: string, kind: DecisionKind) => string | undefined;
16
16
  export declare function decideLinkMaker(baseUrl: string | undefined): DecideLinkMaker;
17
+ export declare function createFeedbackToken(agent: string, runId: string, source: string, nowMs?: number): string;
18
+ /** The run, agent and source a feedback token names, or null for a
19
+ * malformed, tampered or expired one. */
20
+ export declare function verifyFeedbackToken(token: string, nowMs?: number): {
21
+ runId: string;
22
+ agent: string;
23
+ source: string;
24
+ } | null;
25
+ export declare function feedbackPath(agent: string, runId: string, source: string): string;
@@ -74,3 +74,41 @@ export function decidePath(pendingId, kind) {
74
74
  export function decideLinkMaker(baseUrl) {
75
75
  return (pendingId, kind) => (baseUrl ? baseUrl.replace(/\/+$/, '') + decidePath(pendingId, kind) : undefined);
76
76
  }
77
+ // ---- Feedback links ----
78
+ // The same kind of signed link, for feedback on a finished run: who has it
79
+ // can say whether the result was good, add a note and give the text they
80
+ // actually used, without signing in. It names the run, its agent and
81
+ // where the link was sent (slack, email, webhook...), recorded as the
82
+ // feedback's source. A run doesn't go away the way a decision does, so a
83
+ // link can be used again; each use replaces the run's feedback (every
84
+ // one is kept in the audit log). Valid 30 days.
85
+ const FEEDBACK_LINK_TTL_MS = 30 * 24 * 3_600_000;
86
+ export function createFeedbackToken(agent, runId, source, nowMs = Date.now()) {
87
+ const body = Buffer.from(JSON.stringify({ f: runId, a: agent, s: source, exp: nowMs + FEEDBACK_LINK_TTL_MS })).toString('base64url');
88
+ return `${body}.${sign(body)}`;
89
+ }
90
+ /** The run, agent and source a feedback token names, or null for a
91
+ * malformed, tampered or expired one. */
92
+ export function verifyFeedbackToken(token, nowMs = Date.now()) {
93
+ const [body, signature] = token.split('.');
94
+ if (!body || !signature)
95
+ return null;
96
+ const expected = Buffer.from(sign(body));
97
+ const actual = Buffer.from(signature);
98
+ if (expected.length !== actual.length || !timingSafeEqual(expected, actual))
99
+ return null;
100
+ try {
101
+ const payload = JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
102
+ if (typeof payload.f !== 'string' || typeof payload.a !== 'string' || typeof payload.s !== 'string' || typeof payload.exp !== 'number')
103
+ return null;
104
+ if (nowMs > payload.exp)
105
+ return null;
106
+ return { runId: payload.f, agent: payload.a, source: payload.s };
107
+ }
108
+ catch {
109
+ return null;
110
+ }
111
+ }
112
+ export function feedbackPath(agent, runId, source) {
113
+ return `/feedback/${createFeedbackToken(agent, runId, source)}`;
114
+ }
@@ -106,12 +106,22 @@ export interface RunDecision {
106
106
  /** Why it was denied, when the person said. */
107
107
  reason?: string;
108
108
  }
109
+ /** Where feedback came from: the console's Inbox or a run's page, a
110
+ * signed link (from a messaging app, an email or a callback), or an app
111
+ * through the API. */
112
+ export type FeedbackSource = 'inbox' | 'console' | 'slack' | 'telegram' | 'lark' | 'email' | 'webhook' | 'link' | 'api';
113
+ export declare const FEEDBACK_SOURCES: FeedbackSource[];
109
114
  export interface RunFeedback {
110
115
  verdict?: 'good' | 'bad';
111
116
  /** How far the text actually used is from the result. */
112
117
  edit?: 'none' | 'light' | 'heavy';
113
118
  final?: string;
114
119
  note?: string;
120
+ /** Where it came from. */
121
+ source?: FeedbackSource;
122
+ /** Who gave it: the person signed in, a name given with a link, or
123
+ * what an app says of its user. */
124
+ by?: string;
115
125
  at: string;
116
126
  }
117
127
  export type RunOutcome = {
@@ -28,6 +28,7 @@ import { MAX_OUTPUT_RETRIES, checkOutput, outputRetryMessage } from './output-sc
28
28
  export function workflowVersionOf(run) {
29
29
  return run.versions?.workflow ?? run.versions?.brief;
30
30
  }
31
+ export const FEEDBACK_SOURCES = ['inbox', 'console', 'slack', 'telegram', 'lark', 'email', 'webhook', 'link', 'api'];
31
32
  const MAX_FINISHED_PER_AGENT = 500;
32
33
  const SESSION_PREFIX = 'run-';
33
34
  /** A scheduled task's sessions (core/scheduler.ts). */
@@ -509,7 +510,8 @@ export class WorkflowRunner {
509
510
  /** Records feedback given on a run's result in the audit events (the
510
511
  * run itself carries the latest). */
511
512
  recordFeedback(run, feedback, by) {
512
- const { at, ...data } = feedback;
513
+ const { at, by: _by, ...data } = feedback;
514
+ by = by ?? feedback.by;
513
515
  recordEvent({ at, agent: run.agent, workflow_id: run.workflow_id, run_id: run.run_id, kind: 'feedback', ...(by ? { by } : {}), data });
514
516
  }
515
517
  /** Records a question answered in a run's session. */
package/dist/index.d.ts CHANGED
@@ -26,7 +26,7 @@ export { decideReply, proposeEdit, describeChange, type ReplyDecision, type Deci
26
26
  export { recordThread, findThread, findThreadByPending, recordJobThread, findJobThread, findJobThreadBySession, type ThreadLink, type JobThread } from '#core/messaging/threads.js';
27
27
  export type { InboundMessage, MessagingConnector, ThreadMessage, MessagingChoice, MessagingAction } from '#core/messaging/connector.js';
28
28
  export { parseSlackEvent, createSlackConnector, verifySlackRequest, parseSlackInteraction, openSlackAnswerModal, replyInSlack, replyPrivatelyInSlack, slackOutcomeText, listSlackChannels, listSlackChannelMembers, slackAppManifest, slackBotIdentity, toSlackMrkdwn, slackArgs, slackEscape, type SlackEvent, type SlackInteraction, type SlackChannel } from '#core/messaging/connectors/slack/index.js';
29
- export { createDecisionToken, verifyDecisionToken, decidePath, decideLinkMaker, decisionLinkTtlMs, type DecisionKind } from '#core/approval-links.js';
29
+ export { createDecisionToken, verifyDecisionToken, decidePath, decideLinkMaker, decisionLinkTtlMs, createFeedbackToken, verifyFeedbackToken, feedbackPath, type DecisionKind } from '#core/approval-links.js';
30
30
  export { renderDecidePage, renderDecideGonePage, renderDecideInvalidPage, type DecidePageItem } from './web/decide-page.js';
31
31
  export { sendTestWebhook, publicBaseUrl } from '#core/http-notify-triggers/webhook.js';
32
32
  export { describeAgentNotifier, saveAgentNotifier, removeAgentNotifier, setAgentPrimaryNotifier, testAgentNotifier, listAgentPending, slackCredentialsFor, slackConversationsOn, slackClickAllowed, agentApprovers, setAgentApprovers, listAgentSlackMembers, listAgentSlackChannels, announceToNotifier, announceToChat, hasChatApp, hasNotifier, type DefaultWebhook } from './web/notifier-admin.js';
@@ -99,9 +99,9 @@ export { WORKFLOW_EXAMPLE_MESSAGES, type WorkflowExampleMessage } from './core/s
99
99
  export { createTrigger, updateTrigger, rotateTrigger, listTriggers, findTriggerByToken, publicTrigger, checkTriggerSettings, verifySenderSignature, parsePayload, valueAt, deliveryId, passesFilter, paramsFromPayload, checkRunDelivery, fillChatNotice, resultToChat, recordDelivery as recordTriggerDelivery, FileTriggerStore, getTriggerStore, setTriggerStore, TriggerError, type WorkflowTrigger, type PublicTrigger, type TriggerSettings, type TriggerVerify, type TriggerFilter, type TriggerSender, type SignatureAlgorithm, type TriggerDelivery, type TriggerOutcome, type TriggerStore } from './core/workflow-triggers.js';
100
100
  export { checkCallbackUrl, callbackSecret, signCallback, deliverCallback, runCallbackPayload, isPrivateAddress, CallbackUrlError, type CallbackDelivery, type CallbackPending, type RunCallbackEvent } from './core/run-callbacks.js';
101
101
  export { auditDb, openAuditDb, setAuditDb, recordEvent, runEvents, listEvents, eventPeople, eventHash, verifyEventChain, latestEventHash, type ChainCheck, readMeta, writeMeta, type EventFilter, noteVersion, listVersions, getVersion, workflowContent, workflowFromContent, type WorkflowSnapshot, recordTraceSpan, recordTracePrompt, listTraceSpans, pruneTraces, type TraceSpan, retentionDays, type Version, type VersionKind, type AuditEvent, type AuditEventKind } from './core/audit-store.js';
102
- export { WorkflowRunner, FileRunStore, SqliteRunStore, getRunStore, setRunStore, listRuns, runsSince, searchRuns, type RunSearch, getRun, isUnderWay, RunError, type WorkflowRun, type WorkflowRunStatus, type RunVersions, workflowVersionOf, type RunDecision, type RunStore, type ExecuteRun, type RunOutcome, type StartRunInput } from './core/workflow-runs.js';
102
+ export { WorkflowRunner, FileRunStore, SqliteRunStore, getRunStore, setRunStore, listRuns, runsSince, searchRuns, type RunSearch, getRun, isUnderWay, RunError, type WorkflowRun, type WorkflowRunStatus, type RunVersions, workflowVersionOf, FEEDBACK_SOURCES, type FeedbackSource, type RunFeedback, type RunDecision, type RunStore, type ExecuteRun, type RunOutcome, type StartRunInput } from './core/workflow-runs.js';
103
103
  export { readWorkflows, readWorkflow, setWorkflowFields, setWorkflowDelivery, clearWorkflowFields, validateParams, workflowRunMessage, workflowPreviewMessage, migrateWorkflowsFile, WorkflowParamsError, readWorkspacePolicies, writeWorkspacePolicies, type Workflow, type WorkflowFields, type WorkflowParameter, type WorkflowModel, type WorkflowDelivery, type RunMessageExtras } from './core/workflows.js';
104
- export { EvidenceError, evalCandidates, suggestedCriteria, type EvalCandidate, workflowScores, runFeedbackFrom, readEvals, addEvalCase, updateEvalCase, removeEvalCase, setEvalCriteria, effectiveCriteria, codeCheck, judgeCriteria, checkCase, roundSummary, draftCriteria, startEvalRound, EVAL_CRITERIA_PROMPT, DRAFT_CRITERIA_PROMPT, REFERENCE_CRITERION, type WorkflowScores, type EvalCase, type EvalCaseResult, type EvalCheck, type EvalCriterion, type CriterionKind, type EvalRound, type WorkflowEvals, type EvalRunDeps, type StandIn } from './web/workflow-evidence.js';
104
+ export { EvidenceError, evalCandidates, suggestedCriteria, type EvalCandidate, workflowScores, runFeedbackFrom, feedbackSourceOf, readEvals, addEvalCase, updateEvalCase, removeEvalCase, setEvalCriteria, effectiveCriteria, codeCheck, judgeCriteria, checkCase, roundSummary, draftCriteria, startEvalRound, EVAL_CRITERIA_PROMPT, DRAFT_CRITERIA_PROMPT, REFERENCE_CRITERION, type WorkflowScores, type EvalCase, type EvalCaseResult, type EvalCheck, type EvalCriterion, type CriterionKind, type EvalRound, type WorkflowEvals, type EvalRunDeps, type StandIn } from './web/workflow-evidence.js';
105
105
  export { globalConfigPageHtml } from './web/global-config-page.js';
106
106
  export { playgroundHtml } from './web/playground.js';
107
107
  export { readSkill, writeSkill, deleteSkill, SkillInvalidIdError, SkillNotFoundError } from './web/skills-admin.js';
@@ -148,6 +148,8 @@ export { workflowsOverviewPageHtml } from './web/workflows-overview-page.js';
148
148
  export { homeOverview, workflowsOverview, startsOf, type HomeOverview, type WorkflowsOverview, type WorkflowOverviewRow } from './web/workflows-overview.js';
149
149
  export { homePageHtml } from './web/home-page.js';
150
150
  export { schedulesPageHtml } from './web/schedules-page.js';
151
+ export { feedbackSummary, suggestImprovements, isActionable, IMPROVE_PROMPT, type FeedbackItem, type FeedbackSummary, type ImproveSuggestion } from './web/workflow-feedback.js';
152
+ export { feedbackPageHtml } from './web/feedback-page.js';
151
153
  export { listInbox, getInboxCase, timelineOf, RECENT_DAYS, INBOX_VIEWS, type InboxView, type InboxDeps, type InboxItem, type InboxCase, type InboxPending, type InboxStep, type InboxState, type InboxArchived } from './web/inbox-admin.js';
152
154
  export { readArchived, setArchived } from './web/inbox-archive.js';
153
155
  export { startTurnTrace, type TurnTrace } from './core/trace.js';
package/dist/index.js CHANGED
@@ -27,7 +27,7 @@ export { formatArgs, formatChange, labelFor } from '#core/messaging/format-args.
27
27
  export { decideReply, proposeEdit, describeChange } from '#core/messaging/decide.js';
28
28
  export { recordThread, findThread, findThreadByPending, recordJobThread, findJobThread, findJobThreadBySession } from '#core/messaging/threads.js';
29
29
  export { parseSlackEvent, createSlackConnector, verifySlackRequest, parseSlackInteraction, openSlackAnswerModal, replyInSlack, replyPrivatelyInSlack, slackOutcomeText, listSlackChannels, listSlackChannelMembers, slackAppManifest, slackBotIdentity, toSlackMrkdwn, slackArgs, slackEscape } from '#core/messaging/connectors/slack/index.js';
30
- export { createDecisionToken, verifyDecisionToken, decidePath, decideLinkMaker, decisionLinkTtlMs } from '#core/approval-links.js';
30
+ export { createDecisionToken, verifyDecisionToken, decidePath, decideLinkMaker, decisionLinkTtlMs, createFeedbackToken, verifyFeedbackToken, feedbackPath } from '#core/approval-links.js';
31
31
  export { renderDecidePage, renderDecideGonePage, renderDecideInvalidPage } from './web/decide-page.js';
32
32
  export { sendTestWebhook, publicBaseUrl } from '#core/http-notify-triggers/webhook.js';
33
33
  export { describeAgentNotifier, saveAgentNotifier, removeAgentNotifier, setAgentPrimaryNotifier, testAgentNotifier, listAgentPending, slackCredentialsFor, slackConversationsOn, slackClickAllowed, agentApprovers, setAgentApprovers, listAgentSlackMembers, listAgentSlackChannels, announceToNotifier, announceToChat, hasChatApp, hasNotifier } from './web/notifier-admin.js';
@@ -92,9 +92,9 @@ export { WORKFLOW_EXAMPLE_MESSAGES } from './core/system-agents/workflow-example
92
92
  export { createTrigger, updateTrigger, rotateTrigger, listTriggers, findTriggerByToken, publicTrigger, checkTriggerSettings, verifySenderSignature, parsePayload, valueAt, deliveryId, passesFilter, paramsFromPayload, checkRunDelivery, fillChatNotice, resultToChat, recordDelivery as recordTriggerDelivery, FileTriggerStore, getTriggerStore, setTriggerStore, TriggerError } from './core/workflow-triggers.js';
93
93
  export { checkCallbackUrl, callbackSecret, signCallback, deliverCallback, runCallbackPayload, isPrivateAddress, CallbackUrlError } from './core/run-callbacks.js';
94
94
  export { auditDb, openAuditDb, setAuditDb, recordEvent, runEvents, listEvents, eventPeople, eventHash, verifyEventChain, latestEventHash, readMeta, writeMeta, noteVersion, listVersions, getVersion, workflowContent, workflowFromContent, recordTraceSpan, recordTracePrompt, listTraceSpans, pruneTraces, retentionDays } from './core/audit-store.js';
95
- export { WorkflowRunner, FileRunStore, SqliteRunStore, getRunStore, setRunStore, listRuns, runsSince, searchRuns, getRun, isUnderWay, RunError, workflowVersionOf } from './core/workflow-runs.js';
95
+ export { WorkflowRunner, FileRunStore, SqliteRunStore, getRunStore, setRunStore, listRuns, runsSince, searchRuns, getRun, isUnderWay, RunError, workflowVersionOf, FEEDBACK_SOURCES } from './core/workflow-runs.js';
96
96
  export { readWorkflows, readWorkflow, setWorkflowFields, setWorkflowDelivery, clearWorkflowFields, validateParams, workflowRunMessage, workflowPreviewMessage, migrateWorkflowsFile, WorkflowParamsError, readWorkspacePolicies, writeWorkspacePolicies } from './core/workflows.js';
97
- export { EvidenceError, evalCandidates, suggestedCriteria, workflowScores, runFeedbackFrom, readEvals, addEvalCase, updateEvalCase, removeEvalCase, setEvalCriteria, effectiveCriteria, codeCheck, judgeCriteria, checkCase, roundSummary, draftCriteria, startEvalRound, EVAL_CRITERIA_PROMPT, DRAFT_CRITERIA_PROMPT, REFERENCE_CRITERION } from './web/workflow-evidence.js';
97
+ export { EvidenceError, evalCandidates, suggestedCriteria, workflowScores, runFeedbackFrom, feedbackSourceOf, readEvals, addEvalCase, updateEvalCase, removeEvalCase, setEvalCriteria, effectiveCriteria, codeCheck, judgeCriteria, checkCase, roundSummary, draftCriteria, startEvalRound, EVAL_CRITERIA_PROMPT, DRAFT_CRITERIA_PROMPT, REFERENCE_CRITERION } from './web/workflow-evidence.js';
98
98
  export { globalConfigPageHtml } from './web/global-config-page.js';
99
99
  export { playgroundHtml } from './web/playground.js';
100
100
  export { readSkill, writeSkill, deleteSkill, SkillInvalidIdError, SkillNotFoundError } from './web/skills-admin.js';
@@ -139,6 +139,8 @@ export { workflowsOverviewPageHtml } from './web/workflows-overview-page.js';
139
139
  export { homeOverview, workflowsOverview, startsOf } from './web/workflows-overview.js';
140
140
  export { homePageHtml } from './web/home-page.js';
141
141
  export { schedulesPageHtml } from './web/schedules-page.js';
142
+ export { feedbackSummary, suggestImprovements, isActionable, IMPROVE_PROMPT } from './web/workflow-feedback.js';
143
+ export { feedbackPageHtml } from './web/feedback-page.js';
142
144
  export { listInbox, getInboxCase, timelineOf, RECENT_DAYS, INBOX_VIEWS } from './web/inbox-admin.js';
143
145
  export { readArchived, setArchived } from './web/inbox-archive.js';
144
146
  export { startTurnTrace } from './core/trace.js';
@@ -254,6 +254,42 @@ export const agentsConfigPageHtml = `<!doctype html>
254
254
  .chg-note { color: var(--ink-muted); font-family: inherit; font-weight: 400; }
255
255
  .chg details summary { cursor: pointer; color: var(--accent-ink); font-family: var(--font-sans, inherit); font-size: 12px; margin-top: 2px; }
256
256
  .wf-page-meta-item[hidden] { display: none; }
257
+ .wf-fb { display: grid; gap: 26px; }
258
+ .wf-fb-stats { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; }
259
+ .wf-fb-stat { border: 1px solid var(--line); border-radius: 12px; padding: 12px 14px; display: grid; gap: 2px; }
260
+ .wf-fb-stat b { font-size: 22px; font-weight: 600; font-variant-numeric: tabular-nums; }
261
+ .wf-fb-stat span { font-size: 12.5px; color: var(--ink-muted); }
262
+ .wf-fb-stat.good b { color: var(--good); }
263
+ .wf-fb-stat.bad b { color: var(--bad); }
264
+ .wf-fb-sources { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; font-size: 12.5px; color: var(--ink-muted); }
265
+ .wf-fb-src { display: inline-flex; align-items: center; height: 24px; padding: 0 9px; border-radius: 7px; background: var(--surface); color: var(--ink); font-size: 12px; font-weight: 500; }
266
+ .wf-fb-improve { display: grid; gap: 12px; padding: 18px 20px; border-radius: 14px; border: 1px solid var(--line); background: linear-gradient(180deg, color-mix(in srgb, var(--accent-soft) 55%, var(--bg)), var(--bg)); }
267
+ .wf-fb-improve h3 { margin: 0; font-size: 17px; font-weight: 600; }
268
+ .wf-fb-improve p { margin: 0; font-size: 13.5px; color: var(--ink-muted); }
269
+ .wf-fb-improve-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; }
270
+ .wf-fb-sugg { display: grid; gap: 14px; }
271
+ .wf-fb-sugg[hidden] { display: none; }
272
+ .wf-fb-sugg h4 { margin: 0; font-size: 12px; color: var(--ink-faint); font-family: var(--font-mono); font-weight: 500; }
273
+ .wf-fb-changes { margin: 0; padding: 0; list-style: none; display: grid; gap: 8px; }
274
+ .wf-fb-changes li { display: grid; gap: 2px; padding: 10px 12px; border-radius: 10px; background: var(--bg); border: 1px solid var(--line); font-size: 13.5px; }
275
+ .wf-fb-changes li span { font-size: 12.5px; color: var(--ink-muted); }
276
+ .wf-fb-crits { display: grid; gap: 6px; }
277
+ .wf-fb-crits label { display: flex; gap: 8px; align-items: baseline; font-size: 13.5px; }
278
+ .wf-fb-open { margin: 0; padding-left: 18px; font-size: 13px; color: var(--warn); }
279
+ .wf-fb-list { margin: 0; padding: 0; list-style: none; display: grid; gap: 8px; }
280
+ .wf-fb-item { display: grid; gap: 6px; padding: 12px 14px; border: 1px solid var(--line); border-radius: 12px; font-size: 13.5px; }
281
+ .wf-fb-item-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; }
282
+ .wf-fb-item-head .hint { margin-left: auto; }
283
+ .wf-fb-note { margin: 0; overflow-wrap: anywhere; }
284
+ .wf-fb-item details summary { cursor: pointer; font-size: 12.5px; color: var(--ink-muted); }
285
+ .wf-fb-pair { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 10px; margin-top: 6px; }
286
+ .wf-fb-pair pre { margin: 0; max-height: 220px; overflow: auto; font-size: 12.5px; white-space: pre-wrap; }
287
+ .wf-fb-ways { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; }
288
+ .wf-fb-way { border: 1px solid var(--line); border-radius: 12px; padding: 12px 14px; display: grid; gap: 4px; align-content: start; font-size: 13px; }
289
+ .wf-fb-way b { font-size: 13.5px; }
290
+ .wf-fb-way span { color: var(--ink-muted); }
291
+ .wf-fb-way pre { margin: 4px 0 0; font-size: 11.5px; }
292
+ @media (max-width: 760px) { .wf-fb-stats, .wf-fb-ways, .wf-fb-pair { grid-template-columns: minmax(0, 1fr); } }
257
293
  .wf-sub-row { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; }
258
294
  .wf-act-main[hidden], .wf-trace[hidden] { display: none; }
259
295
  .wf-act-main > .wf-section + .wf-section { margin-top: 24px; padding-top: 20px; border-top: 1px solid var(--line); }
@@ -848,6 +884,41 @@ ${consoleSidebarHtml}
848
884
  </div>
849
885
  ${consoleShellScript}
850
886
  <script>
887
+ (function () {
888
+ // Every request this page's address already settles (the agent's
889
+ // config, messaging, pending decisions, schedules and workflows, and on
890
+ // a workflow's page its versions, health, eval candidates and runs)
891
+ // starts now, together, instead of each waiting for the one before it:
892
+ // on a hosted workspace every round trip costs hundreds of
893
+ // milliseconds, and the chain was four of them deep. The page's own
894
+ // request for one of these URLs then gets the response already on its
895
+ // way; each is used once, so a later reload of it fetches fresh.
896
+ var plainFetch = window.fetch.bind(window);
897
+ var early = {};
898
+ (function () {
899
+ var q = new URLSearchParams(location.search);
900
+ var agent = q.get('agent');
901
+ if (location.pathname !== '/agents/config' || !agent) return;
902
+ var base = '/agents/' + encodeURIComponent(agent);
903
+ var urls = [base + '/config', base + '/notifier', base + '/pending', base + '/schedules', base + '/workflows'];
904
+ var wf = q.get('tab') === 'workflows' && q.get('workflow');
905
+ if (wf) {
906
+ var b = base + '/workflows/' + encodeURIComponent(wf);
907
+ urls.push(b + '/versions', b + '/health', b + '/evals/candidates', b + '/runs');
908
+ }
909
+ urls.forEach(function (u) { early[u] = plainFetch(u, { headers: { accept: 'application/json' } }); });
910
+ })();
911
+ window.fetch = function (input, init) {
912
+ var url = typeof input === 'string' ? input : '';
913
+ var method = String((init && init.method) || 'GET').toUpperCase();
914
+ if (method === 'GET' && Object.prototype.hasOwnProperty.call(early, url)) {
915
+ var pending = early[url];
916
+ delete early[url];
917
+ return pending.catch(function () { return plainFetch(input, init); });
918
+ }
919
+ return plainFetch(input, init);
920
+ };
921
+ })();
851
922
  (function () {
852
923
  // The providers whose models take a reasoning effort (web/agent-file-admin.ts).
853
924
  var REASONING_PROVIDERS = ${JSON.stringify(REASONING_PROVIDERS)};
@@ -2093,7 +2164,7 @@ ${renderMarkdownScript}
2093
2164
  '</header>' +
2094
2165
  workflowDraftBannerHtml(w) +
2095
2166
  '<div class="wf-row-body wf-page-body">' +
2096
- '<div class="wf-tabs" role="tablist">' + tabBtn('activity', 'Activity') + tabBtn('brief', 'Prompt') + tabBtn('triggers', 'Triggers') + tabBtn('messages', 'Messaging') + tabBtn('evaluation', 'Evaluation') + tabBtn('contract', 'Contract') + tabBtn('versions', 'Versions') + '</div>' +
2167
+ '<div class="wf-tabs" role="tablist">' + tabBtn('activity', 'Activity') + tabBtn('feedback', 'Feedback') + tabBtn('brief', 'Prompt') + tabBtn('triggers', 'Triggers') + tabBtn('messages', 'Messaging') + tabBtn('evaluation', 'Evaluation') + tabBtn('contract', 'Contract') + tabBtn('versions', 'Versions') + '</div>' +
2097
2168
  panel('brief', workflowBriefHtml(w)) +
2098
2169
  panel('activity', workflowActivityHtml(w, runs, name)) +
2099
2170
  panel('evaluation', workflowEvaluationHtml(w)) +
@@ -2101,6 +2172,7 @@ ${renderMarkdownScript}
2101
2172
  panel('messages', workflowMessagesHtml(w, name)) +
2102
2173
  panel('contract', workflowContractHtml(w, name, params)) +
2103
2174
  panel('versions', workflowVersionsHtml()) +
2175
+ panel('feedback', workflowFeedbackHtml()) +
2104
2176
  '<div class="hint workflow-result"></div>' +
2105
2177
  '<div class="wf-row-foot"><span class="hint">ID <code>' + escapeHtml(w.id) + '</code>, used by the API, schedules and webhooks</span><button type="button" class="wf-remove workflow-forget" title="Its schedules and webhooks go; its instructions stay as a skill for Chat">Remove</button></div>' +
2106
2178
  '</div>' +
@@ -2119,9 +2191,10 @@ ${renderMarkdownScript}
2119
2191
  '<div class="wf-row-body"' + (open ? '' : ' hidden') + '>' +
2120
2192
  // What it does, in full, once it's open (the row shows just its name).
2121
2193
  (w.description && w.description !== w.title ? '<p class="wf-desc">' + escapeHtml(w.description) + '</p>' : '') +
2122
- '<div class="wf-tabs" role="tablist">' + tabBtn('activity', 'Activity') + tabBtn('brief', 'Prompt') + tabBtn('triggers', 'Triggers') + tabBtn('messages', 'Messaging') + tabBtn('evaluation', 'Evaluation') + tabBtn('contract', 'Contract') + tabBtn('versions', 'Versions') + '</div>' +
2194
+ '<div class="wf-tabs" role="tablist">' + tabBtn('activity', 'Activity') + tabBtn('feedback', 'Feedback') + tabBtn('brief', 'Prompt') + tabBtn('triggers', 'Triggers') + tabBtn('messages', 'Messaging') + tabBtn('evaluation', 'Evaluation') + tabBtn('contract', 'Contract') + tabBtn('versions', 'Versions') + '</div>' +
2123
2195
  panel('contract', workflowContractHtml(w, name, params)) +
2124
2196
  panel('versions', workflowVersionsHtml()) +
2197
+ panel('feedback', workflowFeedbackHtml()) +
2125
2198
  panel('triggers', workflowTriggersHtml(w, name, params)) +
2126
2199
  panel('messages', workflowMessagesHtml(w, name)) +
2127
2200
  panel('brief', workflowBriefHtml(w)) +
@@ -2890,6 +2963,139 @@ ${renderMarkdownScript}
2890
2963
  // View shows it in full, Compare what changed from the version before
2891
2964
  // it, and Restore makes it the workflow's draft, to review and publish
2892
2965
  // as the next version. Filled by loadWorkflowVersions.
2966
+ // The Feedback tab: what people said about this workflow's results,
2967
+ // from the Inbox, a messaging app's links, an email or another platform
2968
+ // (each piece says where), and Self-Improve: changes to its prompt and
2969
+ // new success criteria suggested from that feedback, to review and add
2970
+ // to its draft. Filled by loadWorkflowFeedback.
2971
+ function workflowFeedbackHtml() {
2972
+ return '<div class="wf-fb"><p class="hint" style="margin:0">Loading' + String.fromCharCode(8230) + '</p></div>';
2973
+ }
2974
+
2975
+ var FB_SOURCES = { inbox: 'Inbox', console: 'Console', slack: 'Slack', telegram: 'Telegram', lark: 'Lark', email: 'Email', webhook: 'Your app (callback)', link: 'Link', api: 'API', unknown: 'Earlier' };
2976
+
2977
+ function feedbackItemHtml(i, name) {
2978
+ var verdict = i.verdict === 'good' ? '<span class="le-pill good">Good</span>' : i.verdict === 'bad' ? '<span class="le-pill bad">Needs work</span>' : '';
2979
+ var edit = i.edit === 'heavy' ? '<span class="le-pill warn">Changed a lot</span>' : i.edit === 'light' ? '<span class="le-pill neutral">Changed a little</span>' : i.edit === 'none' ? '<span class="le-pill neutral">Used as is</span>' : '';
2980
+ var when = new Date(i.at).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
2981
+ return '<li class="wf-fb-item"><div class="wf-fb-item-head">' + verdict + edit +
2982
+ '<span class="wf-fb-src">' + escapeHtml(FB_SOURCES[i.source || 'unknown'] || i.source) + '</span>' +
2983
+ (i.by ? '<span class="hint" style="margin-left:0">' + escapeHtml(i.by) + '</span>' : '') +
2984
+ '<span class="hint">' + escapeHtml(when) + (i.workflowVersion ? DOT + 'v' + i.workflowVersion : '') + DOT + '<a href="#" class="wf-link wf-fb-trace" data-run="' + escapeHtml(i.runId) + '">trace</a></span></div>' +
2985
+ (i.note ? '<p class="wf-fb-note">' + String.fromCharCode(8220) + escapeHtml(i.note) + String.fromCharCode(8221) + '</p>' : '') +
2986
+ (i.inputs ? '<span class="hint">' + escapeHtml(i.inputs) + '</span>' : '') +
2987
+ '<details><summary>' + (i.final ? 'Its result, and what was used instead' : 'Its result') + '</summary><div class="wf-fb-pair"' + (i.final ? '' : ' style="grid-template-columns:minmax(0,1fr)"') + '>' +
2988
+ '<pre>' + escapeHtml(i.result || '(none)') + '</pre>' + (i.final ? '<pre>' + escapeHtml(i.final) + '</pre>' : '') + '</div></details></li>';
2989
+ }
2990
+
2991
+ function loadWorkflowFeedback(name, card, base) {
2992
+ var box = card.querySelector('.wf-fb');
2993
+ if (!box) return;
2994
+ var id = card.dataset.workflow;
2995
+ fetchJsonRetryOnce(base + '/feedback').then(function (r) {
2996
+ if (!r.ok) { box.innerHTML = '<p class="error">Could not load its feedback: ' + escapeHtml(r.body.error || 'unknown error') + '</p>'; return; }
2997
+ var f = r.body;
2998
+ var w = workflowsById[id] || {};
2999
+ var toChat = (w.delivery && w.delivery.result_to_chat) || (w.schedules || []).some(function (x) { return x.notify && x.status !== 'cancelled'; });
3000
+ var srcs = Object.keys(f.sources || {}).map(function (k) { return '<span class="wf-fb-src">' + escapeHtml(FB_SOURCES[k] || k) + ' ' + f.sources[k] + '</span>'; }).join('');
3001
+ var stat = function (cls, n, label) { return '<div class="wf-fb-stat ' + cls + '"><b>' + n + '</b><span>' + label + '</span></div>'; };
3002
+ box.innerHTML =
3003
+ '<section class="wf-section"><div class="wf-sub-row"><h4 class="wf-sub">What people said</h4><span class="hint">Last ' + f.days + ' days</span></div>' +
3004
+ '<div class="wf-fb-stats">' + stat('', f.total + '<span class="hint" style="font-size:13px;font-weight:400"> of ' + f.runs + '</span>', 'runs got feedback') + stat('good', f.good, 'Good') + stat('bad', f.bad, 'Needs work') + stat('', f.edited, 'Changed before use') + '</div>' +
3005
+ (srcs ? '<div class="wf-fb-sources">From ' + srcs + '</div>' : '') + '</section>' +
3006
+ '<section class="wf-fb-improve"><h3>Improve this workflow</h3>' +
3007
+ '<p>Reads the results people marked <b>needs work</b>, changed, or commented on, and suggests changes to the prompt and new success criteria. Nothing changes until you add them to the draft and publish it.</p>' +
3008
+ '<div class="wf-fb-improve-bar"><button type="button" class="le-btn-dark wf-fb-go"' + (f.actionable ? '' : ' disabled') + '>Suggest improvements</button>' +
3009
+ '<span class="hint">' + (f.actionable ? f.actionable + ' piece' + (f.actionable === 1 ? '' : 's') + ' of feedback to learn from' : 'Nothing to learn from yet: mark a result as needs work, change it, or add a note.') + '</span></div>' +
3010
+ '<div class="wf-fb-sugg" hidden></div></section>' +
3011
+ '<section class="wf-section"><h4 class="wf-sub">Feedback</h4>' +
3012
+ (f.items.length ? '<ul class="wf-fb-list">' + f.items.map(function (i) { return feedbackItemHtml(i, name); }).join('') + '</ul>' : '<p class="hint" style="margin:0">None yet.</p>') + '</section>' +
3013
+ '<section class="wf-section"><h4 class="wf-sub">Where feedback comes from</h4><div class="wf-fb-ways">' +
3014
+ '<div class="wf-fb-way"><b>Inbox</b><span>Under each finished run' + RSQ + 's conversation: Good or Needs work, a note, and the result as it should have been.</span></div>' +
3015
+ '<div class="wf-fb-way"><b>Messaging apps</b><span>' + (toChat ? 'Each result posted to chat ends with Good and Needs work links.' : 'Turn on ' + String.fromCharCode(8220) + 'result to chat' + String.fromCharCode(8221) + ' in Messaging, and each result posted ends with Good and Needs work links.') + '</span></div>' +
3016
+ '<div class="wf-fb-way"><b>Other platforms</b><span>Each finished run' + RSQ + 's callback has a <code>feedback_url</code> to post to.</span>' +
3017
+ '<span data-advanced>Or with an API key:</span><pre data-advanced>POST /agents/' + escapeHtml(name) + '/runs/&lt;runId&gt;/feedback' + String.fromCharCode(10) + '{ "verdict": "bad", "note": "...", "final": "...", "source": "api", "by": "jane@acme.com" }</pre></div>' +
3018
+ '</div></section>';
3019
+ var trace = function (ev) {
3020
+ var a = ev.target.closest('.wf-fb-trace');
3021
+ if (!a) return;
3022
+ ev.preventDefault();
3023
+ showWorkflowTab(card, 'activity');
3024
+ openRunTrace(name, card, a.getAttribute('data-run'));
3025
+ };
3026
+ box.addEventListener('click', trace);
3027
+ var go = box.querySelector('.wf-fb-go');
3028
+ if (go) go.addEventListener('click', function () { suggestImprovements(name, card, base, box); });
3029
+ });
3030
+ }
3031
+
3032
+ // Self-Improve: ask for suggestions, show them (each change and why, the
3033
+ // prompt's diff, new criteria to tick, questions only a person can
3034
+ // answer), and add what's chosen to the draft.
3035
+ function suggestImprovements(name, card, base, box) {
3036
+ var go = box.querySelector('.wf-fb-go');
3037
+ var panel = box.querySelector('.wf-fb-sugg');
3038
+ go.disabled = true;
3039
+ go.textContent = 'Reading the feedback' + String.fromCharCode(8230);
3040
+ panel.hidden = false;
3041
+ panel.innerHTML = '<p class="hint" style="margin:0">This takes a minute: the model reads each result and what people said about it.</p>';
3042
+ fetchJsonRetryOnce(base + '/improve', { method: 'POST' }).then(function (r) {
3043
+ go.disabled = false;
3044
+ go.textContent = 'Suggest again';
3045
+ if (!r.ok) { panel.innerHTML = '<p class="error">' + escapeHtml(r.body.error || 'Could not suggest improvements') + '</p>'; return; }
3046
+ var sg = r.body;
3047
+ var changed = sg.instructions !== sg.from.instructions;
3048
+ if (!changed && !sg.criteria.length) {
3049
+ panel.innerHTML = '<p style="margin:0"><span class="le-pill good">No changes needed</span> ' + escapeHtml(sg.summary || 'The feedback doesn' + RSQ + 't call for changes to the prompt.') + '</p>';
3050
+ return;
3051
+ }
3052
+ panel.innerHTML =
3053
+ (sg.summary ? '<p style="margin:0;color:var(--ink)">' + escapeHtml(sg.summary) + '</p>' : '') +
3054
+ (sg.changes.length ? '<h4>// Suggested changes</h4><ul class="wf-fb-changes">' + sg.changes.map(function (c) { return '<li><strong>' + escapeHtml(c.what) + '</strong>' + (c.why ? '<span>' + escapeHtml(c.why) + '</span>' : '') + '</li>'; }).join('') + '</ul>' : '') +
3055
+ (changed ? '<h4>// The prompt, changed' + (sg.from.drafted ? ' (from its draft)' : '') + '</h4>' + versionDiffHtml(sg.from.instructions, sg.instructions) +
3056
+ '<label style="display:flex;gap:8px;align-items:center;font-size:13.5px"><input type="checkbox" class="wf-fb-take-prompt" checked> Add these prompt changes</label>' : '') +
3057
+ (sg.criteria.length ? '<h4>// New success criteria</h4><div class="wf-fb-crits">' + sg.criteria.map(function (c, i) { return '<label><input type="checkbox" data-crit="' + i + '" checked> <span>' + escapeHtml(c.text) + ' <span class="hint">(' + escapeHtml(critKindText(c)) + ')</span></span></label>'; }).join('') + '</div>' : '') +
3058
+ (sg.open.length ? '<h4>// Only you can answer</h4><ul class="wf-fb-open">' + sg.open.map(function (q) { return '<li>' + escapeHtml(q) + '</li>'; }).join('') + '</ul>' : '') +
3059
+ '<div class="wf-fb-improve-bar"><button type="button" class="le-btn-dark wf-fb-add">Add to draft</button><span class="hint wf-fb-add-status">Then review and publish it, and Evaluate to check it does better.</span></div>' +
3060
+ '<p class="hint" style="margin:0">Suggested by ' + escapeHtml(sg.model) + ' from ' + sg.basedOn + ' piece' + (sg.basedOn === 1 ? '' : 's') + ' of feedback.</p>';
3061
+ panel.querySelector('.wf-fb-add').addEventListener('click', function (ev) {
3062
+ var btn = ev.currentTarget;
3063
+ var status = panel.querySelector('.wf-fb-add-status');
3064
+ var takePrompt = changed && panel.querySelector('.wf-fb-take-prompt') && panel.querySelector('.wf-fb-take-prompt').checked;
3065
+ var picked = sg.criteria.filter(function (c, i) { var b = panel.querySelector('[data-crit="' + i + '"]'); return b && b.checked; });
3066
+ if (!takePrompt && !picked.length) { status.textContent = 'Tick at least one change to add.'; return; }
3067
+ btn.disabled = true;
3068
+ status.textContent = 'Adding' + String.fromCharCode(8230);
3069
+ var id = card.dataset.workflow;
3070
+ var w = withDraftFields(workflowsById[id]);
3071
+ // The whole editor form, as the workflow stands in its draft, with
3072
+ // the prompt changed: the draft keeps everything else as it is.
3073
+ var steps = [];
3074
+ if (takePrompt) steps.push(function () {
3075
+ return fetchJsonRetryOnce(base + '/draft', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({
3076
+ title: w.title, description: w.description, instructions: sg.instructions, parameters: w.parameters || {},
3077
+ output: w.output || '', outputSchema: w.outputSchema ? JSON.stringify(w.outputSchema, null, 2) : '', model: w.model || null,
3078
+ }) });
3079
+ });
3080
+ if (picked.length) steps.push(function () {
3081
+ return fetchJsonRetryOnce(base + '/draft').then(function (d) {
3082
+ var now = d.ok && d.body.draft && d.body.draft.criteria ? d.body.draft.criteria : ((w.evals && w.evals.criteria) || []);
3083
+ var list = now.map(function (c) { return { text: c.text, kind: c.kind, value: c.value }; }).concat(picked.map(function (c) { return { text: c.text, kind: c.kind, value: c.value }; }));
3084
+ return fetchJsonRetryOnce(base + '/draft/criteria', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ criteria: list }) });
3085
+ });
3086
+ });
3087
+ steps.reduce(function (p, step) {
3088
+ return p.then(function (prev) { if (prev && !prev.ok) return prev; return step(); });
3089
+ }, Promise.resolve(null)).then(function (last) {
3090
+ if (last && !last.ok) { btn.disabled = false; status.textContent = last.body.error || 'Could not add them'; return; }
3091
+ btn.textContent = 'Added to the draft';
3092
+ status.innerHTML = 'Review and publish the draft (at the top) to make it live, then run Evaluate to check it does better.';
3093
+ refreshDraft(name, card);
3094
+ });
3095
+ });
3096
+ });
3097
+ }
3098
+
2893
3099
  function workflowVersionsHtml() {
2894
3100
  return '<div class="wf-versions"><p class="hint" style="margin:0">Loading' + String.fromCharCode(8230) + '</p></div>';
2895
3101
  }
@@ -3201,6 +3407,7 @@ ${renderMarkdownScript}
3201
3407
  loadWorkflowHealth(card, base);
3202
3408
  loadCandidates(name, card, base);
3203
3409
  loadWorkflowRuns(name, card, base);
3410
+ loadWorkflowFeedback(name, card, base);
3204
3411
  if (openTraces[id] && card.querySelector('.wf-trace')) openRunTrace(name, card, openTraces[id].run);
3205
3412
  card.querySelector('.workflow-edit').addEventListener('click', function () { openWorkflowEditor(name, card); });
3206
3413
  // Opens the workflow's page on its Triggers tab.
@@ -0,0 +1,14 @@
1
+ import type { RunFeedback } from '../core/workflow-runs.js';
2
+ export declare function feedbackPageHtml(view: {
3
+ state: 'ask';
4
+ title: string;
5
+ result: string;
6
+ verdict?: 'good' | 'bad';
7
+ given?: RunFeedback;
8
+ error?: string;
9
+ } | {
10
+ state: 'thanks';
11
+ title: string;
12
+ } | {
13
+ state: 'invalid';
14
+ }): string;
@@ -0,0 +1,56 @@
1
+ // The page a signed feedback link opens (GET /feedback/<token>, from a
2
+ // messaging app, an email or a callback): a run's result, and a form to
3
+ // say whether it was good, add a note, give the text actually used, and a
4
+ // name, sent with no sign-in (POST, the link is the permission). Plain
5
+ // HTML and a form, so it works anywhere, scripts or not.
6
+ import { devUiCss } from './dev-ui-styles.js';
7
+ const esc = (s) => s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
8
+ export function feedbackPageHtml(view) {
9
+ const page = (title, body) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${esc(title)}</title>
10
+ <style>${devUiCss}
11
+ body { background: var(--canvas); }
12
+ .fb { max-width: 640px; margin: 6vh auto 40px; padding: 0 16px; display: grid; gap: 18px; }
13
+ .fb-card { background: var(--bg); border: 1px solid var(--line); border-radius: 16px; padding: 22px 24px; display: grid; gap: 16px; box-shadow: 0 2px 10px rgba(0, 0, 0, .04); }
14
+ .fb h1 { margin: 0; font-size: 24px; font-weight: 500; letter-spacing: -0.02em; }
15
+ .fb h1 .soft { color: var(--ink-faint); }
16
+ .fb-result { max-height: 280px; overflow: auto; padding: 12px 14px; border-radius: 10px; background: var(--surface); white-space: pre-wrap; overflow-wrap: anywhere; font-size: 14px; line-height: 1.55; }
17
+ .fb-k { font-size: 12px; font-family: var(--font-mono); color: var(--ink-faint); margin: 0 0 6px; }
18
+ .fb-verdict { display: flex; gap: 10px; }
19
+ .fb-verdict label { flex: 1; display: flex; align-items: center; justify-content: center; gap: 8px; height: 46px; border: 1px solid var(--line); border-radius: 12px; font-size: 15px; font-weight: 600; cursor: pointer; }
20
+ .fb-verdict input { position: absolute; opacity: 0; pointer-events: none; }
21
+ .fb-verdict label:has(input:checked) { border-color: var(--primary); background: var(--primary); color: var(--on-primary); }
22
+ .fb textarea, .fb input[type="text"] { width: 100%; font-size: 14px; border-radius: 10px; padding: 10px 12px; }
23
+ .fb textarea { min-height: 80px; }
24
+ .fb details summary { cursor: pointer; font-size: 13.5px; color: var(--ink-muted); }
25
+ .fb details[open] summary { margin-bottom: 8px; }
26
+ .fb .send { height: 42px; border-radius: 11px; border: 0; background: var(--primary); color: var(--on-primary); font-size: 14.5px; font-weight: 600; }
27
+ .fb .hint { font-size: 12.5px; color: var(--ink-muted); margin: 0; }
28
+ .fb .error { color: var(--bad); font-size: 13.5px; margin: 0; }
29
+ .fb-done { text-align: center; padding: 34px 24px; }
30
+ .fb-done .big { font-size: 40px; }
31
+ </style></head><body><main class="fb">${body}</main></body></html>`;
32
+ if (view.state === 'invalid') {
33
+ return page('Feedback link', '<div class="fb-card fb-done"><div class="big">⌛</div><h1>This link has expired</h1><p class="hint">Feedback links last 30 days. Give feedback on this run from the Inbox instead.</p></div>');
34
+ }
35
+ if (view.state === 'thanks') {
36
+ return page('Thanks', `<div class="fb-card fb-done"><div class="big">🙏</div><h1>Thanks, that helps</h1><p class="hint">Your feedback on ${esc(view.title)} is saved. It's used to improve the workflow; you can close this page.</p></div>`);
37
+ }
38
+ const given = view.given;
39
+ const verdict = view.verdict ?? given?.verdict;
40
+ const check = (v) => (verdict === v ? ' checked' : '');
41
+ return page(`Feedback: ${view.title}`, `
42
+ <h1><span class="soft">How did</span> ${esc(view.title)} <span class="soft">do?</span></h1>
43
+ <form class="fb-card" method="post">
44
+ <div><p class="fb-k">// Its result</p><div class="fb-result">${esc(view.result || '(no result)')}</div></div>
45
+ ${given ? `<p class="hint">Feedback was already given${given.by ? ` by ${esc(given.by)}` : ''}; sending again replaces it.</p>` : ''}
46
+ <div class="fb-verdict" role="radiogroup" aria-label="Was it good?">
47
+ <label><input type="radio" name="verdict" value="good"${check('good')} required>👍 Good</label>
48
+ <label><input type="radio" name="verdict" value="bad"${check('bad')}>👎 Needs work</label>
49
+ </div>
50
+ <label><span class="fb-k">// What should change? (optional)</span><textarea name="note" maxlength="1000" placeholder="e.g. It should give the tracking number, and keep it shorter">${esc(given?.note ?? '')}</textarea></label>
51
+ <details><summary>Fix the result yourself (optional)</summary><textarea name="final" maxlength="50000" style="min-height:160px">${esc(given?.final ?? view.result)}</textarea><p class="hint">Change it to what you'd actually send. The workflow learns from the difference.</p></details>
52
+ <label><span class="fb-k">// Your name (optional)</span><input type="text" name="name" maxlength="80" placeholder="So the team knows who said it"></label>
53
+ ${view.error ? `<p class="error">${esc(view.error)}</p>` : ''}
54
+ <button type="submit" class="send">Send feedback</button>
55
+ </form>`);
56
+ }
@@ -79,6 +79,19 @@ export const inboxPageHtml = `<!doctype html>
79
79
  .ib-act summary code { font-size: 12px; }
80
80
  .ib-act.failed summary { color: var(--bad); }
81
81
  .ib-typing { font-size: 13px; color: var(--ink-muted); font-style: italic; }
82
+ .ib-fb { display: grid; gap: 10px; padding: 12px 14px; border: 1px solid var(--line); border-radius: 12px; background: var(--bg); }
83
+ .ib-fb-ask { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; }
84
+ .ib-fb-ask[hidden], .ib-fb-form[hidden], .ib-fb-given[hidden] { display: none; }
85
+ .ib-fb-q { font-size: 14px; font-weight: 600; margin-right: auto; }
86
+ .ib-fb-pick { display: inline-flex; gap: 6px; }
87
+ .ib-fb-pick button { height: 34px; padding: 0 14px; border-radius: 9px; font-size: 13.5px; font-weight: 600; background: var(--bg); }
88
+ .ib-fb-pick button[aria-pressed="true"] { background: var(--primary); border-color: var(--primary); color: var(--on-primary); }
89
+ .ib-fb-form { display: grid; gap: 8px; }
90
+ .ib-fb-form textarea { width: 100%; box-sizing: border-box; min-height: 64px; font-size: 13.5px; border-radius: 9px; }
91
+ .ib-fb-form textarea.ib-fb-final { min-height: 140px; margin-top: 6px; }
92
+ .ib-fb-form details summary { cursor: pointer; font-size: 13px; color: var(--ink-muted); }
93
+ .ib-fb-given { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; font-size: 13.5px; }
94
+ .ib-fb-given .ib-fb-change { margin-left: auto; height: 28px; padding: 0 10px; font-size: 12.5px; }
82
95
  @media (max-width: 860px) {
83
96
  .ib-split { grid-template-columns: minmax(0, 1fr); }
84
97
  .ib-split.has-thread .ib-items { display: none; }
@@ -159,6 +172,10 @@ ${renderMarkdownScript}
159
172
  var state = { view: VIEWS.some(function (v) { return v[0] === asked; }) ? asked : '', q: params.get('q') || '', workflow: params.get('workflow') || '', item: params.get('item') || '' };
160
173
  var listed = null;
161
174
  var openThread = null;
175
+ // The conversation the address opens on (?item=) is asked for now,
176
+ // alongside the list, not after it: on a hosted workspace that saves a
177
+ // round trip of hundreds of milliseconds. Used once.
178
+ var earlyThread = state.item ? { id: state.item, response: fetch('/inbox/cases/' + encodeURIComponent(state.item), { headers: { accept: 'application/json' } }) } : null;
162
179
  var fullAccess = !document.querySelector('.le-app.le-inbox-only');
163
180
  var role = 'owner';
164
181
  var workflows = {};
@@ -332,7 +349,9 @@ ${renderMarkdownScript}
332
349
  function loadThread(id) {
333
350
  var box = page.querySelector('.ib-thread');
334
351
  if (!openThread || openThread.id !== id) box.innerHTML = '<div class="ib-thread-empty">Loading' + ELLIPSIS + '</div>';
335
- return fetch('/inbox/cases/' + encodeURIComponent(id), { headers: { accept: 'application/json' } })
352
+ var early = earlyThread && earlyThread.id === id ? earlyThread.response : null;
353
+ earlyThread = null;
354
+ return (early || fetch('/inbox/cases/' + encodeURIComponent(id), { headers: { accept: 'application/json' } }))
336
355
  .then(function (r) { return r.ok ? r.json() : r.json().then(function (b) { throw new Error(b.error || 'HTTP ' + r.status); }); })
337
356
  .then(function (c) {
338
357
  if (state.item !== id) return;
@@ -405,10 +424,69 @@ ${renderMarkdownScript}
405
424
  if (run.status === 'done' && !(run.output === undefined && lastText && lastText === String(run.result || '').trim())) out.push(msgHtml('agent', agent, run.finished_at, run.output !== undefined
406
425
  ? '<pre class="ib-pre">' + esc(JSON.stringify(run.output, null, 2)) + '</pre>'
407
426
  : '<div class="ib-md">' + renderMarkdownPreview(run.result || 'Done.') + '</div>'));
427
+ if (run.status === 'done') out.push(feedbackHtml(run));
408
428
  }
409
429
  return out.join('');
410
430
  }
411
431
 
432
+ // How a finished run did, in a person's words: Good or Needs work, a
433
+ // note, and the result as it should have been. It feeds the workflow's
434
+ // Feedback tab and Self-Improve. Shown as given once given, to change.
435
+ function feedbackHtml(run) {
436
+ var f = run.feedback;
437
+ if (!canDecide()) return f ? '<li class="ib-fb"><span class="hint">Feedback: ' + esc(f.verdict === 'good' ? 'Good' : f.verdict === 'bad' ? 'Needs work' : 'given') + (f.note ? DOT + esc(f.note) : '') + '</span></li>' : '';
438
+ var given = f ? '<div class="ib-fb-given"><span class="ib-state ' + (f.verdict === 'bad' ? 'bad' : 'good') + '">' + (f.verdict === 'bad' ? 'Needs work' : f.verdict === 'good' ? 'Good' : 'Feedback given') + '</span>' +
439
+ (f.note ? '<span>' + String.fromCharCode(8220) + esc(f.note) + String.fromCharCode(8221) + '</span>' : '') +
440
+ '<span class="hint">' + esc((f.by ? f.by + DOT : '') + ago(f.at)) + '</span><button type="button" class="ib-fb-change">Change</button></div>' : '';
441
+ return '<li class="ib-fb" data-run="' + esc(run.run_id) + '">' + given +
442
+ '<div class="ib-fb-ask"' + (f ? ' hidden' : '') + '><span class="ib-fb-q">How did it do?</span>' +
443
+ '<span class="ib-fb-pick"><button type="button" data-verdict="good"' + (f && f.verdict === 'good' ? ' aria-pressed="true"' : '') + '>' + String.fromCodePoint(128077) + ' Good</button>' +
444
+ '<button type="button" data-verdict="bad"' + (f && f.verdict === 'bad' ? ' aria-pressed="true"' : '') + '>' + String.fromCodePoint(128078) + ' Needs work</button></span></div>' +
445
+ '<form class="ib-fb-form" hidden>' +
446
+ '<textarea name="note" maxlength="1000" placeholder="What should change? (optional) e.g. give the tracking number, keep it shorter">' + esc(f && f.note ? f.note : '') + '</textarea>' +
447
+ '<details><summary>Fix the result yourself (optional)</summary><textarea name="final" class="ib-fb-final">' + esc(f && f.final != null ? f.final : (run.result || '')) + '</textarea><span class="hint">Change it to what you' + String.fromCharCode(8217) + 'd actually send. The workflow learns from the difference.</span></details>' +
448
+ '<div class="ib-actions"><button type="submit" class="ib-btn">Send feedback</button><button type="button" class="ib-btn plain ib-fb-cancel">Cancel</button><span class="hint ib-fb-result" role="status"></span></div>' +
449
+ '</form></li>';
450
+ }
451
+
452
+ function wireFeedback(c) {
453
+ var box = page.querySelector('.ib-thread .ib-fb[data-run]');
454
+ if (!box) return;
455
+ var run = c.run;
456
+ var verdict = run.feedback && run.feedback.verdict;
457
+ var ask = box.querySelector('.ib-fb-ask');
458
+ var form = box.querySelector('.ib-fb-form');
459
+ var change = box.querySelector('.ib-fb-change');
460
+ if (change) change.addEventListener('click', function () { box.querySelector('.ib-fb-given').hidden = true; ask.hidden = false; form.hidden = false; });
461
+ ask.addEventListener('click', function (ev) {
462
+ var b = ev.target.closest('[data-verdict]');
463
+ if (!b) return;
464
+ verdict = b.getAttribute('data-verdict');
465
+ var all = ask.querySelectorAll('[data-verdict]');
466
+ for (var i = 0; i < all.length; i++) all[i].setAttribute('aria-pressed', String(all[i] === b));
467
+ form.hidden = false;
468
+ form.querySelector('textarea[name="note"]').focus();
469
+ });
470
+ form.querySelector('.ib-fb-cancel').addEventListener('click', function () { form.hidden = true; });
471
+ form.addEventListener('submit', function (ev) {
472
+ ev.preventDefault();
473
+ var result = form.querySelector('.ib-fb-result');
474
+ if (!verdict) { result.textContent = 'Choose Good or Needs work first.'; return; }
475
+ var body = { verdict: verdict };
476
+ var note = form.querySelector('textarea[name="note"]').value.trim();
477
+ if (note) body.note = note;
478
+ var final = form.querySelector('textarea[name="final"]').value;
479
+ if (final !== (run.result || '')) body.final = final;
480
+ var send = form.querySelector('[type="submit"]');
481
+ send.disabled = true;
482
+ result.textContent = 'Sending' + ELLIPSIS;
483
+ fetch('/inbox/cases/' + encodeURIComponent(run.run_id) + '/feedback', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
484
+ .then(function (r) { return r.json().then(function (b) { if (!r.ok) throw new Error(b.error || 'Could not send it'); return b; }); })
485
+ .then(function () { openThread = null; loadThread(c.id); })
486
+ .catch(function (err) { send.disabled = false; result.textContent = err.message; });
487
+ });
488
+ }
489
+
412
490
  function renderThread(c) {
413
491
  var box = page.querySelector('.ib-thread');
414
492
  var run = c.run;
@@ -440,6 +518,7 @@ ${renderMarkdownScript}
440
518
  .catch(function (err) { archive.disabled = false; archive.textContent = err.message; });
441
519
  });
442
520
  wireCase(c);
521
+ wireFeedback(c);
443
522
  }
444
523
 
445
524
  function valueHtml(v) {
@@ -573,10 +652,17 @@ ${renderMarkdownScript}
573
652
  }, 15000);
574
653
  }
575
654
 
655
+ // The list doesn't wait for the person's role: only whether they can
656
+ // decide depends on it, so a conversation already open is drawn again
657
+ // if they turn out not to.
658
+ start();
576
659
  (window.leShell && window.leShell.settings ? window.leShell.settings() : fetch('/config/settings').then(function (r) { return r.ok ? r.json() : null; }))
577
- .then(function (s) { if (s && s.signIn && s.signIn.role) role = s.signIn.role; })
578
- .catch(function () {})
579
- .then(start);
660
+ .then(function (s) {
661
+ var was = role;
662
+ if (s && s.signIn && s.signIn.role) role = s.signIn.role;
663
+ if (role !== was && state.item && openThread) { openThread = null; loadThread(state.item); }
664
+ })
665
+ .catch(function () {});
580
666
  })();
581
667
  </script>
582
668
  </body>
@@ -161,7 +161,10 @@ export declare function setAgentPrimaryNotifier(config: AgentConfig, channel: un
161
161
  * regardless of which events they subscribed to. A webhook gets a signed
162
162
  * `run_finish` payload with `data` merged in; the apps get `text`.
163
163
  * Returns whether any notifier took it. */
164
- export declare function announceToNotifier(config: AgentConfig, text: string, data: Record<string, unknown>, defaultWebhook?: DefaultWebhook): boolean;
164
+ /** `feedback`, for a finished run: its signed feedback link for each
165
+ * channel (slack, telegram, lark, webhook), added to each app's message as
166
+ * Good / Needs work links and to a webhook's payload as feedback_url. */
167
+ export declare function announceToNotifier(config: AgentConfig, text: string, data: Record<string, unknown>, defaultWebhook?: DefaultWebhook, feedback?: (channel: string) => string | undefined): boolean;
165
168
  /** Posts `text` to the agent's messaging apps only (Slack, Lark,
166
169
  * Telegram), not to a webhook: a run's chat notice. Whether any app got
167
170
  * it. */
@@ -293,7 +293,14 @@ function activeNotifierTargets(config, defaultWebhook) {
293
293
  * regardless of which events they subscribed to. A webhook gets a signed
294
294
  * `run_finish` payload with `data` merged in; the apps get `text`.
295
295
  * Returns whether any notifier took it. */
296
- export function announceToNotifier(config, text, data, defaultWebhook) {
296
+ /** `feedback`, for a finished run: its signed feedback link for each
297
+ * channel (slack, telegram, lark, webhook), added to each app's message as
298
+ * Good / Needs work links and to a webhook's payload as feedback_url. */
299
+ export function announceToNotifier(config, text, data, defaultWebhook, feedback) {
300
+ const ask = (channel) => {
301
+ const url = feedback?.(channel);
302
+ return url ? `${text}\n\nHow did it do? Good: ${url}?v=good · Needs work: ${url}?v=bad` : text;
303
+ };
297
304
  let targets;
298
305
  try {
299
306
  targets = activeNotifierTargets(config, defaultWebhook);
@@ -305,19 +312,19 @@ export function announceToNotifier(config, text, data, defaultWebhook) {
305
312
  for (const target of targets) {
306
313
  switch (target.channel) {
307
314
  case 'webhook':
308
- postLifecycleWebhook(target.config.webhookUrl, target.config.webhookSecret, 'run_finish', { agent: config.name, text, ...data });
315
+ postLifecycleWebhook(target.config.webhookUrl, target.config.webhookSecret, 'run_finish', { agent: config.name, text, ...data, ...(feedback?.('webhook') ? { feedback_url: feedback('webhook') } : {}) });
309
316
  sent = true;
310
317
  break;
311
318
  case 'slack':
312
- new SlackNotifier({ botToken: target.config.botToken, channelId: target.config.channelId }).postMessage(text);
319
+ new SlackNotifier({ botToken: target.config.botToken, channelId: target.config.channelId }).postMessage(ask('slack'));
313
320
  sent = true;
314
321
  break;
315
322
  case 'lark':
316
- new LarkNotifier({ appId: target.config.appId, appSecret: target.config.appSecret, chatId: target.config.chatId }).postMessage(text);
323
+ new LarkNotifier({ appId: target.config.appId, appSecret: target.config.appSecret, chatId: target.config.chatId }).postMessage(ask('lark'));
317
324
  sent = true;
318
325
  break;
319
326
  case 'telegram':
320
- new TelegramNotifier({ botToken: target.config.botToken, chatId: target.config.chatId }).postMessage(text);
327
+ new TelegramNotifier({ botToken: target.config.botToken, chatId: target.config.chatId }).postMessage(ask('telegram'));
321
328
  sent = true;
322
329
  break;
323
330
  }
@@ -1,5 +1,5 @@
1
1
  import type { ModelCall } from '#core/run-agent.js';
2
- import type { RunFeedback, WorkflowRun } from '#core/workflow-runs.js';
2
+ import { type FeedbackSource, type RunFeedback, type WorkflowRun } from '#core/workflow-runs.js';
3
3
  import { type JsonSchema } from '#core/output-schema.js';
4
4
  export declare class EvidenceError extends Error {
5
5
  }
@@ -26,8 +26,15 @@ export interface WorkflowScores {
26
26
  export declare function workflowScores(runs: WorkflowRun[]): WorkflowScores;
27
27
  /** Feedback on a finished run, from an app or a person: `final`, the text
28
28
  * actually used (an edited draft, say), and/or `verdict` good or bad,
29
- * and a short `note`. */
30
- export declare function runFeedbackFrom(run: WorkflowRun, body: Record<string, unknown>): RunFeedback;
29
+ * and a short `note`; `source`, where it came from, and `by`, who gave
30
+ * it, when the caller says (see FeedbackSource). */
31
+ export declare function runFeedbackFrom(run: WorkflowRun, body: Record<string, unknown>, given?: {
32
+ source?: FeedbackSource;
33
+ by?: string;
34
+ }): RunFeedback;
35
+ /** A source an app names for its feedback, or undefined for none or one
36
+ * not known. */
37
+ export declare function feedbackSourceOf(value: unknown): FeedbackSource | undefined;
31
38
  export interface EvalCase {
32
39
  id: string;
33
40
  params: Record<string, string>;
@@ -24,6 +24,7 @@
24
24
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
25
25
  import { dirname, join } from 'node:path';
26
26
  import { randomUUID } from 'node:crypto';
27
+ import { FEEDBACK_SOURCES } from '#core/workflow-runs.js';
27
28
  import { checkOutput } from '#core/output-schema.js';
28
29
  import { editAmount } from './goals-admin.js';
29
30
  export class EvidenceError extends Error {
@@ -63,8 +64,9 @@ export function workflowScores(runs) {
63
64
  }
64
65
  /** Feedback on a finished run, from an app or a person: `final`, the text
65
66
  * actually used (an edited draft, say), and/or `verdict` good or bad,
66
- * and a short `note`. */
67
- export function runFeedbackFrom(run, body) {
67
+ * and a short `note`; `source`, where it came from, and `by`, who gave
68
+ * it, when the caller says (see FeedbackSource). */
69
+ export function runFeedbackFrom(run, body, given = {}) {
68
70
  if (run.status !== 'done')
69
71
  throw new EvidenceError('Only a run that finished with a result can get feedback.');
70
72
  const verdict = body.verdict === 'good' || body.verdict === 'bad' ? body.verdict : undefined;
@@ -78,9 +80,16 @@ export function runFeedbackFrom(run, body) {
78
80
  ...(verdict ? { verdict } : {}),
79
81
  ...(final !== undefined ? { final, edit: editAmount(run.result ?? '', final) } : {}),
80
82
  ...(note ? { note } : {}),
83
+ ...(given.source ? { source: given.source } : {}),
84
+ ...(given.by ? { by: given.by.slice(0, 120) } : {}),
81
85
  at: new Date().toISOString(),
82
86
  };
83
87
  }
88
+ /** A source an app names for its feedback, or undefined for none or one
89
+ * not known. */
90
+ export function feedbackSourceOf(value) {
91
+ return typeof value === 'string' && FEEDBACK_SOURCES.includes(value) ? value : undefined;
92
+ }
84
93
  /** The check every round adds for a workflow with an output schema: its
85
94
  * result matches the schema (core/output-schema.ts), checked in code. */
86
95
  export const OUTPUT_SCHEMA_CRITERION = { id: 'output-schema', text: 'Matches the output schema', kind: 'output_schema' };
@@ -0,0 +1,76 @@
1
+ import type { ModelCall } from '../core/run-agent.js';
2
+ import type { FeedbackSource, WorkflowRun } from '../core/workflow-runs.js';
3
+ import { type EvalCriterion } from './workflow-evidence.js';
4
+ /** One piece of feedback, as the Feedback tab lists it. */
5
+ export interface FeedbackItem {
6
+ runId: string;
7
+ at: string;
8
+ verdict?: 'good' | 'bad';
9
+ edit?: 'none' | 'light' | 'heavy';
10
+ note?: string;
11
+ by?: string;
12
+ source?: FeedbackSource;
13
+ /** The run's inputs, in a line. */
14
+ inputs: string;
15
+ /** The start of its result, and of the text used instead when it was
16
+ * changed. */
17
+ result: string;
18
+ final?: string;
19
+ workflowVersion?: number;
20
+ }
21
+ export interface FeedbackSummary {
22
+ days: number;
23
+ /** Finished runs in the period, and how many got feedback. */
24
+ runs: number;
25
+ total: number;
26
+ good: number;
27
+ bad: number;
28
+ /** Results changed before they were used, a little or a lot. */
29
+ edited: number;
30
+ /** Feedback by where it came from. */
31
+ sources: Partial<Record<FeedbackSource | 'unknown', number>>;
32
+ /** Newest first. */
33
+ items: FeedbackItem[];
34
+ /** Bad, edited or with a note: what Self-Improve learns from. */
35
+ actionable: number;
36
+ }
37
+ /** Whether a piece of feedback says something to learn from. */
38
+ export declare function isActionable(f: {
39
+ verdict?: string;
40
+ edit?: string;
41
+ note?: string;
42
+ }): boolean;
43
+ /** A workflow's feedback over `days`, from its runs (each carries the
44
+ * latest feedback given on it). */
45
+ export declare function feedbackSummary(runs: WorkflowRun[], days: number): FeedbackSummary;
46
+ export declare const IMPROVE_PROMPT = "You improve an AI workflow from what people said about its results. You get its prompt (what the agent follows on every run), its result format, its success criteria, its tools, and feedback on recent runs: each run's inputs, the result it gave, whether a person marked it good or bad, their note, and the text they actually used when they changed the result.\n\nFind what the feedback says should change: mistakes that recur, rules the agent missed, the tone, length or format people keep fixing, facts it needed and didn't have. Then change the prompt as little as it takes to fix them:\n- Keep everything that works, word for word: its structure, its rules, its examples. Edit or add only what the feedback supports; never remove a rule because one run broke it.\n- Write each change as a plain instruction the agent can follow, in the prompt's own style and language. Put it where it belongs (a rule with the rules, an example with the examples).\n- Never invent facts, policies, prices or names that aren't in the prompt or the feedback. When a fix needs a fact you don't have, say so in \"open\" instead.\n- Ignore feedback that is about one case only, or that contradicts other feedback, unless a pattern is clear.\n- Good feedback tells you what to keep: don't change what people marked good.\n\nAlso suggest up to four new success criteria: yes or no checks that a good result passes, for what people kept correcting, each under 20 words (\"The reply states the refund amount\", \"It signs off with the team's name\"). Leave out any the current criteria already cover. Each has \"kind\": \"judge\" (a reviewer decides, most of them), or \"contains\" / \"not_contains\" with \"value\" for an exact phrase the feedback demands.\n\nReply with JSON only:\n{\"summary\": \"<one or two sentences: what the feedback shows>\",\n \"changes\": [{\"what\": \"<the change, in a short sentence>\", \"why\": \"<the feedback behind it, briefly>\"}],\n \"instructions\": \"<the whole prompt, with the changes made>\",\n \"criteria\": [{\"text\": \"...\", \"kind\": \"judge\"}],\n \"open\": [\"<a question only a person can answer, if any>\"]}\nIf the feedback doesn't call for any change, keep \"instructions\" exactly as given, and leave \"changes\" and \"criteria\" empty.";
47
+ export interface ImproveSuggestion {
48
+ summary: string;
49
+ changes: {
50
+ what: string;
51
+ why: string;
52
+ }[];
53
+ /** The whole prompt with the changes made (the same as given when
54
+ * nothing should change). */
55
+ instructions: string;
56
+ criteria: EvalCriterion[];
57
+ open: string[];
58
+ /** How many pieces of feedback it read. */
59
+ basedOn: number;
60
+ }
61
+ /** Changes to a workflow's prompt and new success criteria, suggested from
62
+ * its feedback, for a person to review. Reads the feedback worth learning
63
+ * from (bad, changed or with a note), newest first, and a few marked good
64
+ * for what to keep. */
65
+ export declare function suggestImprovements(model: ModelCall, input: {
66
+ title: string;
67
+ instructions: string;
68
+ output?: string;
69
+ criteria: {
70
+ text: string;
71
+ kind: string;
72
+ value?: string;
73
+ }[];
74
+ tools: string[];
75
+ items: FeedbackItem[];
76
+ }): Promise<ImproveSuggestion>;
@@ -0,0 +1,119 @@
1
+ // Feedback on a workflow's runs, and Self-Improve: what people said about
2
+ // its results (from the Inbox, a signed link in a messaging app or an
3
+ // email, a callback, or an app through the API: see FeedbackSource), as a
4
+ // summary for its Feedback tab; and, from that, changes to its prompt and
5
+ // new success criteria a model suggests, for a person to review, add to
6
+ // the workflow's draft (web/workflow-drafts.ts) and publish as its next
7
+ // version. Nothing here changes a workflow by itself.
8
+ import { randomUUID } from 'node:crypto';
9
+ import { EvidenceError } from './workflow-evidence.js';
10
+ const excerpt = (text, max) => {
11
+ const t = (text ?? '').trim();
12
+ return t.length > max ? t.slice(0, max - 1) + '…' : t;
13
+ };
14
+ /** Whether a piece of feedback says something to learn from. */
15
+ export function isActionable(f) {
16
+ return f.verdict === 'bad' || f.edit === 'light' || f.edit === 'heavy' || Boolean(f.note);
17
+ }
18
+ /** A workflow's feedback over `days`, from its runs (each carries the
19
+ * latest feedback given on it). */
20
+ export function feedbackSummary(runs, days) {
21
+ const finished = runs.filter((r) => r.status === 'done');
22
+ const given = finished.filter((r) => r.feedback).sort((a, b) => b.feedback.at.localeCompare(a.feedback.at));
23
+ const sources = {};
24
+ for (const r of given) {
25
+ const k = r.feedback.source ?? 'unknown';
26
+ sources[k] = (sources[k] ?? 0) + 1;
27
+ }
28
+ const items = given.map((r) => {
29
+ const f = r.feedback;
30
+ return {
31
+ runId: r.run_id, at: f.at,
32
+ ...(f.verdict ? { verdict: f.verdict } : {}), ...(f.edit ? { edit: f.edit } : {}), ...(f.note ? { note: f.note } : {}),
33
+ ...(f.by ? { by: f.by } : {}), ...(f.source ? { source: f.source } : {}),
34
+ inputs: excerpt(Object.entries(r.params ?? {}).map(([k, v]) => `${k}: ${v}`).join(' · '), 200),
35
+ result: excerpt(r.result, 600),
36
+ ...(f.final !== undefined && f.edit !== 'none' ? { final: excerpt(f.final, 600) } : {}),
37
+ ...((r.versions?.workflow ?? r.versions?.brief) ? { workflowVersion: r.versions.workflow ?? r.versions.brief } : {}),
38
+ };
39
+ });
40
+ return {
41
+ days, runs: finished.length, total: given.length,
42
+ good: given.filter((r) => r.feedback.verdict === 'good').length,
43
+ bad: given.filter((r) => r.feedback.verdict === 'bad').length,
44
+ edited: given.filter((r) => r.feedback.edit === 'light' || r.feedback.edit === 'heavy').length,
45
+ sources, items: items.slice(0, 100), actionable: given.filter((r) => isActionable(r.feedback)).length,
46
+ };
47
+ }
48
+ export const IMPROVE_PROMPT = `You improve an AI workflow from what people said about its results. You get its prompt (what the agent follows on every run), its result format, its success criteria, its tools, and feedback on recent runs: each run's inputs, the result it gave, whether a person marked it good or bad, their note, and the text they actually used when they changed the result.
49
+
50
+ Find what the feedback says should change: mistakes that recur, rules the agent missed, the tone, length or format people keep fixing, facts it needed and didn't have. Then change the prompt as little as it takes to fix them:
51
+ - Keep everything that works, word for word: its structure, its rules, its examples. Edit or add only what the feedback supports; never remove a rule because one run broke it.
52
+ - Write each change as a plain instruction the agent can follow, in the prompt's own style and language. Put it where it belongs (a rule with the rules, an example with the examples).
53
+ - Never invent facts, policies, prices or names that aren't in the prompt or the feedback. When a fix needs a fact you don't have, say so in "open" instead.
54
+ - Ignore feedback that is about one case only, or that contradicts other feedback, unless a pattern is clear.
55
+ - Good feedback tells you what to keep: don't change what people marked good.
56
+
57
+ Also suggest up to four new success criteria: yes or no checks that a good result passes, for what people kept correcting, each under 20 words ("The reply states the refund amount", "It signs off with the team's name"). Leave out any the current criteria already cover. Each has "kind": "judge" (a reviewer decides, most of them), or "contains" / "not_contains" with "value" for an exact phrase the feedback demands.
58
+
59
+ Reply with JSON only:
60
+ {"summary": "<one or two sentences: what the feedback shows>",
61
+ "changes": [{"what": "<the change, in a short sentence>", "why": "<the feedback behind it, briefly>"}],
62
+ "instructions": "<the whole prompt, with the changes made>",
63
+ "criteria": [{"text": "...", "kind": "judge"}],
64
+ "open": ["<a question only a person can answer, if any>"]}
65
+ If the feedback doesn't call for any change, keep "instructions" exactly as given, and leave "changes" and "criteria" empty.`;
66
+ const KINDS = ['judge', 'contains', 'not_contains'];
67
+ /** Changes to a workflow's prompt and new success criteria, suggested from
68
+ * its feedback, for a person to review. Reads the feedback worth learning
69
+ * from (bad, changed or with a note), newest first, and a few marked good
70
+ * for what to keep. */
71
+ export async function suggestImprovements(model, input) {
72
+ const learn = input.items.filter(isActionable).slice(0, 14);
73
+ const keep = input.items.filter((i) => !isActionable(i) && i.verdict === 'good').slice(0, 4);
74
+ if (!learn.length)
75
+ throw new EvidenceError('There is no feedback to learn from yet: mark a result bad, change it, or add a note, from the Inbox, a messaging app or the API.');
76
+ const block = (i, n) => `<run n="${n}">\n<inputs>${i.inputs || 'none'}</inputs>\n<result>${i.result}</result>\n` +
77
+ `<feedback verdict="${i.verdict ?? 'none'}" edited="${i.edit ?? 'no'}">${i.note ?? ''}</feedback>\n` +
78
+ (i.final ? `<used_instead>${i.final}</used_instead>\n` : '') + '</run>';
79
+ const content = `The workflow: ${input.title}\n\n<prompt>\n${input.instructions.slice(0, 20000)}\n</prompt>\n\n` +
80
+ `<result_format>${input.output ?? 'none'}</result_format>\n\n` +
81
+ `<success_criteria>\n${input.criteria.map((c) => `- [${c.kind}${c.value ? `: ${c.value}` : ''}] ${c.text}`).join('\n') || 'none'}\n</success_criteria>\n\n` +
82
+ `Its tools: ${input.tools.length ? input.tools.join(', ') : 'none'}\n\n` +
83
+ `Feedback to learn from (newest first):\n${learn.map((i, n) => block(i, n + 1)).join('\n')}\n\n` +
84
+ (keep.length ? `Results people marked good (keep what made them good):\n${keep.map((i, n) => block(i, n + 1)).join('\n')}` : '');
85
+ const response = await model([{ role: 'user', content }], IMPROVE_PROMPT, []);
86
+ const text = response.content.filter((b) => b.type === 'text').map((b) => b.text ?? '').join('');
87
+ const match = /\{[\s\S]*\}/.exec(text);
88
+ let parsed = {};
89
+ try {
90
+ parsed = JSON.parse(match?.[0] ?? '');
91
+ }
92
+ catch {
93
+ throw new EvidenceError('The model didn’t give usable suggestions this time: try again.');
94
+ }
95
+ const str = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
96
+ const instructions = str(parsed.instructions, 30000) || input.instructions;
97
+ const have = new Set(input.criteria.map((c) => c.text.toLowerCase()));
98
+ const criteria = (Array.isArray(parsed.criteria) ? parsed.criteria : []).flatMap((raw) => {
99
+ const c = (raw ?? {});
100
+ const t = str(c.text, 300);
101
+ let kind = KINDS.includes(c.kind) ? c.kind : 'judge';
102
+ const value = str(c.value, 300);
103
+ if (kind !== 'judge' && !value)
104
+ kind = 'judge';
105
+ return t && !have.has(t.toLowerCase()) ? [{ id: randomUUID().slice(0, 8), text: t, kind, ...(kind !== 'judge' ? { value } : {}) }] : [];
106
+ }).slice(0, 4);
107
+ return {
108
+ summary: str(parsed.summary, 600),
109
+ changes: (Array.isArray(parsed.changes) ? parsed.changes : []).flatMap((raw) => {
110
+ const c = (raw ?? {});
111
+ const what = str(c.what, 300);
112
+ return what ? [{ what, why: str(c.why, 400) }] : [];
113
+ }).slice(0, 10),
114
+ instructions,
115
+ criteria,
116
+ open: (Array.isArray(parsed.open) ? parsed.open : []).map((o) => str(o, 300)).filter(Boolean).slice(0, 5),
117
+ basedOn: learn.length + keep.length,
118
+ };
119
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "loopengine",
3
- "version": "0.5.6",
3
+ "version": "0.5.8",
4
4
  "type": "module",
5
5
  "description": "Runtime for tool-using AI agents with a transparent ReAct loop.",
6
6
  "license": "MIT",