2026-10-07 14:56:13 +00:00
package main
import (
"context"
"errors"
"fmt"
2026-10-26 03:44:19 +00:00
"io"
2026-10-07 14:56:13 +00:00
"os"
2026-11-07 05:01:30 +00:00
"reflect"
2026-10-11 01:50:48 +00:00
"strconv"
2026-10-07 14:56:13 +00:00
2026-11-04 03:55:17 +00:00
"go.maximumdirect.net/ckconfig"
"go.maximumdirect.net/ckprompt"
commandkit "go.maximumdirect.net/commandkit"
2026-11-06 01:01:13 +00:00
configkit "go.maximumdirect.net/configkit"
promptkit "go.maximumdirect.net/promptkit"
2026-10-07 14:56:13 +00:00
)
type campaign struct {
2026-11-06 01:01:13 +00:00
PromptID string ` yaml:"prompt_id" `
ProfileID string ` yaml:"profile_id" `
Model string ` yaml:"model" `
2026-10-07 14:56:13 +00:00
}
2026-11-21 19:46:21 +00:00
type storageConfiguration struct {
Driver string ` yaml:"driver" `
Location string ` yaml:"location" `
}
2026-10-07 14:56:13 +00:00
type appConfiguration struct {
2026-11-21 19:46:21 +00:00
PromptKit promptkit . Settings ` yaml:"promptkit" `
Storage storageConfiguration ` yaml:"storage" `
DefaultCampaign string ` yaml:"default_campaign" `
Campaigns map [ string ] campaign ` yaml:"campaigns" `
2026-10-07 14:56:13 +00:00
}
2026-10-11 01:50:48 +00:00
type inspectionInput struct {
2026-10-07 14:56:13 +00:00
Campaign commandkit . Supplied [ string ]
2026-10-11 01:50:48 +00:00
Limit commandkit . Supplied [ int ]
2026-10-07 14:56:13 +00:00
}
2026-11-07 05:01:30 +00:00
type applicationCacheEntry struct {
selection ckconfig . Selection
campaign commandkit . Supplied [ string ]
result * configkit . Result [ appConfiguration ]
2026-10-11 21:54:39 +00:00
}
2026-10-11 01:50:48 +00:00
// runCache belongs to one invocation and is shared only where the application
// chooses to pass it to its loaders.
type runCache struct {
2026-11-07 05:01:30 +00:00
applications [ ] applicationCacheEntry
2026-10-17 19:06:05 +00:00
llmClient promptkit . LLMClient
}
type exampleLLMClient struct {
calls * int
}
func ( client * exampleLLMClient ) Generate ( context . Context , promptkit . GenerateRequest ) ( * promptkit . GenerateResponse , error ) {
if client . calls != nil {
( * client . calls ) ++
}
return & promptkit . GenerateResponse { Content : "Example response." } , nil
2026-10-07 14:56:13 +00:00
}
type restoreInput struct {
Campaign commandkit . Supplied [ string ]
Session string
}
2026-11-07 05:01:30 +00:00
type requestInputs struct {
Execution ckprompt . ExecutionInput ` json:"execution" `
Resources ckprompt . ResourceInput ` json:"resources" `
Inputs ckprompt . PromptInputs ` json:"inputs" `
}
2026-10-07 14:56:13 +00:00
type session struct {
ID string
Campaign string
Summary string
}
2026-10-26 03:44:19 +00:00
var errSessionNotFound = errors . New ( "saved session was not found" )
2026-10-11 01:50:48 +00:00
func campaignSelector ( ) commandkit . Flag [ * inspectionInput ] {
return commandkit . ValueFlag ( commandkit . FlagMeta { Name : "campaign" , Usage : "Select campaign inputs." } , ( * string ) ( nil ) , parseString ,
func ( input * * inspectionInput , value commandkit . Supplied [ string ] ) { ( * input ) . Campaign = value } )
2026-10-07 14:56:13 +00:00
}
2026-10-11 21:54:39 +00:00
func loadApplicationConfig ( ctx context . Context , selection ckconfig . Selection , input * inspectionInput , cache * runCache ) ( * configkit . Result [ appConfiguration ] , error ) {
2026-10-11 01:50:48 +00:00
if err := ctx . Err ( ) ; err != nil {
return nil , err
}
2026-10-11 21:54:39 +00:00
campaignInput := commandkit . Supplied [ string ] { }
if input != nil {
campaignInput = input . Campaign
}
if cache != nil {
2026-11-07 05:01:30 +00:00
for _ , cached := range cache . applications {
if reflect . DeepEqual ( cached . selection , selection ) && cached . campaign == campaignInput {
return cached . result , nil
}
2026-10-11 21:54:39 +00:00
}
2026-10-07 14:56:13 +00:00
}
2026-11-21 19:46:21 +00:00
definition := configkit . Definition [ appConfiguration ] {
Defaults : func ( ) appConfiguration {
return appConfiguration { DefaultCampaign : "spring" , Storage : storageConfiguration { Driver : "local" , Location : "./data" } , Campaigns : map [ string ] campaign {
"spring" : { PromptID : "briefing" , ProfileID : "spring" , Model : "spring-model" } ,
"autumn" : { PromptID : "briefing" , ProfileID : "autumn" , Model : "autumn-model" } ,
} }
2026-10-07 14:56:13 +00:00
} ,
2026-11-21 19:46:21 +00:00
Resolve : func ( value * appConfiguration , resolution * configkit . Resolution ) error {
name , chosen , err := selectedCampaign ( * value , commandkit . Supplied [ string ] { } )
if err != nil {
return nil
}
deps := [ ] configkit . Path { configkit . Keys ( "default_campaign" ) , configkit . Keys ( "campaigns" , name ) }
profilePath := configkit . Keys ( "promptkit" , "profiles" )
profileFound := false
for _ , profile := range value . PromptKit . Profiles {
if profile . ID == chosen . ProfileID {
profileFound = true
break
}
}
if ! profileFound {
value . PromptKit . Profiles = append ( value . PromptKit . Profiles , promptkit . ProfileSettings { ID : chosen . ProfileID , Backend : new ( "local" ) , Endpoint : new ( "https://example.invalid/v1" ) , Model : new ( chosen . Model ) , ExtraParams : map [ string ] any { "campaign" : name } } )
resolution . RecordNormalization ( profilePath , "Selected campaign profile" , deps ... )
}
promptPath := configkit . Keys ( "promptkit" , "prompts" )
for index := range value . PromptKit . Prompts {
prompt := & value . PromptKit . Prompts [ index ]
if prompt . ID != "briefing" {
continue
}
if chosen . PromptID != prompt . ID {
prompt . ID = chosen . PromptID
2026-11-21 20:53:36 +00:00
resolution . RecordNormalization ( promptPath , "Selected campaign prompt" , deps ... )
2026-11-21 19:46:21 +00:00
}
if prompt . DefaultProfile == nil {
prompt . DefaultProfile = new ( chosen . ProfileID )
resolution . RecordDerivedDefault ( promptPath . Index ( index ) . Key ( "default_profile" ) , "Selected campaign profile" , deps ... )
}
break
}
return nil
} ,
}
definition = promptkit . Configure ( definition , func ( value * appConfiguration ) * promptkit . Settings { return & value . PromptKit } )
resources := promptkit . SettingsInput ( configkit . Mapping ( "example resources" , map [ string ] any {
"collections" : map [ string ] any { "field-notes" : map [ string ] any {
"release_version" : "1" ,
"backends" : [ ] any { map [ string ] any { "id" : "demo" , "endpoint" : "https://example.invalid/v1" } } ,
"profiles" : [ ] any { map [ string ] any { "id" : "assistant" , "backend" : "field-notes/demo" , "model" : "example-model" } } ,
"prompts" : [ ] any { map [ string ] any { "id" : "briefing" , "default_profile" : "field-notes/assistant" , "inputs" : [ ] any { map [ string ] any { "name" : "topic" , "required" : true , "content_type" : "text/plain" , "description" : "Topic to brief" } } , "messages" : [ ] any { map [ string ] any { "role" : "user" , "content" : "Write a concise briefing about {{.topic}}." } } , "output" : map [ string ] any { "format" : "text" , "validation_mode" : "none" } } } ,
} } ,
"prompts" : [ ] any { map [ string ] any { "id" : "briefing" , "inputs" : [ ] any { map [ string ] any { "name" : "topic" , "required" : true , "content_type" : "text/plain" , "description" : "Topic to brief" } } , "messages" : [ ] any { map [ string ] any { "role" : "user" , "content" : "Write a concise briefing about {{.topic}}. {{if .mode}}{{input \"notes\"}}{{end}}" } } , "output" : map [ string ] any { "format" : "text" , "validation_mode" : "none" } } } ,
"backends" : [ ] any { map [ string ] any { "id" : "local" , "endpoint" : "https://example.invalid/v1" } } ,
} ) )
source := configkit . NoSource ( )
2026-10-11 21:54:39 +00:00
if selection . Config . Set {
source = configkit . File ( selection . Config . Value )
}
2026-11-21 19:46:21 +00:00
options := configkit . LayeredOptions [ appConfiguration ] { Definition : definition , Underlays : [ ] configkit . Underlay { promptkit . BundledOpenRouterUnderlay ( ) , { Inputs : [ ] configkit . Input { resources } } } }
2026-10-11 21:54:39 +00:00
if selection . Overlay . Set {
options . Overlay = selection . Overlay . Value
2026-11-21 19:46:21 +00:00
options . OverlayFilesystem = & configkit . FilesystemContext { Root : "." , BaseDir : "." }
2026-10-11 21:54:39 +00:00
}
if campaignInput . Set {
options . Overrides = [ ] configkit . Override { { Path : configkit . Keys ( "default_campaign" ) , Value : campaignInput . Value , Flag : "--campaign" } }
}
2026-11-07 05:01:30 +00:00
options . Overrides = append ( options . Overrides , selection . Overrides ... )
2026-11-21 19:46:21 +00:00
result , err := configkit . LoadLayered ( configkit . Input { Source : source } , options )
2026-10-11 21:54:39 +00:00
if err == nil && result != nil && cache != nil {
2026-11-07 05:01:30 +00:00
cache . applications = append ( cache . applications , applicationCacheEntry { selection : selection , campaign : campaignInput , result : result } )
2026-10-07 14:56:13 +00:00
}
return result , err
}
2026-10-11 01:50:48 +00:00
func loadPromptEngine ( ctx context . Context , selection ckconfig . Selection , input * inspectionInput , cache * runCache ) ( * promptkit . Engine , error ) {
application , err := loadApplicationConfig ( ctx , selection , input , cache )
2026-10-07 14:56:13 +00:00
if err != nil {
return nil , err
}
2026-11-21 19:46:21 +00:00
if _ , _ , err := selectedCampaign ( application . Config , commandkit . Supplied [ string ] { } ) ; err != nil {
2026-10-07 14:56:13 +00:00
return nil , err
}
2026-10-17 19:06:05 +00:00
var client promptkit . LLMClient = & exampleLLMClient { }
if cache != nil && cache . llmClient != nil {
client = cache . llmClient
}
2026-11-21 19:46:21 +00:00
return promptkit . NewFromConfig ( application , promptkit . RuntimeConfig { } , promptkit . WithLLMClient ( client ) )
2026-10-07 14:56:13 +00:00
}
2026-10-11 01:50:48 +00:00
func selectedCampaign ( configuration appConfiguration , supplied commandkit . Supplied [ string ] ) ( string , campaign , error ) {
name := configuration . DefaultCampaign
if supplied . Set {
name = supplied . Value
}
chosen , ok := configuration . Campaigns [ name ]
if ! ok {
return "" , campaign { } , fmt . Errorf ( "unknown campaign %q" , name )
2026-10-07 14:56:13 +00:00
}
2026-10-11 01:50:48 +00:00
return name , chosen , nil
2026-10-07 14:56:13 +00:00
}
2026-10-12 22:22:51 +00:00
func buildValidationRequest ( ctx context . Context , seed ckprompt . ValidationRequest , input * inspectionInput , cache * runCache ) ( promptkit . RunRequest , error ) {
application , err := loadApplicationConfig ( ctx , seed . Selection , input , cache )
if err != nil {
return promptkit . RunRequest { } , err
}
name , _ , err := selectedCampaign ( application . Config , input . Campaign )
if err != nil {
return promptkit . RunRequest { } , err
}
request := seed . Request
vars := make ( map [ string ] string , len ( request . Vars ) + 2 )
for key , value := range request . Vars {
vars [ key ] = value
}
if _ , supplied := vars [ "topic" ] ; ! supplied {
vars [ "topic" ] = name + " campaign planning"
}
if _ , supplied := vars [ "mode" ] ; ! supplied {
vars [ "mode" ] = ""
}
request . Vars = vars
return request , nil
}
2026-10-07 14:56:13 +00:00
func newApp ( ) ( * commandkit . App , error ) {
2026-10-17 19:06:05 +00:00
return newAppWithLLMClient ( & exampleLLMClient { } )
}
func newAppWithLLMClient ( client promptkit . LLMClient ) ( * commandkit . App , error ) {
2026-10-26 03:44:19 +00:00
return newAppWithEngineLoader ( client , loadPromptEngine , nil )
2026-10-19 19:56:33 +00:00
}
2026-10-26 03:44:19 +00:00
func newAppWithEngineLoader (
client promptkit . LLMClient ,
engineLoader func ( context . Context , ckconfig . Selection , * inspectionInput , * runCache ) ( * promptkit . Engine , error ) ,
smokeTest func ( context . Context , ckprompt . SmokeRequest , * inspectionInput , * runCache ) ( commandkit . Acquired [ * promptkit . SmokeTestReport ] , error ) ,
) ( * commandkit . App , error ) {
2026-10-17 19:06:05 +00:00
if client == nil {
client = & exampleLLMClient { }
}
2026-10-11 01:50:48 +00:00
limitDefault := 0
limitFlag := commandkit . ValueFlag ( commandkit . FlagMeta { Name : "limit" , Usage : "Override the application item limit." } , & limitDefault , strconv . Atoi ,
func ( input * * inspectionInput , value commandkit . Supplied [ int ] ) { ( * input ) . Limit = value } )
inputFactory := func ( ) * inspectionInput { return & inspectionInput { } }
2026-10-17 19:06:05 +00:00
stateFactory := func ( ) * runCache { return & runCache { llmClient : client } }
2026-10-11 01:50:48 +00:00
appScope := ckconfig . FromConfigKit ( "app" , "Application settings." , loadApplicationConfig )
2026-11-07 05:01:30 +00:00
appScope . Features . Overrides = true
2026-11-21 19:46:21 +00:00
storageScope := ckconfig . FromConfigKitSubtree ( "storage" , "Storage settings." , configkit . Keys ( "storage" ) , loadApplicationConfig )
storageScope . Features . Overrides = true
2026-10-19 19:56:33 +00:00
engineScope := ckprompt . ConfigScope ( engineLoader )
2026-10-11 01:50:48 +00:00
configCommand := ckconfig . Command ( ckconfig . Suite [ * inspectionInput , * runCache ] {
NewInput : inputFactory ,
NewState : stateFactory ,
CheckInput : func ( scope string , _ ckconfig . Selection , input * inspectionInput ) error {
if scope == "app" && input . Campaign . Set && ! input . Limit . Set {
return errors . New ( "application campaign inspection requires --limit" )
}
return nil
} ,
Selectors : [ ] ckconfig . Selector [ * inspectionInput ] {
2026-11-21 19:46:21 +00:00
{ Binding : campaignSelector ( ) , AgainstName : "against-campaign" , Scopes : [ ] string { "app" , "storage" , "promptkit" } } ,
2026-11-07 04:36:05 +00:00
{ Binding : limitFlag , AgainstName : "against-limit" , Scopes : [ ] string { "app" } } ,
2026-10-11 01:50:48 +00:00
} ,
2026-11-21 19:46:21 +00:00
Scopes : [ ] ckconfig . Scope [ * inspectionInput , * runCache ] { appScope , storageScope , engineScope } ,
2026-10-07 14:56:13 +00:00
} )
2026-10-19 19:56:33 +00:00
definitions := ckprompt . FromEngine ( engineLoader )
2026-10-11 01:50:48 +00:00
definitions . NewInput = inputFactory
definitions . NewState = stateFactory
definitions . Selectors = [ ] commandkit . Flag [ * inspectionInput ] { campaignSelector ( ) }
2026-10-19 19:56:33 +00:00
definitions = ckprompt . WithRequestValidation ( definitions , engineLoader , buildValidationRequest )
2026-11-07 05:01:30 +00:00
definitions = ckprompt . WithRequestPreparation ( definitions , engineLoader ,
func ( ctx context . Context , seed ckprompt . PreparationRequest , input * inspectionInput , cache * runCache ) ( promptkit . RunRequest , error ) {
return buildValidationRequest ( ctx , ckprompt . ValidationRequest { Selection : seed . Selection , Request : seed . Request , Namespaces : seed . Namespaces } , input , cache )
} )
2026-10-19 19:56:33 +00:00
definitions = ckprompt . WithSmokeTesting ( definitions , engineLoader , nil )
2026-11-07 05:01:30 +00:00
definitions = ckprompt . WithNamespaces ( definitions , promptkit . Namespaces { } )
2026-10-26 03:44:19 +00:00
if smokeTest != nil {
definitions . SmokeTest = smokeTest
}
2026-11-07 04:27:28 +00:00
definitionDeclarations := ckprompt . Declarations ( definitions )
2026-11-07 05:01:30 +00:00
resources := ckprompt . NewResourceFlags ( func ( input * requestInputs ) * ckprompt . ResourceInput { return & input . Resources } )
execution := ckprompt . NewExecutionFlags ( func ( input * requestInputs ) * ckprompt . ExecutionInput { return & input . Execution } )
inputs := ckprompt . NewPromptInputFlags ( func ( input * requestInputs ) * ckprompt . PromptInputs { return & input . Inputs } )
requestFlags := append ( [ ] commandkit . Flag [ requestInputs ] { resources . Prompt , resources . Profile } , execution . All ( ) ... )
requestFlags = append ( requestFlags , inputs . All ( ) ... )
requestInspect := commandkit . NewCommand ( commandkit . CommandSpec [ requestInputs ] {
Name : "inspect" , Summary : "Inspect application-owned request inputs." , Flags : requestFlags ,
Run : func ( invocation commandkit . Invocation , input requestInputs ) commandkit . Outcome {
_ = invocation . Reporter ( ) . Report ( commandkit . Report { Value : input } )
return commandkit . Success ( )
} ,
} )
2026-10-07 14:56:13 +00:00
2026-10-11 01:50:48 +00:00
store := map [ string ] session {
"session-42" : { ID : "session-42" , Campaign : "spring" , Summary : "A synthetic planning session." } ,
}
restore := commandkit . NewCommand ( commandkit . CommandSpec [ restoreInput ] {
2026-10-07 14:56:13 +00:00
Name : "restore" ,
2026-10-11 01:50:48 +00:00
Summary : "Restore a saved session." ,
Flags : [ ] commandkit . Flag [ restoreInput ] { commandkit . ValueFlag ( commandkit . FlagMeta { Name : "campaign" , Usage : "Campaign owning the session." } , ( * string ) ( nil ) , parseString ,
func ( input * restoreInput , value commandkit . Supplied [ string ] ) { input . Campaign = value } ) } ,
Arguments : [ ] commandkit . Argument [ restoreInput ] { commandkit . ValueArgument ( commandkit . ArgumentMeta { Name : "ID" , Usage : "Session identifier." } , true , parseString ,
func ( input * restoreInput , value commandkit . Supplied [ string ] ) { input . Session = value . Value } ) } ,
2026-10-07 14:56:13 +00:00
Run : func ( invocation commandkit . Invocation , input restoreInput ) commandkit . Outcome {
2026-10-26 03:44:19 +00:00
reporter := invocation . Reporter ( )
2026-10-11 01:50:48 +00:00
if err := invocation . Context . Err ( ) ; err != nil {
2026-10-26 03:44:19 +00:00
return commandkit . Failure ( "Session restore was canceled." ) . WithCause ( err )
2026-10-11 01:50:48 +00:00
}
application , err := loadApplicationConfig ( invocation . Context , ckconfig . Selection { } , nil , nil )
if err != nil {
2026-10-26 03:44:19 +00:00
return commandkit . Failure ( "Could not load application configuration." ) . WithCause ( err )
2026-10-11 01:50:48 +00:00
}
name , _ , err := selectedCampaign ( application . Config , input . Campaign )
if err != nil {
2026-10-26 03:44:19 +00:00
return commandkit . Failure ( err . Error ( ) ) . WithCause ( err )
2026-10-11 01:50:48 +00:00
}
record , ok := store [ input . Session ]
if ! ok {
2026-10-26 03:44:19 +00:00
return commandkit . Outcome { Kind : commandkit . OutcomeDomain , Status : 4 , Domain : "session_not_found" , Cause : errSessionNotFound , Explanation : commandkit . Explanation { Message : "Saved session was not found." } }
2026-10-11 01:50:48 +00:00
}
if record . Campaign != name {
2026-10-26 03:44:19 +00:00
cause := fmt . Errorf ( "session belongs to campaign %q" , record . Campaign )
return commandkit . Outcome { Kind : commandkit . OutcomeDomain , Status : 3 , Domain : "campaign_mismatch" , Cause : cause , Explanation : commandkit . Explanation { Message : "Session campaign does not match the selected campaign." } }
2026-10-11 01:50:48 +00:00
}
2026-10-26 03:44:19 +00:00
_ = reporter . RenderOutput ( func ( writer io . Writer ) error {
_ , err := fmt . Fprintf ( writer , "restored %s: %s\n" , record . ID , record . Summary )
return err
} )
2026-10-11 01:50:48 +00:00
return commandkit . Success ( )
2026-10-07 14:56:13 +00:00
} ,
} )
2026-10-19 19:56:33 +00:00
declarations := [ ] commandkit . Declaration {
2026-10-11 01:50:48 +00:00
configCommand ,
2026-11-03 04:09:27 +00:00
commandkit . Completion ( "composed-example" ) ,
2026-10-11 01:50:48 +00:00
commandkit . Group ( "session" , "Manage saved sessions." , restore ) ,
2026-11-07 05:01:30 +00:00
commandkit . Group ( "request" , "Inspect application-owned request inputs." , requestInspect ) ,
2026-10-19 19:56:33 +00:00
commandkit . Alias ( "list collections" , "promptkit list collections" ) ,
commandkit . Alias ( "promptkit list bundles" , "promptkit list collections" ) ,
commandkit . Alias ( "pk" , "promptkit" ) ,
commandkit . Alias ( "smoke" , "promptkit test" ) ,
commandkit . FlagAliasFor ( "promptkit show prompt" , "--fmt" , "--format" ) ,
commandkit . FlagAlias ( "--hlep" , "--help" ) ,
}
2026-11-07 04:27:28 +00:00
declarations = append ( declarations , definitionDeclarations ... )
2026-10-19 19:56:33 +00:00
return commandkit . New ( commandkit . Identity { Name : "composed-example" , Version : "1.0" } , declarations ... )
2026-10-07 14:56:13 +00:00
}
2026-10-11 01:50:48 +00:00
func parseString ( raw string ) ( string , error ) { return raw , nil }
2026-10-07 14:56:13 +00:00
func main ( ) {
app , err := newApp ( )
if err != nil {
fmt . Fprintln ( os . Stderr , err )
os . Exit ( 1 )
}
outcome := app . Execute ( context . Background ( ) , os . Args [ 1 : ] , commandkit . Streams { Out : os . Stdout , Err : os . Stderr } )
if outcome . Status != 0 {
os . Exit ( outcome . Status )
}
}